function run_article_recommend(that) {
	var showPos = $('body').find('#osszevont_hasab .eszkoztar').position();
	var isVisible = false;
	var nRecommends = $(that).find('.ajanlo_szoveg ul li').length;
	var iCurrent = 0;

	function showNext() {
		if (iCurrent < nRecommends-1) {
			$(that).find('.ajanlo_szoveg ul').animate({left:'-=344'}, 150, 'linear');
			iCurrent++;
			updateCounter();
		}
	}

	function showPrev() {
		if (iCurrent > 0) {
			$(that).find('.ajanlo_szoveg ul').animate({left:'+=344'}, 150, 'linear');
			iCurrent--;
			updateCounter();
		}
	}

	function updateCounter() {
		$(that).find('#article_num').text((iCurrent+1)+'/'+nRecommends);
	}

	// esemenykezelok
	$(that).find('#button_close').unbind('click').click(function() {
		$(that).stop().css('right', '-400px');
	});
	$(that).find('#button_next').unbind('click').click(function() {
		showNext();
	});
	$(that).find('#button_prev').unbind('click').click(function() {
		showPrev();
	});

	$(window).scroll(function() {
		if (isVisible == false && $(window).scrollTop() > showPos.top / 2) {
			// megjenites
			$(that).animate({right: '0px'}, 500, 'linear', function() {
				isVisible = true;
			});
		}
		else {
			// eltuntetes
			if (isVisible == true && $(window).scrollTop() < showPos.top / 2) {
				isVisible = false;
				$(that).stop().css('right', '-400px');
			}
		}
	});
}

function run_load_box_vote(that) {
	var datasource = $(that).data('datasource');
	$.get(
		datasource,
		{
			vote_id: $(that).data('id'),
			position_name: $(that).data('position_name'),
			style: $(that).data('style'),
			align: $(that).data('align')
		},
		function (data) {
			$(that).html(data);
			run_post_box_vote(that);
		},
		'html'
	);
}

function run_post_box_vote(that) {
	var datasource = $(that).data('datasource');
	$(that).find('form').submit(function() {
		$.post(
			datasource,
			$(this).serialize(),
			function (data) {
				$(that).html(data);
				run_post_box_vote(that);
				// captcha ujrakerese
				$(that).find('img#id_image_checknum').attr('src', $(that).find('img#id_image_checknum').attr('src')+'&'+Math.floor(Math.random()*1024));
			},
			'html'
		);
		return false;
	});
}

function run_clock() {
    var aClock = $('#analog-clock');
    var clockWidthHeight = aClock.width();//width and height of the clock

    startClock(aClock, clockWidthHeight);
}
function startClock(aClock, clockWidthHeight ){
    aClock.css({"height":clockWidthHeight +"px"});//sets the height if .js is enabled. If not, height = 0;
    aClock.fadeIn();//fade it in

    //call rotatehands function
    setInterval(function(){

        rotateHands(clockWidthHeight);

    }, 200);//1000 = 1 second

    rotateHands(clockWidthHeight);//make sure they start in the right position
}
function rotateHands(clockWidthHeight){

    //get current time/date from local computer
    var now = new Date();

    //set the second hand
    var secondAngle = 360/60 * now.getSeconds();//turn the time into angle
    $('#secondHand').rotate(secondAngle, 'abs');//set the hand angle
    $('#secondHand').css( { "left": (clockWidthHeight - $('#secondHand').width())/2 + "px", "top":(clockWidthHeight - $('#secondHand').height())/2 + "px" });//set x and y pos

    //set the minute hand
    var minuteAngle = 360/60 * now.getMinutes();//turn the time into angle
    $('#minuteHand').rotate(minuteAngle, 'abs');//set the hand angle
    $('#minuteHand').css( { "left": (clockWidthHeight - $('#minuteHand').width())/2 + "px", "top":(clockWidthHeight - $('#minuteHand').height())/2 + "px" });//set x and y pos

    //set the hour hand
    var hourAngle = 360/12 * now.getHours();//turn the time into angle
    $('#hourHand').rotate((hourAngle + minuteAngle/12)%360, 'abs');//set the hand angle
    $('#hourHand').css( { "left": (clockWidthHeight - $('#hourHand').width())/2 + "px", "top":(clockWidthHeight - $('#hourHand').height())/2 + "px" });//set x and y pos
}

function run_smaller(that) {
    $(that).click( function() {
    	decFontSize($('body div[id=cikk_torzs] div[id=lead]'));
        decFontSize($('body div[id=cikk_torzs] div[id=text]'));
    	decFontSize($('body div[id=hozzaszolas_torzs] *'));
        return false;
    });
}

function run_bigger(that) {
    $(that).click( function() {
    	incFontSize($('body div[id=cikk_torzs] div[id=lead]'));
        incFontSize($('body div[id=cikk_torzs] div[id=text]'));
    	incFontSize($('body div[id=hozzaszolas_torzs] *'));
        return false;
    });
}

function decFontSize(element)
{
	var currSize = parseInt($(element).css('font-size'));
	if (currSize>13) {
		$.cookie('fontsize', currSize-2, { path : '/' });
		$(element).css('font-size',currSize-2);
	}
}

function incFontSize(element)
{
	var currSize = parseInt($(element).css('font-size'));
	if (currSize<21) {
		$.cookie('fontsize', currSize+2, { path : '/' });
		$(element).css('font-size',currSize+2);
	}
}

function newsboxShow(prefix, id) {
    $('#'+prefix+id).parent().parent().find('.egy_sor .details').css('display','none');

//	$("div#hirek*").each(function(i, tagfound) {alert(tagfound);});
	$("div#"+prefix+id).css("display", "block");
}

function morenews( that ) {
    $(that)
        .prev().removeClass('last')
        .parent().find('.hidden').removeClass('hidden');

    $(that)
        .addClass('hidden');

    return false;
}

function lessnews( that ) {
    var first = $(that)
        .addClass('hidden')
        .parent().find('a.hidden:first')
            .removeClass('hidden')
            .prev().addClass('last')
            .next().next();

    var curr = first;
    while($(curr)[0] != $(that)[0]) {
        $(curr).addClass('hidden');
        curr = $(curr).next();
    }

    return false;
}

function run_country_leading_articles_slider(that) {
    var $offer = $(that).find('.one_c_article');
    var $links = $(that).find('.flag');
    var t;
    var timeout = 4000;

    $links.hover( function() {
        clearTimeout(t);
        $links.removeClass('active');
        $links.eq( $links.index(this) ).addClass('active');
        $offer.addClass('hidden');
        $offer.eq( $links.index(this) ).removeClass('hidden');
    },
    function() {
        t = setTimeout(function() { this.nextoffer(); }, timeout);
    });

    $offer.hover( function() {
        clearTimeout(t);
    },
    function() {
        t = setTimeout(function() { this.nextoffer(); }, timeout);
    });

    nextoffer = function() {
        next = $offer.index( $offer.not('.hidden')[0] ) + 1;
        if (next == $offer.length) {
            next = 0
        }

        $links.removeClass('active');
        $links.eq( next ).addClass('active');
        $offer.addClass('hidden');
        $offer.eq( next ).removeClass('hidden');

        t = setTimeout(function() { this.nextoffer(); }, timeout);
    }

    t = setTimeout(function() { this.nextoffer(); }, timeout);
}

function run_comments_form(that) {
	//$(that).find('form').find('input:submit').attr('disabled', '');
	if ($(that).find('#hozzaszolas_fejlec #show-form')) {
		$(that).find('#hozzaszolas_fejlec #show-form a').click(function() {
			$(that).find('#hozzaszolas_fejlec #show-form').hide();
			$(that).find('table').show();
			post_comments_form(that);
		});
	}
	post_comments_form(that);
}

function post_comments_form(target)
{
	var datasource = $(target).data('datasource');
	$(target).find('form').submit(function() {
		var showForm = $(target).find('form input[name=show_form]').val();
		$.post(
			datasource,
			$(this).serialize(),
			function (data) {
				$(target).html(data);
				run_comments_list($('.run_comments_list'), 0, undefined, showForm);
			},
			'html'
		);
		return false;
	});
}

function run_comments_list(that, page, listing_order, show_form) {

	var divId = $(that).attr('id');
	var datasource = $(that).data('datasource');
	var params =  divId.match(/_([0-9]+)_([a-z]+)_([0-9]+)$/);
	var linkId = params[1];
	var linkType = params[2];
	var listingOrder = listing_order == undefined ? null : listing_order;
	var showForm = show_form == undefined ? 0 : show_form;
	var firsttime = page==undefined;
	if (page == undefined) {
		var page = params[3];
	}
	else {
		var page = (page < 0) ? 0 : page;
	}

	var loaderImageContainer = $('#comments_loader_image');
    var ajaxLoaderImage = $('#comments_loader_image img.ajax-loader');

	if (!firsttime) {
		window.scrollTo(0,$('[name=comments]').position().top);
		var timer = setTimeout( function() {
			var p = $(loaderImageContainer).position();
	        var w = $(loaderImageContainer).width();
	        var h = $(loaderImageContainer).height();
	        ajaxLoaderImage
	           .css({top: p.top+($(window).height()-32)/2, left: p.left+(w/2)-16})
	           .show();
	        $('#'+divId).fadeTo(0, 0.5);
		}, 400);

	    $.get(datasource, {id:linkId, type:linkType, page:page, lm:listingOrder, show_form:showForm}, function (data, textStatus) {
	        if (textStatus=='success') {
						clearTimeout(timer);
						ajaxLoaderImage.hide();
						$('#'+divId)
							.empty()
							.html(data)
							.fadeTo(0, 1, function() {
								if(jQuery.browser.msie) {
									$(that).get(0).style.removeAttribute('filter');
								}
								window.scrollTo(0,$('[name=comments]').position().top);
							})
						;

						// webaudit meres:
						/*var tracker_src = $('.median_tracker_img:first').attr('src');
						if (tracker_src && tracker_src != undefined) {
							tracker_src += "&" + Math.floor(Math.random()*1000);
							$('body').append('<img src="' + tracker_src + '" style="position:absolute;top:-100px;left:-100px" width="1" height="1" />');
						}
						// google analytics:
						if (pageTracker && pageTracker != undefined) {
							pageTracker._trackPageview();
						}*/

						$(that).find('.pager a').each( function() {
							$(this).click( function() {
								run_comments_list(that, $(this).attr('href').split('#')[1]);
								return false;
							});
						});
						$(that).find('#hozzaszolas_fejlec a.change-order').each( function() {
							$(this).click( function() {
								run_comments_list(that, 0, $(this).attr('href').split('#')[1]);
								return false;
							});
						});

						run_comments_form($(that).find('.run_comments_form'));

						// betumeret beallitasa:
						setFontSize('comments');
	        }
	    });
	}
	else {
	    $(that).find('.pager a').each( function() {
	    	$(this).click( function() {
		    	run_comments_list(that, $(this).attr('href').split('#')[1]);
		    	return false;
	    	});
	    });
	    $(that).find('#hozzaszolas_fejlec a.change-order').each( function() {
	    	$(this).click( function() {
		    	run_comments_list(that, 0, $(this).attr('href').split('#')[1]);
		    	return false;
	    	});
	    });
	}
}

quiz = function(form) {
    this.rulesAcceptRequired = 1;
    this.rulesAccepted = false;

    form.find('#button_mehet').attr('class', (this.rulesAcceptRequired != 0 ? "disabled" : ""));

    this.submit = function() {
        return (this.rulesAcceptRequired == 0 || this.rulesAccepted);
    }
}

function run_magantanar(that) {
    var q = new quiz(that);
    $(that).submit( function() {
        return q.submit();
    });

    (btnAccept = that.find('#button_accept')).click( function() {
        q.rulesAccepted = btnAccept.attr('checked') ? true : false;
        that.find('#button_mehet').attr('class', q.rulesAccepted ? "" : "disabled");
    });
}

jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

$(document).ready( function() {
    if ($('#temp_etarget_hirdetes').text()=='') {
        $('#etarget_div').css('display','none');
    } else {
        $('#etarget_hirdetes').html( '<div class="etarget">' + $('#temp_etarget_hirdetes .etarget').html() + '</div>' );
    }

    $('.pic a img').parent().each( function() {
        var a = $(this).attr('href');
        if (a.substr(a.length-3,3).toLowerCase()=='jpg') {
        	$(this).lightBox({
        	    imageLoading: 'gfx/lightbox-ico-loading.gif',
			    imageBtnClose: 'gfx/lightbox-btn-close.gif',
			    imageBtnPrev: 'gfx/lightbox-btn-prev.gif',
			    imageBtnNext: 'gfx/lightbox-btn-next.gif'
        	});
        }
    });

    setFontSize();

    executeRunjs('body');
});

function setFontSize(target)
{
	if (target == undefined) {
		target = 'article';
	}

	var fontSize = parseInt($.cookie('fontsize'));
	if (fontSize != null && fontSize > 0) {
		switch (target) {
			case 'article' :
			{
				$('body div[id=cikk_torzs] div[id=lead]').css('font-size', fontSize);
				$('body div[id=cikk_torzs] div[id=szoveg] div[id=article]').css('font-size', fontSize);
			}
			case 'comments' :
			{
				$('body div[id=hozzaszolas_torzs] *').css('font-size', fontSize);
				break;
			}
		}
	}
}

function executeRunjs( startElement ) {
	runjs_each($(startElement+' .runjs'));
}

function run( runjs_tag ) {
	runjs_each($('.runjs.'+runjs_tag));
}

function runjs_each( objlist ) {
	jQuery.each(objlist, function() {
		var className = $(this).attr('class');
		var currObj = this;
		if (/\bnotfound|running\b/.test(className)==false) {
			var classes = className.split(' ');
			var thisobj = $(this);
			jQuery.each(classes, function() {
				if (this.substring(0,4)=='run_') {
					if (jQuery.isFunction( window[this] )) {
						$(currObj).addClass('running');
						window[this](thisobj);
					}
					else {
						$(currObj).addClass('notfound');
					}
				}
			});
		}
	});
}

