var reloadPosts = function(){
	$.ajax({
		url: 'recent_posts.php',
		success: function(data) {
			$('#posts_holder').html(data);
			$('#forum_list').addClass('current');
		}
	});
};

$(document).ready(function() {
  if ($(window).width() > 1024) {
   $('.share-follow-tab').show()
  }
  $('a.follow-tag').live('click', function(){
	  if (!$(this).attr('rel')) {
		return true;
	  }
  var self = $(this);
  $.post('index.php', {action: 'follow', tag: $(this).attr('rel')}, function(data){
		self.removeClass('follow-tag').addClass('unfollow-tag');
		self.text('Спри');
  }, 'text/plain');
	return false;
  });
  
  $('a.unfollow-tag').live('click', function(){
  var self = $(this);
  $.post('index.php', {action: 'unfollow', tag: $(this).attr('rel')}, function(data){
		self.removeClass('unfollow-tag').addClass('follow-tag');
		self.text('Следвай');
  }, 'text/plain');
	return false;
  });
	initRailScroll()
		// correct the poll header
	var question = $('.question')[0];
	if (question && $(question).text().length > 28) {
		var index = $(question).text().indexOf(' ', 25);
		var first = $(question).text().substring(0,index);
		var second = $(question).text().substring(index);
		$(question).text(first);
		$(question).parent().append('<br/>');
		$(question).parent().append('<span class="question">' + second +'</span>');
	}
	// show next and prev tab
	$('#right_column > .r_tabs').eq(0).find('.tabs a').click(function() {
		$(this).parent().children('a').removeClass('current');
		$(this).addClass('current');
		$('div.list_wrapper').hide();
		$('.'+$(this).attr('id')+'.list_wrapper').show();
	});
	
	$('#keyword').focus(function(){
		if ($(this).val() == 'Търсена дума')
			$(this).val('');
	});
	$('#keyword').blur(function(){
		if ($(this).val() == '')
			$(this).val('Търсена дума');
	}); 
	$('#keyword').autocomplete('/ajax_search.php', {limit: 50, scroll: false, width:260, selectFirst: false, formatTerm: function(term){return escape(term)}}).result(function(){
		$('#search_form').submit()
	});
	
	// show hide comments
	$('a.show_comment').toggle( 
	  function() {
		$(this).removeClass('show_comment').addClass('hide_comment');
		$('ul#comments').toggle('slow');
		$('div#pager').toggle('slow');
	  },
	  function() {
		$(this).removeClass('hide_comment').addClass('show_comment');
		$('ul#comments').toggle('slow');
		$('div#pager').toggle('slow');
	  }
	);
	
	// show or hide the login form
	$('.link-show-login').click(function(){
		$('#user_login').slideDown('slow');
	});
	$('#link-hide-login').click(function(){
		$('#user_login').slideUp('slow');
	});
	
	if (parseInt($('#pm_count').text()) > 0) {
		$('#pm_count_holder').show();
	} else {
		$('#pm_count_holder').hide();
	}
	
	$('#notifications').hover(
		function(){
			$.ajax({
				url: 'notifications.php'
				//,success: function(){$('#user_notifications_link small').html("0");}
			});
		},
		function(){}
	);
	
	scrollInterval = window.setInterval(autoscroll, 10000);
	
	$('div.box_articles').hover(function(){
		$(this).find('.news_scroll').css({visibility:'visible'});
	}, function(){
		$(this).find('.news_scroll').css({visibility:'hidden'});
	});
	
	$('.news_scroll').parent().each(function(){
		var thisStep = 1;
		$(this).children('.news_scroll').click(function(){
			var rel = $(this).attr('rel');
			if (rel == 'prev' && thisStep > 1) {
				thisStep--;
				movement = '+=300';
			} else if(rel == 'next' && thisStep <10) {
				thisStep++;
				movement = '-=300';
			} else {
				return false;
			}
			
			$(this).parents('.box_articles').find('.news_scroller').children('.news_scroller_container').animate({
				left: movement
			}, 1000);
			
			return false;			
		});
	});
	
	var pdfPage = 1;
	$('#pdf-page').css('width', ($('#pdf-page a').length * 240) + 'px');
	$('#pdf-page-prev').click(function(){
		if (autoPagePdfInterval) {
				$('#pdf-page-timer').css('width', '2px');
				window.clearInterval(autoPagePdfInterval);
			}
		if (pdfPage > 1) {
			pdfPage--;
			
			$('#pdf-page').animate({left: '+=240px'}, 1000, 'swing', function(){
				window.setTimeout(function(){autoPagePdfInterval = window.setInterval(autoPagePdf, 50)}, 1000);
			});
		} else {
			pdfPage = $('#pdf-page a').length;
			$('#pdf-page').animate({left: -((pdfPage-1) * 240) + 'px' }, 1000, 'swing', function(){
				window.setTimeout(function(){autoPagePdfInterval = window.setInterval(autoPagePdf,50)}, 1000);
			});
		}
		
		return false;
	});
	
	$('#pdf-page-next').click(function(){
		if (autoPagePdfInterval) {
				$('#pdf-page-timer').css('width', '2px');
				window.clearInterval(autoPagePdfInterval);
			}
		if (pdfPage < $('#pdf-page a').length) {
			pdfPage++;
			$('#pdf-page').animate({left: '-=240px'}, 1000, 'swing', function(){
				window.setTimeout(function(){autoPagePdfInterval = window.setInterval(autoPagePdf,50)}, 1000);
			});
		} else {
			pdfPage = 1;
			$('#pdf-page').animate({left: '0px'}, 1000, 'swing', function(){
				window.setTimeout(function(){autoPagePdfInterval = window.setInterval(autoPagePdf,50)}, 1000);
			});
		}
		
		return false;
	});
	
	autoPagePdfInterval = window.setInterval(autoPagePdf, 50);
	var c = document.cookie.split(';');
	var cookies = {};
	for(i in c) {
		var a = c[i].split('=');
		if (a[0].indexOf('_cr') !== -1) {
			var id = a[0].replace('_cr[', '').replace(']', '').replace(/^\s+|\s+$/g,"");
			cookies[id] = a[1];
		}
	}
	
	$('img.rate_comment').each(function(){
		if (!cookies[$(this).attr('rel')]) {
			var action = ($(this).attr('src').indexOf('_up') > -1) ? 'crateup' : 'cratedown';
			$(this).css('cursor', 'pointer');
			$(this).hover(
				function(){
					var src = $(this).attr('src').replace('.gif', '_active.gif');
					$(this).attr('src', src);
				},
				function(){
					var src = $(this).attr('src').replace('_active.gif', '.gif');
					$(this).attr('src', src);
				}
			);
			$(this).click(function(){
				rate_comment($(this).attr('rel'), action, this);
				$(this).unbind('click');
				$(this).css('cursor', 'default');
			});
		} else {
			if (cookies[$(this).attr('rel')] == 'up') {
				var src = $(this).attr('src').replace('up.gif', 'up_active.gif');
			} else {
				var src = $(this).attr('src').replace('down.gif', 'down_active.gif');
			}
			$(this).attr('src', src);
			$(this).css('cursor', 'default');
			$(this).css('cursor', 'default');
		}
	});
	
	if ($('div.banner_300').height() < 10) {
		$('#m_downloaded').css('margin-top', '0px');
	}
	
	var tabsSwitch = function() {
		var self = this;
		var scope = $(self).parent();
		var current = 'most_' + $('a.current', scope).removeClass('current').attr('rel');
		var new_current = 'most_' + $(self).attr('rel');
		$('#' + current).hide();
		$('#' + new_current).fadeIn();
		$(self).addClass('current');
	
	}
	$('.r_tabs_second > .tabs > a').click(tabsSwitch);
	$('#most_fixer > a').click(tabsSwitch);
});

var autoPagePdfInterval = null;
var autoPagePdf = function(){
	var step = 3;
	currentWidth = $('#pdf-page-timer').width();
	if (currentWidth+step >= 300) {
		currentWidth = 1;
		$('#pdf-page-timer').css('width', step + 'px')
		$('#pdf-page-next').click();
		return;	
	}
	currentWidth+=step;
	$('#pdf-page-timer').css('width', currentWidth + 'px');
}

var step = 3;

var scrollTo = function(toStep, obj) {
	$('.footer_pager a').removeClass('current');
	$(obj).addClass('current');
	if (toStep == step)
		return false;
	
	if (toStep > step) {
		$('#items_container').animate({
			left: '-=' + (800 * (toStep - step))
		}, 1000);
	} else {
		$('#items_container').animate({
			left: '+=' + (800 * (step - toStep))
		}, 1000);
	}
	step = toStep;
};

var scrollLeft = function(){
	if (step == 1) {
		scrollTo(5, $('.footer_pager a:eq(4)'));
		return ;
	}
	
	if (scrollInterval) {
		window.clearInterval(scrollInterval);
		window.setTimeout(function(){scrollInterval = window.setInterval(autoscroll, 10000);}, 15000);
	}
	
	step--;
	$('.footer_pager a').removeClass('current');
	$('.footer_pager a:eq(' + (step-1) + ')').addClass('current');
	$('#items_container').animate({
		left: '+=800'
	}, 1000);
};

var scrollRight = function(){
	if (step == 5) {
		scrollTo(1, $('.footer_pager a:eq(0)'));
		return ;
	}
	
	if (scrollInterval) {
		window.clearInterval(scrollInterval);
		window.setTimeout(function(){scrollInterval = window.setInterval(autoscroll, 10000);}, 15000);
	}
	
	step++;
	$('.footer_pager a').removeClass('current');
	$('.footer_pager a:eq(' + (step-1) + ')').addClass('current');
	$('#items_container').animate({
		left: '-=800'
	}, 1000);
};

showTopics = function(i, obj, prefix){
	$(obj).parent().parent().find('a').removeClass('current');
	$(obj).addClass('current');
	
	for (n = 0; n < 4; n++) {
		if (n == i)
			$('#' + prefix + '_list_' + n).show();
		else
			$('#' + prefix + '_list_' + n).hide();
	}
}

function increaseFontSize() {
	var max = 36;
   var p = document.getElementsByTagName('p');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 13;
      }
      if(s!=max) {
         s += 1;
      }
      p[i].style.fontSize = s+"px"
   }
}
function decreaseFontSize() {
	var min = 1;
   var p = document.getElementsByTagName('p');
   for(i=0;i<p.length;i++) {
      if(p[i].style.fontSize) {
         var s = parseInt(p[i].style.fontSize.replace("px",""));
      } else {
         var s = 12;
      }
      if(s!=min) {
         s -= 1;
      }
      p[i].style.fontSize = s+"px"
   }
}

function rate_news(id,action,obj) {
	if (obj == undefined) {
		obj = '.rate-results';
		var obj2 = '.rate-label';
	} else {
		var obj2 = obj + 'label';
	}
	var placeholder = obj;
	
	$.ajax({
		url: "modules.php?modname=rate&id=" + id + "&action=" + action,
		success: function(data) {
				$(placeholder).html(data);
				if (parseInt(data) == 1)
					$(obj2).html(' препоръка');
				else
					$(obj2).html(' препоръки');
			}
	});
	return false;
};



function rate_comment(id, action, obj)
{
	$(obj).css('cursor', 'default');
	$.ajax({
		url: "modules.php?modname=rate&id=" + id + "&action=" + action,
		success: function(data) {
				$(obj).parent().children('span').html('<b>' + data + '</b>');
				$(obj).parent().parent().find('img.rate_comment').unbind('mouseenter').unbind('mouseleave').unbind('hover');
			}
	});
	return false;
}

var autoscroll = function(){
	
	toStep = step + 1;
	if (toStep > 5)
		toStep = 1;
	
	scrollTo(toStep, $('.footer_pager a:eq(' +(toStep-1)+')'));
	
};

var scrollInterval = null;

var loadVotes = function(){
		var news = '[';
		$('.rate-results').each(function(){
			news += $(this).attr('rel');
			news += ','; 
		});
		news += '0]';
		$.post('modules.php?modname=rate&action=getall', 'ids=' + news, function(data){
			for (i in data) {
				html = $('<span class="rate-fade-id" style="display:none"> '+ data[i].votes+'</span>')
				$('#rate' + data[i].id).html(html);
				$('#rate' + data[i].id + 'label').text(' ' + data[i].html);
			}
			$('.rate-fade-id').fadeIn().attr('style', '');
		}, 'json');
};

  function initRailScroll() {
    if ($('.share-follow-tab').length === 0 || ($.browser.msie && parseInt($.browser.version, 10) < 7)) {
      return;
    }

    var $window = $(window);
    var descripY = parseInt($('.tiny_mce').offset().top, 10) - 20;
    var h = $('.wrapper-reset-relative').children(':first').height();
    if (h>=200) {
		descripY += 108;
	}
    var $postShare = $('.share-follow-tab');
    var pullX = $postShare.css('margin-left');

    $window.data('scrollBound', false);
	var oldLeft = $postShare.css('left');
	
    function positionShareScroll() {
      var scrollY = $window.scrollTop();
      var footerY = parseInt($('#footer_links').offset().top, 10);
      var height = parseInt($postShare.height(), 10);
      var fixedShare = $postShare.css('position') == 'fixed';
	  
	  
      if (scrollY > descripY && (scrollY + 20 + height) > footerY) {
		$postShare.stop().css({
		  top: -(scrollY + 20 + height - footerY)
        });
      } else if (scrollY + 50 > descripY) {
		$postShare.stop().css({
          top: '20px'
        });
      } else {
	
        $postShare.css({
          top: (descripY - 375 - scrollY + height)
        });
      }
    }
	
	$window.data('scrollBound', true).bind('scroll.positionShare', function() {
            positionShareScroll();
          });
    positionShareScroll();
  }

