var someStuff = {
	fancyboxFormatTitle	: function (title, currentArray, currentIndex, currentOpts) {
		title = title.split('|');
		if(title[0] || title[1]) {
			return '<div id="fancybox-title-db">' + (title[0] ? '<div class="image-caption">' + title[0] + '</div>' : '') + (title[1] ? '<div class="image-author">' + title[1] + '</div>' : '') + '</div>';
		}
	}
};

var rating = {
	rateArticle : function (rating, t) {
		$('.article-social .vote a').
			unbind('click').
			click(function (){
				return false;
			});
			
		var id = window.location.href.split('-');
		var storage = "a"+id;
		
		if($.Storage.get(storage) == null) {
			if(rating > 0) {
				$(t).find("span").text('+'+(parseInt($(t).find("span").text())+1));
			} else {
				$(t).find("span").text((parseInt($(t).find("span").text())-1));
			}
			
			$.Storage.set(storage, "1");
			$.post('/rating/article/'+(rating > 0 ? 'plus' : 'minus')+'/'+parseInt(id[id.length-1]));
		}
		return false;
	},
	rateComment : function (rating, t) {
		$(t).parent().children().find('a').
			unbind('click').
			click(function (){
				return false;
			});
			

        //var id = $(t).parents().find("article").first().attr("id").split("_");

        var id = $(t).parent().parent().parent().parent().attr("id").split("_");

        id = id[1];
        
		var storage = "c"+id;

        var storageResource = $.Storage.get(storage);
		
		if(storageResource == null) {
			if(rating > 0) {
				$(t).text('+'+(parseInt($(t).text())+1));
			} else {
				$(t).text((parseInt($(t).text())-1));
			}
			
			$.Storage.set(storage, "1");
			$.post('/rating/comment/'+(rating > 0 ? 'plus' : 'minus')+'/'+parseInt(id));
		}
		return false;
	},
    rateImage : function (id, rate) {
        var storage = "i"+id;

        if($.Storage.get(storage) == null) {
            $.Storage.set(storage, "1");

            $('#image-rating-'+id).removeClass("rating-unrated");
            $('#image-rating-'+id).addClass("rating-rated");

            $.post('/rating/image/'+parseInt(id), {
                stars: rate
            },function (data){
                var JSONObj = $.parseJSON(data);

                rateId='#image-rating-'+id;
                rateView=$(rateId+' .current-rating');
                if (rateView){
                    rating.adjustStars(rateView, 1*JSONObj.avg_rating);
                    $(rateId+' .rating-result-view').html(1*JSONObj.avg_rating);
                    $(rateId+' .total-rated-view').html(parseInt(JSONObj.sum));
                }
            });
        }
        return false;
    },
	rateMovieArticle :	function () {
        var id = window.location.href.split('-');

        id = id[id.length-1];

        var storage = "ma"+id;


		if($.Storage.get(storage) == null) {
			$.Storage.set(storage, "1");

            var starsCount = $('#movie-article-rate .rate div a.hover').get().length;

			$.post('/rating/article/plus/'+parseInt(id), {
				stars: starsCount
			},function (data) {
                var JSONObj = $.parseJSON(data);

                $('#ratingsTotal').text(JSONObj.totalRatings);
                $('#ratingsAverage').text(JSONObj.averageRating);

                var newWidth = parseInt((JSONObj.averageRating / 5) * 100)+'%';

                //alert('newWidth: ' + newWidth);

                $('#movieUserRating').css('width',newWidth);


                $('#userArticleRating').unbind('mouseenter mouseleave').remove();
                $("#currentArticleRating").unbind('mouseenter mouseleave').show();

            });
		}
		return false;
	},
    adjustStars: function (el, result){
        width=0;
        if (result>0 && result<=1){
            width+=2+result*16;
        }
        if (result>1 && result<=2){
            width+=23+(result-1)*18;
        }
        if (result>2 && result<=3){
            width+=46+(result-2)*20;
        }
        if (result>3 && result<=4){
            width+=71+(result-3)*22;
        }
        if (result>4 && result<=5){
            width+=99+(result-4)*24;
        }
        width+=3;
        el.css('width', width+'px');
    }
};

(function($) {

    var elem;

    var hrs, mins, secs = 0;

    $.fn.ticker = function(){

        if(typeof $(this) === undefined){
            return;
        }

        if($(this).length == 0){
            return;
        }

        var hours, minutes, seconds = 0;

        var timeParts = $(this).text().split(":");

        this.elem = $(this);

        this.hrs = timeParts[0];
        this.mins = timeParts[1];
        this.secs = timeParts[2];

        $.ticker.tick(this);

    };

    $.ticker = function(obj) {
    };

    $.ticker.tick = function(obj){

        if(parseInt(obj.hrs,10) <= 0 && parseInt(obj.mins,10) <= 0 && parseInt(obj.secs,10) <= 0){
            obj.elem.text("00:00:00");
        } else {

            obj.secs--;

            if(obj.secs == 0){
                if(obj.mins > 0){
                    obj.secs = 59;
                    obj.mins--;
                }
            }

            if(obj.mins == 0 && obj.mins - 1 >= 0){
                obj.mins = 59;
                if(obj.hrs - 1 >= 0){
                    obj.hrs--;
                }
            }

            if(obj.secs.toString().length == 1){
                obj.secs = "0" + obj.secs;
            }

            if(obj.mins.toString().length == 1){
                obj.mins = "0" + obj.mins;
            }

            if(obj.hrs.toString().length == 1){
                obj.hrs = "0" + obj.hrs;
            }
            
            obj.elem.text(obj.hrs + ":" + obj.mins + ":" + obj.secs);

            setTimeout(function(){
                $.ticker.tick(obj)
            },1000);

        }
    };

    $.ticker.writeOut = function(obj, hours, minutes, seconds){
        if(hours >= 0 && minutes >= 0 && seconds > 0){
            elem.text(hours + ":" + minutes + ":" + seconds);
        } else {
            elem.text("00:00:00");
        }
    };
})(jQuery);

$(function() {
	$('a[rel*=external]').attr('target', '_blank');

    $(".comment-form, .comment-answer").append('<input type="hidden" name="spamtest" value="spamtest" />');

    if($('.article-social .vote').get().length > 0) {
        $('.article-social .vote a.up').click(function(){rating.rateArticle(+1,$(this));return false;});
        $('.article-social .vote a.down').click(function(){rating.rateArticle(-1,$(this));return false;});
    }

    if($('.article-comments .comment-rating').get().length > 0) {
        $('.article-comments .comment-rating a.up').click(function(){rating.rateComment(+1,$(this));return false;});
        $('.article-comments .comment-rating a.down').click(function(){rating.rateComment(-1,$(this));return false;});
        $('.article-comments .comment-actions li.comment-like a').click(
            function(){
                var elem = $(this).parent().parent().parent().find('.comment-rating a.up');
                rating.rateComment(+1,elem);
                return false;
            });
        $('.article-comments .comment-actions li.comment-dislike a').click(
            function(){
                var elem = $(this).parent().parent().parent().find('.comment-rating a.down');
                rating.rateComment(-1,elem);
                return false;
            });
    }


	$('.rating').each(function() {
		$('span', this).width(1*$('span', this).text()*20+'%');
	});

    $('.rate').each(function() {
		$('span', this).width(1*$('span', this).text()*20+'%');
	});

	$('.comment-form li input, .comment-form li textarea').live('focus', function() {
		if ($(this).val() == $(this).attr('alt'))
			$(this).val('');
		if (!$(this).hasClass('focused')) {
			$(this).addClass('focused');
			$(this).attr('alt', $(this).val());
			$(this).val('');
		}
	});

	$('.comment-form li input, .comment-form li textarea').blur(function() {
		if ($(this).val() == '') {
			$(this).val($(this).attr('alt'));
			$(this).removeClass('focused');
		}
	});
	
	if($('body.tv div.player script').length > 0) {
		$('#header ul[id!=menu], #header p, #header ul#menu li, .side .block, .content .block, #footer .block').addClass('dimmed');
		$('#header ul#menu li.active, .content .block.first').removeClass('dimmed');
		
		$('.dimmed').hover(function() {
			$(this).animate({opacity: 1}, 200).removeClass('dimmed');
		}, function() {
			$(this).animate({opacity: .3}, 200).addClass('dimmed');
		});
	}

	$('.list div.comment').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});

	$('p.buried a').click(function(e) {
		e.preventDefault();
		comment = $(this).parents('li');
		comment.slideUp(function() {
			$('p.buried', comment).hide();
			comment.removeClass('buried').slideDown();
		});
	});

	$('li.comment-answer a').click(function(e) {
		e.preventDefault();
		$(this).parent().addClass('active').parents('article').addClass('active');
		if ($(this).parents('article.comment').find('.comment-form').length==0) {
			var commentForm = $('.comment-form.hidden').clone();
//			commentForm.submit(function(e) {
//				e.preventDefault();
//				$(this).slideUp(function() {
//					$(this).remove();
//				});
//			});
			commentForm.appendTo($(this).parents('article.comment')).removeClass('hidden');

            var idContainer = $(this).parents("article").first().attr("id").split("_");
            var commentParentId = idContainer[1];

            commentForm.find(".parent").val(commentParentId);
		}
	});
	
	$('.image-rating .rating a').hover(function() {
		$(this).addClass('hover').prevAll().addClass('hover');
	}, function() {
		$(this).removeClass('hover').prevAll().removeClass('hover');
	}).click(function (){
		rating.rateImage();
		return false;
	});

	$('#movie-article-rate .rate a').hover(function() {
		$(this).addClass('hover').prevAll().addClass('hover');
	}, function() {
		$(this).removeClass('hover').prevAll().removeClass('hover');
	}).click(function (){
		rating.rateMovieArticle();
		return false;
	});

    $("#currentArticleRating").hover(function(){
        $(this).hide(0,function (){
            $("#userArticleRating").show();
        });
    });

    $("#userArticleRating").hover(function (){},function (){
        $(this).hide(0,function (){
            $("#currentArticleRating").show();
        });
    });

    $(".afisha-row").hover(
        function (){
            $(this).css("background-color","#DCEAF8");
        },
        function (){
            $(this).css("background-color","#FFFFFF");
        }
    );

    function toggleAfishaRow(eventId){
        var elem = $("#afisha-info-row-"+eventId);

        if(elem.css("display") == "table-row"){
            elem.css("display","none");
            $(this).parent().parent().parent().parent().removeClass("afisha-row-open");
        } else {
            $(this).parent().parent().parent().parent().addClass("afisha-row-open");
            elem.css("display","table-row");
        }
    }

    $('.toggle-afisha-row').click(function (){

        var eventId = $(this).attr("id").split('-')[1];

        toggleAfishaRow(eventId);

        return false;
    });

    $('.afisha-row-clickable').click(function (){

        var elem = $(this).find("a");

        if(elem.length > 1){
            elem = elem.first();
        }

        if(elem.hasClass("toggle-afisha-row")){

            var eventId = elem.attr("id").split("-")[1];

            toggleAfishaRow(eventId);

        } else {
            window.location.href = elem.attr("href");
        }

    });

    $.datepicker.setDefaults( $.datepicker.regional[ "lv" ] );

    $('.datepicker input').datepicker();

    if ($('#ticker').length>0){
        $('#ticker').ticker();
    }

    $('.atis-twiter .article .image').first().show();

    $('*').filter(function(index){
        if(this.id.match(/(.*)\-submit/g)){
            var parts = this.id.split('-');

            var matchString = "";
            var i;

            /* Match all parts except final one(eg. -submit) */

            for(i=0;i<parts.length-1;i++){
                matchString += parts[i] + '-'
            }

            var formMatch = matchString+"form";
            var formElem = $("#"+formMatch);

            if(formElem.length > 0){
                var linkElem = $('#'+this.id);
                linkElem.click(function(){
                    formElem.submit();
                    return false;
                });
            }
        }
    });

    /*$('#atis-jauta-submit').click(function(){
        $('#atis-jauta-form').submit();
        return false;
    });

    $('#atis-jauta-submit-c').click(function(){
        $('#atis-jauta-form-c').submit();
        return false;
    });

    $('#atis-jauta-submit-c').click(function(){
        $('#atis-jauta-form-c').submit();
        return false;
    });*/

    if($(".contest-kas-notiek").length > 0) {
        if($('#press-end').length > 0) {
            $(this).bind("contextmenu", function(e) {
                e.preventDefault();
            });

            $(window).bind('blur', function(){
                $('#kas_notiek_answers_finish').val("1");
                $('#kas_notiek_answers_fairly').val("0");
                $('form.did-form').submit();
            });

            $('#press-end').click(function (){
                $('#kas_notiek_answers_finish').val("1");
                $('form.did-form').submit();
            });
        }

        if($('.time-left').length > 0) {
            var timeInSeconds = 0;

            $('.time-left:eq(1) span').each(function(i,j){
                timeInSeconds += Math.pow(60,2-i)*$(this).text();
            });
            
            var shortly = new Date();
            shortly.setSeconds(timeInSeconds);
            
            $('.time-left.hidden').countdown({until: shortly, format: 'HMS', tickInterval: 1, onTick: function (p){
                $('.time-left:eq(1) span').each(function (i,j){
                    var c = p[i+4];
                    if(i == 0) {
                        c += p[i+3]*60;
                    }
                    $(this).text((c < 10 ? '0' : '')+c);
                });
            }});
        }
    }

    $(".kro:not(.krono) .krp").hover(function(){
        this.parentNode.style.backgroundPosition="0px -40px";
    },
    function(){
        this.parentNode.style.backgroundPosition="0px -0px";
    });

    $(".kro:not(.krono) .krm").hover(function(){
        this.parentNode.style.backgroundPosition="0px -80px";
    },
    function(){
        this.parentNode.style.backgroundPosition="0px -0px";
    });

    function colCCarousel_initCallback(carousel){

        var numPanels;
        numPanels = carousel.size();

        var i = 0;

        for(i = 1; i <= numPanels; i++){
            var tpl = '<li><a href="#">'+(i)+'</a></li>';
            $('ul#col-c-carousel-tabs').html($('ul#col-c-carousel-tabs').html()+tpl);
        }

        $('ul#col-c-carousel-tabs li a').click(function(){
            carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
            return false;
        });

        carousel.clip.hover(function() {
            carousel.stopAuto();
        }, function() {
            carousel.startAuto();
        });

    }

    function colCCarousel_switchButtons(carousel,slideElem,index,state){
        var carouselTabs = $('#col-c-carousel-tabs').children();

        var liIndex = index - 1;

        var liElem = $(carouselTabs[liIndex]);

        slideElem = $(slideElem);

        //console.log("LI Elem height: " + slideElem.height());

        carouselTabs.each(function(){
            $(this).removeClass('active');
        });

        liElem.addClass('active');

        $('#dienas-zurnali').height(slideElem.height()+55);

        return true;

    }

    var colCCarousel = $('#col-c-journal-carousel').jcarousel(
        {
            buttonNextHTML: null,
            buttonPrevHTML: null,
            initCallback: colCCarousel_initCallback,
            itemVisibleInCallback: colCCarousel_switchButtons,
            auto: 10,
            wrap: 'last',
            scroll: 1,
            size: $('#col-c-journal-carousel').children().length
        }
    );

});


function draugiemSay(title, url, titlePrefix) {
	window.open(
		'http://www.draugiem.lv/say/ext/add.php?title='+encodeURIComponent(title)+
		'&link=' + encodeURIComponent(url) +
		'&titlePrefix=' + encodeURIComponent(titlePrefix),
		'',
		'location=1,status=1,scrollbars=0,resizable=0,width=530,height=400'
	);
	return false;
}

var banners = {
    specialBaltcomClose : function (){
        document.getElementById("peldosais-baneris").style.display = "none";
    }
}

