/*
 *
 *  NEW DIGIMANIE.CZ JS FUNCTIONS
 **********************************
 */


/* *** search text field - old code *** */

function setTopBackgroundBanner(){
	var windowWidth = $(window).width();
	var isChrome = window.chrome;
	if(windowWidth < 1000){
		windowWidth = 1000;
	}
	var left = windowWidth - $('.background-banner a img').width();
	if (left > 0){
		$('.background-banner').css("overflow","hidden");
		$('.background-banner').css("width",windowWidth);
		if(isChrome){
			if(windowWidth % 2 == 0) {
			    $('.background-banner').css("left","0px");
            } else {
              $('.background-banner').css("left","-1px");
            }
		}else{
			$('.background-banner').css("left","auto");
		}
	}else{
		if(isChrome || window.opera){
			left = left + (left%2);
		}else{
			left = left - (left%2);
		}
		left = left / 2;

		$('.background-banner').css("overflow","hidden");
		$('.background-banner').css("width",windowWidth - (left));
		$('.background-banner').css("left",left);
	}
}

function clickclear(thisfield, defaulttext) {
    if (thisfield.value == defaulttext) {
        thisfield.value = "";
    }
}

function clickrecall(thisfield, defaulttext) {
    if (thisfield.value == "") {
        thisfield.value = defaulttext;
    }
}

/* *** select date - old code - nahradit? *** */

var oldDateSelect;
var dateId = '#date-select';

function changeDate(day, month, year, history){
	if ( history ) { dateId = '#history-date-select';}
    oldDateSelect = $(dateId).html();
    sidebardigi.renderAjaxNavigation(day,month,year, 'digimanie', history,{callback:setDate, errorHandler:setOldDate});
}

function setDate(result){
    $(dateId).html(result);
}

function setOldDate(){
    $(dateId).html(oldDateSelect);
}

/* *** new cameras - old code - nahradit? *** */

var oldProdukty;

function getAnotherProducts(stranka){
    oldProdukty = $('#vypis-produktu-table').html();
    digivypisproduktu.renderAjaxProductsPictures(stranka, 'digimanie', {callback:setProducts, errorHandler:setOldProducts});
}

function setProducts(result){
    $('#vypis-produktu-table').html(result);
}

function setOldProducts(){
    $('#vypis-produktu-table').html(oldProdukty);
}


/* *** firemnik - old code - nahradit? *** */

var oldFiremnik;

function getAnotherFirms(unid){
    oldFiremnik = $('#firemnikHP').html();
    firemnikdigi.renderAjaxDirectoryHPBoxPhotographer( 'digimanie', unid, {callback:setNewFiremnik, errorHandler:setOldFiremnik});
}

function setNewFiremnik(result){
    $('#firemnikHP').html(result);
}

function setOldFiremnik(){
    $('#firemnikHP').html(oldFiremnik);
}

var oldThemebox;
function getAnotherMonth(year, month){
    oldThemebox = $('#header-theme').html();
    monththemedigi.renderAjaxTheme(year, month, 'digimanie', {callback:setNewMonthTheme, errorHandler:setOldMonthTheme});
}

function setNewMonthTheme(result){
    $('#header-theme').html(result);
}

function setOldMonthTheme(){
    $('#header-theme').html(oldThemebox);
}

var oldReview;
function getAnotherReview(start){
    oldReview = $('#nejnovejsi-recenze').html();
    digivypisproduktu.renderAjaxNejnovejsiRecenze(start, 'digimanie', {callback:setReviews, errorHandler:setOldReviews});
}

function setReviews(result){
    $('#nejnovejsi-recenze').html(result);
}

function setOldReviews(){
    $('#nejnovejsi-recenze').html(oldReview);
}
var oldDiscAns;
function rollDiscAns(pageNumber, pageSize,size,showall,allowRemove,UNID){
    oldDiscAns = $('#discussion-ansv').html();
    digivoter.renderDiscusionAnsversAjax(pageNumber,pageSize,size,showall,allowRemove,'digimanie',UNID,{callback:setDiscAns, errorHandler:setOldDiscAns})
}

function setDiscAns(result){
    $('#discussion-ansv').html(result);
    $('#discussion-ansv').scroll(0,0);
}

function setOldDiscAns(){
    $('#discussion-ansv').html(oldDiscAns);
}

var voteOldValue;
var spanId;
function makeVote(unid, id, value) {
    spanId = '#'+unid.replace(/\./, "\\.")+'-'+id;
    voteOldValue = $(spanId).html();
    digivoter.makeVote(unid, id, value,"digimanie", {callback:handleVote});
}
function handleVote(result){
    $(spanId).fadeOut('slow', function(){
        $(spanId).html(result[0]).fadeIn('slow').addClass('red');
        $(spanId).fadeOut(2500, function(){
            $(spanId).empty().html(result[1]).fadeIn('slow').removeClass('red');
        });
//            $(spanId+'info').html(result[0]);
    });
}

function expert_popup(obj){
    var unid = $(obj).attr('rel');
    window.open("competition.jsp?doc=" + unid + "&popup=1&iframe=1","soutez","menubar=no,status=no,center:true,scrollbars=yes,width=710,height=700")
}

/* *** Rotator global functions - NEW *** */

/* auto rotation - new code */
function rotatorAutoSwitchInit(obj){
    setInterval(function (){
        var n = $(obj).children('.active').next('.value');
        if( $(n).index('.value') < 0 ){
            n = $(obj).children('.active').siblings('.value:first');
        }
        rotatorSwitch( n );
    }, 6000+500*(Math.floor(Math.random()*3)));
}

function rotatorSwitch(obj){
    var i = $(obj).index() - 1;
    /*
    objs = $(obj).parent().children('.value');
    i = $(objs).index( obj );
    */
    $(obj).siblings('.active').removeClass('active');
    $(obj).addClass('active').parent().siblings('.article').hide().filter('.article:eq('+i+')').show();
    //$(obj).addClass('active').parent().siblings('.article').fadeOut().filter('.article:eq('+i+')').fadeIn();
    if( $(obj).next('.value').length ) {
        $(obj).siblings('.arrow.r').removeClass('off');
    } else {
        $(obj).siblings('.arrow.r').addClass('off');
    }
    if( $(obj).prev('.value').length ) {
        $(obj).siblings('.arrow.l').removeClass('off');
    } else {
        $(obj).siblings('.arrow.l').addClass('off');
    }
}
function hideAll(){
    var rok = new Date().getUTCFullYear();
    for ( i = rok; i > 2005; i-- ){
        $( '#' + i ).hide();
    }
};
/*doprovodne funkce pro karusel s promennou delkou*/
function setWidth(){/*nastavi sirku pro .content a pro .window pokud ke pridana trida photo*/
	$( '.carousel.photo .content' ).each( function ()
	{
		var windowWidth = $( '.tisk' ).width();

		$( this ).css( 'width', windowWidth - 2 * 39 );
		$( this ).find( '.window' ).css( 'width', Math.floor( (windowWidth - 2 * 39) / 132 ) * 132 );
	} );
}
function setRightArrow(){ /*nastavi umisteni prave sipky, pokud je pridana trida photo*/
$('.carousel.photo .content').each(function (){
	 	var arrowRSize = $(this).find('.arrow.r').width();
	    var contentSize = $(this).width();

	    $(this).find('.arrow.r').css('left', contentSize + arrowRSize);
	 });
};

function prepareCarousel(specClass){
	$(specClass).each(function (){

        $(this).append('<span class="arrow l off"></span><span class="arrow r"></span>');

        var current = 0;
        var speed = 'fast';
        var wSize = $(this).find('.window').width();
        var maximum = $(this).find('li').size();
        var liSize = $(this).find('li').outerWidth();
        var step = Math.floor(wSize/liSize);
        var carousel_height = $(this).find('.window').height();
        var ulSize = liSize * maximum;
		if ($(this).parent().hasClass( 'photo' )) {//pokud jsme na photo.jsp

			var docUnid = $(document).getUrlParam("doc");// pokud je url zadano klasickym zpusobem
			if(docUnid == null || docUnid.length == 0){// pokud je url v upravenem tvaru photo_doc-xxx.html
				var url = window.location.pathname;
				var from = url.indexOf("-") + 1;
				var to = url.indexOf(".");
				docUnid = url.substring(from, to);
			}
			var listItem = document.getElementById(docUnid);
			var position = $('li').index(listItem);
			current = step * Math.floor(position / step);
		}
        var ul = $(this).find('ul');
        $(ul).css('position', 'absolute').css('width', ulSize+'px').css('left', -(current * liSize));

        var goleft = $(this).find('.arrow.l');
        var goright = $(this).find('.arrow.r');

        var setArrows = function (){
            if (current - step < 0){
                $(goleft).addClass('off');
            } else {
                $(goleft).removeClass('off');
            }
            if (current + step >= maximum){
                $(goright).addClass('off');
            } else {
                $(goright).removeClass('off');
            }
        }

        setArrows();

        $(goleft).click(function (){
            if(current - step < 0 || current - step >= maximum) {
                return;
            } else {
                current = current - step;
                $(ul).animate({left: -(liSize * current)}, speed, null);
                setArrows();
            }
            return false;
        });

        $(goright).click(function (){
            if(current + step < 0 || current + step >= maximum) {
                return;
            } else {
                current = current + step;
                $(ul).animate({left: -(liSize * current)}, speed, null);
                setArrows();
            }
            return false;
        });


    });

	//pozice obrazku v aktualni otazce na hp
	$('.box.competition.actual-question').each( function(){
		var boxHeight = $(this).height();
		var pictureHeight = $(this).find('.picture').height();
		var topp = (boxHeight - pictureHeight)/2;
		$(this).find('.picture').css('padding-top',topp);
	});
};
// jcarousel pro recommended articles START
var visibleItems = 4;

function mycarousel_initCallback(carousel) {
  jQuery('.recommended-articles-carousel .arrow.r').bind('click', function() {
    carousel.next();
    return false;
  });

  jQuery('.recommended-articles-carousel .arrow.l').bind('click', function() {
    carousel.prev();
    return false;
  });

  jQuery('.control .dot').bind('mousedown', function(){
        carousel.scroll($(this).index());
        $mouseDown = true;
        $(".control .dot").bind('mouseover',function(){
          carousel.scroll($(this).index());
        });
  });

  $(document).bind('mouseup', function(){
        $(".control .dot").unbind('mouseover');
  });
};
// jcarousel pro recommended articles END
function setPinifyResult(result){
		var stepsArray = [];
		for (i = 0; i < result.length && i < 5; i++){
			if(result[i]!=null){
				items = result[i];
				var item = {
					'name': items[0],
					'url': items[1] + '?utm_source=ie9&utm_medium=web&utm_campaign=pinned-ie9',
					'icon': items[2]
				};
				stepsArray.push(item);
			}
		}
		$.pinify.addJumpList({
			title: 'Nejnovější',
			items: stepsArray
		});
	}

function automaticDynamicListReload(){
	pinifydigi.renderAjaxNewestArticlesForJumpList('digimanie',{callback:setPinifyResult});
	setTimeout("automaticDynamicListReload()",900000);//	15 min - 900s - 900000ms
}

/* *** jQuery functions *** */

$(document).ready(function(){
	setTopBackgroundBanner();

	//jcarousel recommended articles START
	$("#RACarousel").jcarousel({
    scroll: 4,
    initCallback: mycarousel_initCallback,
    itemVisibleOutCallback:{
        onAfterAnimation: function (c, o, i, s) {
            i = i - 1;
            $('.control .dot:eq(' + i + ')').removeClass('active');
            if(Math.floor(i/visibleItems) == 0){
                $('.recommended-articles-carousel .arrow.l').removeClass('off');
            }
            if(Math.floor(i/visibleItems) == Math.floor(($('#RACarousel li').size() - 1 )/visibleItems) ){
                $('.recommended-articles-carousel .arrow.r').removeClass('off');
            }
        }
    },
    itemVisibleInCallback: {
        onAfterAnimation: function (c, o, i, s) {
            i = i - 1;
            $('.control .dot:eq(' + i + ')').addClass('active');
            if(i == 0){
                $('.recommended-articles-carousel .arrow.l').addClass('off');
            }
            if(i == ($('#RACarousel li').size() - 1) ){
                $('.recommended-articles-carousel .arrow.r').addClass('off');
            }
        }
    },
    buttonNextHTML: null,
    buttonPrevHTML: null
  });
	//jcarousel recommended articles END
	/*diskuze zobrazeni i-frame inicializace obsahu*/
	$('.artif:not(.show)').each(function(){
		$(this).hide();
	});
//PINIFY pro IE
	if (document.documentMode > 5)//5 je defaultni hodnota
	{
		$("head").pinify({
			applicationName: "Digimanie.cz",
			favIcon: "/favicon.ico",
			startUrl: "http://www.digimanie.cz",
			tasks: [{
				'name': "Recenze",
				'action': "http://www.digimanie.cz/recs.jsp?utm_source=ie9&utm_medium=web&utm_campaign=pinned-ie9",
				'icon': "/favicon.ico"
			},
				{
					'name': "Aktuality",
					'action': "http://www.digimanie.cz/akt.jsp?utm_source=ie9&utm_medium=web&utm_campaign=pinned-ie9",
					'icon': "/favicon.ico"
				},
				{
					'name': "Články",
					'action': "http://www.digimanie.cz/news.jsp?type=story&utm_source=ie9&utm_medium=web&utm_campaign=pinned-ie9",
					'icon': "/favicon.ico"
				},
				{
					'name': "Témata",
					'action': "http://www.digimanie.cz/theme_list.jsp?utm_source=ie9&utm_medium=web&utm_campaign=pinned-ie9",
					'icon': "/favicon.ico"
				},
				{
					'name': "Soutěže",
					'action': "http://www.digimanie.cz/branch.jsp?node=5450A622D9C32DF3C125740B002E92C6&utm_source=ie9&utm_medium=web&utm_campaign=pinned-ie9",
					'icon': "/favicon.ico"
				},
				{
					'name': "Fórum",
					'action': "http://www.digimanie.cz/forum?utm_source=ie9&utm_medium=web&utm_campaign=pinned-ie9",
					'icon': "/favicon.ico"
				}]
		});

		automaticDynamicListReload();
	}

//PINIFY pro IE	END

    //expertiady podle let
    hideAll();
    var rok = new Date().getUTCFullYear();
    $('#'+(rok)).show();

    $('.expert-time-menu').click(function(){
        hideAll();
        var year = $(this).attr('rel');
        $('#' + year).show();
    });
    //expertiady podle let END

    /* multi boxes - most-read/discussed, recent comments/new in forum - NEW */

    $('.box.multi').children('.head:not(.part-a), .content:not(.part-a)').hide();
	$('.box.multi .content').children(':not(.content1)').hide();
//    $('.box.multi .content .content2').hide();

    $('.box.multi .head .hidden').click(function (){
        $(this).parent().parent().children('.part-a, .part-b').toggle();
    });

    $('.box.multi .switch').click(function (){
	    var cssclasses = $(this).attr('class').split(' ');
	    var cssFrom; var cssTo;
	    for(i = 0; i < cssclasses.length; i++){
			temp = cssclasses[i];
		    if(temp.indexOf('content') == 0){
			    cssFrom = temp;
		    }else if (temp.indexOf('to-content') == 0){
			    cssTo = temp.substring(3);
		    }
	    }

        $(this).parent().parent().children('.' +cssFrom + ', .' + cssTo).toggle();
        $(this).parent().children('.' +cssFrom + ', .' + cssTo).toggle();
    });

    /* article rotator - top articles, month theme - NEW */

    $('.rotator .content').each(function (){
        $(this).children('.article:not(:first)').hide();
        var a = $(this).children('.article');
        var n = '<div class="navi">';
        var l = '';
	    n += '<span class="arrow l off"></span>';
        for(i=0;i<a.length;i++){
            l = $(a[i]).children('h3').children('a').attr('rel');
            n += '<span class="value'+(i?'':' active')+'">'+(l?l:i+1)+'</span>';
        }
        n += '<span class="arrow r"></span>';
	    n += '</div>';
        $(this).append(n);

        $(this).find('.navi .value').mouseover(function (){
            rotatorSwitch(this);
        });

        $(this).find('.navi .arrow.l').click(function (){
            if( $(this).not('.off').length ) {
                rotatorSwitch( $(this).siblings('.active').prev('.value') );
            }
        });

        $(this).find('.navi .arrow.r').click(function (){
            if( $(this).not('.off').length ) {
                rotatorSwitch( $(this).siblings('.active').next('.value') );
            }
        });

    });

    $('.rotator.auto .content .navi').each(function (){
        rotatorAutoSwitchInit(this);
    });

    /* new cameras - autostart - NEW */

    $('.new-cameras').delegate('.navi .arrow','click',function (){
        if( $(this).not('.off').length ) {
            getAnotherProducts( $(this).attr('rel') );
        }
    });

    /* firemnik - autostart - NEW */

    $('.firemnik').delegate('.navi .arrow','click',function (){
        if( $(this).not('.off').length ) {
	        var unid = $(this).attr('rel');
            getAnotherFirms(unid);
        }
    });


    /* sections/branches sub navigation - NEW */

    $('#sections .nav a').hoverIntent({
        over:function(e){
            var asn = '.sub-nav.'+$(this).attr('rel');
            $(asn).css('z-index','101').slideDown('fast');
            //$(asn).css('z-index','101').fadeIn('slow');
        },
        out:function(e){
            var sn = $(this).attr('rel');
            var asn = '.sub-nav.'+sn;
            if( !$(e.relatedTarget).hasClass(sn) && !$(e.relatedTarget).parents(sn).length ){
                $(asn).css('z-index','100').slideUp('slow');
                //$(asn).css('z-index','100').fadeOut('slow');
            }
        }
    });


    $('#sections .sub-nav').mouseleave(function(e){
        sn = $(e.relatedTarget).attr('rel');
        if( !$(this).hasClass(sn) ){
            $(this).css('z-index','100').slideUp('slow');
            //$(asn).css('z-index','100').fadeOut('slow');
        }
    });

    /* initPressReleaseBox() - autostart version, for new html code - NEW */

/*
    var zajeti = null;
    $('#prboxik, #pressrelbar').hoverIntent({
        over:function (){
            clearTimeout(zajeti);
            $('#prboxik').slideDown('slow');
        },
        timeout:500,
        out:function(){
            zajeti = setTimeout( function (){$('#prboxik').slideUp('slow');}, 1500);}
    });
*/

    $('#pressrelbar').hoverIntent({
        over:function (){
            $('#prboxik').slideDown('slow');
        },
        timeout:500,
        out:function(e){
            $('#prboxik').delay(1500).slideUp('slow');
        }
    });

	$('.notes table').each(function(){
		var cssClass = $(this).attr('class');
		if (cssClass == null ||cssClass.length == 0) {
			 $(this).addClass("tbl_grey");
		}
	});

    /* rozbalovaci vyrobci - NEW - obecny kod */

    $('.producers .content .all').each(function (){
        var all = $(this);
        $(this).parent().append('<span class="switch open clear right">zobrazit všechny</span><span class="switch close clear right">zobrazit pouze vybrané</span>');
        $(this).siblings('.switch').click(function (){
            $(this).fadeOut('slow');
            $(this).siblings('.switch').fadeIn('slow');
            if( $(this).hasClass('open') ){
                $(all).slideDown('slow');
            } else if ( $(this).hasClass('close') ){
                $(all).slideUp('slow');
            }
        });
    });

	/*diskuze zobrazeni i-frame*/
	$('.box.discussion.author .content .i-frame').click(function(){
		if($(this).hasClass('show')){
			$(this).hide();
			$('.box.discussion.author .content .i-frame.hide').show();
			$('.box.discussion.iframe').slideDown('slow');
		}else{
			$(this).hide();
			$('.box.discussion.author .content .i-frame.show').show();
			$('.box.discussion.iframe').slideUp('slow');
		}
	});

    /* foto galerie - NEW - vertikalni centrovani */

    $('#main .box.photo-gallery .content').each(function(){
        var h = $(this).height();
        $(this).children('a:has(img)').each(function(){
            $(this).css('padding-top',(h - $(this).height())/2+'px' );
        });
    });

	$('#main .box.articles.others-articles .content.full .article.short.ico .par a img').each(function(){
		var width = parseInt($(this).attr("width"));
		var height = parseInt($(this).attr("height"));
		var cssclass = $(this).attr("class");

		if(cssclass != "prev" ){

			if(width >= height){
				$(this).attr("width", 50);
				$(this).removeAttr("height");
			}else{//width < height
				$(this).attr("height", 50);
				$(this).removeAttr("width");
			}
		}

	});

    /* carousel (recommendedarticles) - NEW */

	setWidth();

    prepareCarousel('.carousel .content');

	setRightArrow();


    $('#expertiada-popup').click(function(){
        expert_popup(this);
    });

	$(window).scroll(function(){
            if  ($(window).scrollTop() >= $(".scroll-sidebar-box").offset().top){
                $(".scroll-sidebar-box").css("position", "fixed");
                $(".scroll-sidebar-box").css("border", "0px 1px 1px solid");
	            var top = $('#container-footer-separator').offset().top - ($(window).scrollTop() + $(".scroll-sidebar-box").outerHeight(true))
	            if(top > 0){
		            $(".scroll-sidebar-box").css("top", "0");
	            }else{
		            $(".scroll-sidebar-box").css("top", top);
	            }
            }
            if  ($(window).scrollTop() <= $(".sidebarBannerIdentifier").offset().top){
                $(".scroll-sidebar-box").css("position", "relative");
                $(".scroll-sidebar-box").css("top", $(".sidebarBannerIdentifier").offset);
                $(".scroll-sidebar-box").css("border", "0px none");

            }
	});

});

$(window).resize(function() {
	setWidth();
	prepareCarousel('.carousel.photo .content');
	setRightArrow();
	setTopBackgroundBanner();
});

