$(document).ready(function(){
	/*
	if($('#agrFilter').length) {
		$(window).scroll(function(){
			
			if  ($(window).scrollTop() > $("#bodyarea").offset().top){
			   $("#agrFilter").css("position", "fixed");
			   $("#agrFilter").css("top", "0");
			   $('#agrFilter').css('height', '136');
			}
			
			if  ($(window).scrollTop() <= $("#bodyarea").offset().top){
			   $("#agrFilter").css("position", "relative");
			   $("#agrFilter").css("top", $("#bodyarea").offset);
			   $('#agrFilter').css('height', '87');
			}
		}); 
	}
	*/
	if($('#selectCity').length) {
		
		jQuery('#offersContainer').onScrollBeyond(
			function() {
			    offersPage += 1;
			    loadOffers();
			}
		);
		
		var config = {
			timeout: 10, // number = milliseconds delay before onMouseOut
			out: selectMenuOut // function = onMouseOut callback (REQUIRED)
		};
		$('#selectCity').hoverIntent( config );
	
		
		
		$('#selectCity .select').click(function(){
			$('#selectCity ul').toggle();
			return false;
		});
		
		$('#selectCity ul li a').click(function(){
			var text = $(this).html();
			var id = $(this).attr('href').replace('#','');
			
			$.cookie('aggre_city', id, { expires: 365 });
			
			$('#selectCity .select span').html(text);
			$('#selectCity #cityID').val(id);
			$('#selectCity ul').hide();
			$('#offersContainer').html('');
			
			offersPage = 1;
			loadOffers();
			
			return false;
		});
		
		$(".checkbox input").change(function(){
			$('#offersContainer').html('');
			
			offersPage = 1;
			loadOffers();
		})
	}
	
	if($('#userOnlineBaloonButton')){
		var userOnlineA = 0;
		$('#userOnlineBaloonButton').click(function(){
			if(userOnlineA == 0){
				$('#userOnlineBaloonButton').addClass('userOnlineBaloonButtonClicked');
				userOnlineA = 1;
			}
			else {
				$('#userOnlineBaloonButton').removeClass('userOnlineBaloonButtonClicked');
				userOnlineA = 0;
			}
			$('#userOnlineBaloon').toggle();
			return false;
		});

		$("body").click(function(e){
			$('#userOnlineBaloonButton').removeClass('userOnlineBaloonButtonClicked');
			userOnlineA = 0;
			$('#userOnlineBaloon').hide();

		});
	}

	if( $("#names #search_input_names") ) {
		$("#names").click(function(){
			if($("#names").val() == $("#names").attr('title') || $("#names").val() == "" ) $("#names").val('');
		});
		$("#names").blur(function(){
			if($("#names").val() == "") $("#names").val( $("#names").attr('title') );
		});
	}

	if($('#showOnlineUsers')){
		var activ1 = 0;
		$('#showOnlineUsers').click(function(){
			$('#showOnlineUsersDiv').toggle();

			if(activ1 == 0){
				$('#showOnlineUsers').addClass('showOnlineUsersA');
				activ1 = 1;
			}
			else {
				$('#showOnlineUsers').removeClass('showOnlineUsersA');
				activ1 = 0;
			}
			return false;
		});
	}
	if($('#showBDUsers')){
		var activ2 = 0;
		$('#showBDUsers').click(function(){
			$('#showBDUsersDiv').toggle();
			if(activ2 == 0){
				$('#showBDUsers').addClass('showOnlineUsersA');
				activ2 = 1;
			}
			else {
				$('#showBDUsers').removeClass('showOnlineUsersA');
				activ2 = 0;
			}
			return false;
		});
	}

	/*----------------------------------------------------------------------------------------*/
	/* Start clock */
	var options = {
		format: '%H:%M' // 12-hour with am/pm
	}

	$("#liveClock").jclock(options);

	var now = new Date();
	day = now.getDate();
	month = now.getMonth()+1;
	year = now.getFullYear();

	$("#liveData").html(day+'.'+month+'.'+year);
	/*----------------------------------------------------------------------------------------*/

	/*----------------------------------------------------------------------------------------*/
	var isOver = false;
	var over;

	/* Drop Down in main menu */
	$('#hoverMenu').mouseenter(function(){
		isOver = true;
	});
	$('#hoverMenu').mouseleave(function(){
		isOver = false;
		setTimeout(function(){
			if (isOver == false) {
				$('#hoverMenu').hide();
				$("#menu"+over).removeClass('select');
				$("#menu"+curCat).addClass('select');
			}
		}, 200);
	});
	$('#categories').mouseleave(function(){

		setTimeout(function(){
			if (isOver == false) {
				$('#hoverMenu').hide();
				$("#menu"+over).removeClass('select');
				$("#menu"+curCat).addClass('select');
			}
		}, 200);
		isOver = false;
	});
	function menuOut(){
		//$('#hoverMenu').hide();
		//$("#menu"+over).removeClass('select');
		//$("#menu"+curCat).addClass('select');
	};

	function menuIn(){

		$("#menu"+over).removeClass('select');
		$("#menu"+curCat).removeClass('select');

		over = $(this).attr("href").replace('#','');

			if(over != 'http://www.bg-mamma.com/index.php'){
				$('#hoverMenu').show();
				// Ajax load categories
				$.ajax({
				  url: 'http://www.bg-mamma.com/categories.php?id='+over+'',
				  success: function(data) {
				    $('#hoverContent').html(data);
				    $("#menu"+over).addClass('select');
				  }
				});
			}else {
				$('#hoverMenu').hide();
			}
			isOver = true;

	};
	var config = {
	     over: menuIn, // function = onMouseOver callback (REQUIRED)
	     timeout: 10, // number = milliseconds delay before onMouseOut
	     out: menuOut // function = onMouseOut callback (REQUIRED)
	};
	$('#categories a').hoverIntent( config );

	$('#categories a').click(function(){
		over = $(this).attr("href").replace('#','');
		if(over != 'http://www.bg-mamma.com/index.php' && over != '/catalog/'){
			return false;
		}
	});
	//$('#wraper').mouseover(function(){
	//	if (isOver == false) {
	//			$('#hoverMenu').slideUp("fast");
	//	}
	//});
	/* Drop Down in main menu */

	/*----------------------------------------------------------------------------------------*/
	/* Drop Down in searches */

	var a = 'down';
	$('#topSearch a.select').click(function(){
		if (a == 'down') {
			$(this).css("background-image", "url(http://static.bg-mamma.com/img/1/search_select_backUp.gif)");
			a = 'up';
		}
		else if (a == 'up') {
			$(this).css("background-image", "url(http://static.bg-mamma.com/img/1/search_select_back.gif)");
			a = 'down';
		}
		$('#topSearch .dropdown').toggle();

		return false;
	});

	$('#topSearch .dropdown a').click(function(){
		var select = $(this).attr("href").replace('#','');
		$('#topSearch .in').val(select);
		if(select != 5 || select != 6){
			$('#topicI').remove();
			$('#brdI').remove();
		}
		$('#topSearch .dropdown').hide();
		$('#topSearch a.select').css("background-image", "url(http://static.bg-mamma.com/img/1/search_select_back.gif)");
		a = 'down';
		$('#topSearch a.select').html( $(this).html() );
		return false;
	});

	$("body").click(function(e){
		$('#topSearch a.select').css("background-image", "url(http://static.bg-mamma.com/img/1/search_select_back.gif)");
		a = 'down';
		$('#topSearch .dropdown').hide();
	});


	/*----------------------------------------------------------------------------------------*/

	/*----------------------------------------------------------------------------------------*/
	/*if( $('#actualno') ){

		$('#actualnoContent').cycle({
	        fx: 'scrollHorz',
	        speed: 600,
			timeout: 0,
	        next: '#actualnoNext',
	        prev: '#actualnoPrev',
	        pager: '#buttons',
	        pagerAnchorBuilder: function(idx, slide) {
	            // return selector string for existing anchor
	            return '#buttons a:eq(' + idx + ')';
	        }
	    });


	}*/
	/*----------------------------------------------------------------------------------------*/

	/*----------------------------------------------------------------------------------------*/

	$("#share a").mouseover(function(){
         $(this).effect( "bounce",
          {times:1}, 300 );
     });

	/*----------------------------------------------------------------------------------------*/

	/*----------------------------------------------------------------------------------------*/
	/* news in pink forum box */
	if ($('.pinkNewsContentThumbs')) {
		$('.pinkNewsContentThumbs .thumb > img').hide();
		$('.pinkNewsContentThumbs .thumb > img:first').show();

		var slide = 1;
		var t;
		function pinkBlockNews(){
			$('.pinkNewsContentThumbs .thumb > img').hide();
			$('.pinkNewsContentThumbs .links > a').removeClass('select');
			$('.pinkNewsContentThumbs .thumb #ti'+slide).show();
			$('.pinkNewsContentThumbs .links #t'+slide).addClass('select');

			if( slide < 3) slide++;
			else slide = 1;
			// start rowing
			t = setTimeout(function(){pinkBlockNews();}, 5000);
		}

		pinkBlockNews();
		$('.pinkNewsContentThumbs a').mouseout(function(){
			t = setTimeout(function(){pinkBlockNews();}, 5000);
		});
		$('.pinkNewsContentThumbs a').mouseover(function(){
			var num = $(this).attr('id').replace('t', '');
			slide = num;
			$('.pinkNewsContentThumbs .thumb > img').hide();
			$('.pinkNewsContentThumbs .links > a').removeClass('select');
			$('.pinkNewsContentThumbs .thumb #ti'+num).show();
			$('.pinkNewsContentThumbs .links #t'+num).addClass('select');
			clearTimeout(t);
		});
	}
	/*----------------------------------------------------------------------------------------*/

	/*----------------------------------------------------------------------------------------*/
	/* Gallery Home Block */
	/*var secondGallery = 0;
	if ($('#galleryHome')) {
		$(function(){
			$("#galleryHome").tabs();
		});

		$('#ghScroll-1').cycle({
	        fx: 'scrollHorz',
	        speed: 600,
			timeout: 0,
	        next: '#ghNext-1',
	        prev: '#ghPrev-1'
	    });

		if(secondGallery == 0) {
			$('#galleryHomeClick-2').click(function(){
				$('#ghScroll-2').cycle({
			        fx: 'scrollHorz',
			        speed: 600,
					timeout: 0,
			        next: '#ghNext-2',
			        prev: '#ghPrev-2'
			    });
				secondGallery = 1;
			});
		}
	}*/

	/*----------------------------------------------------------------------------------------*/

	/*----------------------------------------------------------------------------------------*/
	/* nice selects in calculators form */
	if($('#calculators')){
		$('#calculators select').uniform();
	}
	/*----------------------------------------------------------------------------------------*/

	$('.votingname').click(function(){
		id = $(this).attr('rel');
		$.ajax({
			url: 'index.php?action=namesVote;id='+id+'',
			success: function(data) {
				if(data == '0') alert('Вече сте гласували за това име!');

				if ( $('#numLikes') && data == '1' ){
					newVal = ($('#numLikes').html()*1)+1;
					$('#numLikes').html(newVal);
				}
			}
		});
		return false;
	});

	/*----------------------------------------------------------------------------------------*/
	/* Gallery Home Block */
	var secondGallery = 0;
	if ($('#top10_names')) {
		$(function(){
			$("#top10_names").tabs();
		});
	}

	/*----------------------------------------------------------------------------------------*/



	if($("#debug_info")){
		$("#debug_info a").click(function(){
			$("#hidden_queries").toggle();
			return false;
		});
	}

	if($("#sponsoredNames")){
		$("#sponsoredNames").change(function(){
			chars = 44 - ($("#sponsoredNames").val().length)*1;
			$("#chars").html(chars);
		});
		$("#sponsoredNames").keypress(function(){
			chars = 44 - ($("#sponsoredNames").val().length)*1;
			$("#chars").html(chars);
		});
		$ ("#sponsoredNames").bind ("input paste", function (e) {
			chars = 44 - ($("#sponsoredNames").val().length)*1;
			$("#chars").html(chars);
		});
	}


	$('.markread').click(function(){
		var id = $(this).attr('rel');
		$('#log-'+id).children("td").removeClass("bolded");

		if(id){
			$.get('/catalog/markRead/'+id, function(data) {
				var number = $('#unreadNumber').html()*1;
				$('#unreadNumber').html(number-1);
		        });
		}
	});
});

//BEGIN : Increase/Decrease Font
function changeFontSize(increase)
{
	var fontText = document.getElementById('fontText');
	var dsi = fontText.style.fontSize;
	if (dsi == '')
	{
		dsi =  12;
	}
	else
	{
		      dsi = parseInt(fontText.style.fontSize.replace("px",""));
	}

		if (increase == 0 && dsi < 16) {
			dsi++;
		}
		else if (dsi > 10 ){
			dsi--;
		}

fontText.style.fontSize=dsi +"px";

}

function jChangeFontSize(increase, className) {

	var dsi = $('.'+className).css('font-size');
	dsi = dsi.replace("px","");
	if (dsi == 0) dsi =  11;

	if (increase == 1 && dsi < 16) {
		dsi++;
	}
	else if (increase == 0 && dsi > 11 ){
		dsi--;
	}else if (dsi == 11){
		$.cookie("fontsize", null);
	}
	if( className == 'post'){
		$('.'+className).css('font-size', dsi+"px");
		$('.'+className+' div').css('font-size', dsi+"px");
		$('.'+className+' a').css('font-size', dsi+"px");
	}
	else {
		$('.'+className).css('font-size', dsi+"px");
		$('.'+className+' a').css('font-size', dsi+"px");
	}
	$.cookie("fontsize", dsi, { expires: 365 });
	return false;
}
//END : Increase/Decrease Font
document.getElementsByClassName = function(className){
    var nodes = document.getElementsByTagName('*');
    var matches = new Array();
    for(i=0;i<nodes.length;i++){
        var tmp = nodes[i].getAttribute('class') || nodes[i].getAttribute('className');
        if(tmp == className) matches[matches.length] = nodes[i];
    }
    return matches;
}
function resizeimages(){

	if(document.getElementsByTagName){

		var posts = document.getElementsByClassName('post');

		for (var i = 0; i < posts.length; i++) {
			for(images=0; images<posts[i].getElementsByTagName('img').length; images++){

				img = posts[i].getElementsByTagName('img')[images];

				if(img.width > 600){
				img.style.width = '600px';
				img.style.height = 'auto';
				eval("imgpop" + String(images) + " = new Function(\"imgpop = window.open('" + img.src + " ','fullscale','scrollbars=1,resizable=1'); imgpop.focus();\")");
				eval("img.onclick = imgpop" + String(images) + ";");
				if (document.all) img.style.cursor = 'hand';
				if (!document.all) img.style.cursor = 'pointer';
				img.title = 'Кликни за да уголемиш картинката.';
						}
			}
		}
	}

}
window.onload = resizeimages;

$(document).ready(function(){

    /**
     * Character Counter for inputs and text areas
     */
    $('.word_count').each(function(){
	    // get current number of characters
	    var length = $(this).val().length;
	    var max = parseInt($(this).attr('rel'));

	    //first calculate
	    $(this).parent().find('.counter').html( max-length );

	    // bind on key up event
	    $(this).keyup(function(){
		    // get new length of characters
		    var new_length = $(this).val().length;
		    // get new length of words
		    //var new_length = $(this).val().split(/\b[\s,\.-:;]*/).length;
		    // update
		    $(this).parent().find('.counter').html( max-new_length );
		    if(new_length > max) {
			    var text = $(this).val();
			    $(this).val(text.substr(0,max));
			    $(this).parent().find('.counter').html( max-$(this).val().length );
		    }
	    });
    });

});


function adToFav(text){

	var info = text.split('-');

	$.get("/catalog/addToFsavorites/"+info[0]+"/"+info[1]+"/",
		function(data){
			if(info[0] == 'add') $('#favContainer').html('<a href="#" onclick="adToFav(\'rem-'+info[1]+'\'); return false;" class="addInFav" ></a>');
			else $('#favContainer').html('<a href="#" onclick="adToFav(\'add-'+info[1]+'\'); return false;" class="addInFav" ></a>');
		}
	);

	return false;
}

var offersPage = 1;

function loadOffers() {
	
	var categories = '';
	var city = 0;
	
	if($('.offers-loader').length == 0) $('#offersContainer').append('<img class="offers-loader" src="http://static.bg-mamma.com/img/1/ajax-loader-offers.gif" alt="Loading ..." />');
	
	$(".checkbox input:checked").each( function() {
		categories += ','+$(this).val();
	})
	
	city = $('#selectCity #cityID').val();
	
	var url = 'http://www.bg-mamma.com/index.php?action=ofertiList&page='+offersPage+'&categories='+categories+'&city='+city;
	
	$.get(url, function(data) {
		if(data != '') {
			$('#offersContainer').append(data);
		}
		$('.offers-loader').remove();
	});
}

function selectMenuOut() {
	$('#selectCity ul').hide();
};

