// variables - change their values in templates
var section = 'WIDEO';              // ID kategorii do której maja być linkowane filmy
var username = 'onlinegp24';        // nazwa uzytkownika
var start = 1;                      // index poczatku
var count = 12;                     // ilosc wyswietlanych filmow
var order = 'published';            // porzadek sortowania
var windowWidth = 670;              // szerokosc okna wideo
var windowHeight = 400;             // wysokosc okna wideo
var category = '';                  // kategoria/keyword filmow
var searchtext = '';                // tekst wyszukiwania
var current = '';                   // obecnie wybrany element
var init = true;                    // flaga inicjalizacji

// show player
showPlayer = function (element,link,displayDescription,width,height) {
    if (!link) {
        link = element.attr("href");
    }
    var pageLink = link;
    if (!width || !height) {
        width = 670;
        height = 400;
    }
    if (current!=link | !displayDescription) {
        id=link.substr(link.length-11,11);
        var link = 'http://www.youtube.com/v/' + id + '&border=0&autoplay=0&rel=0&fs=1&egm=0&theme=light&color=white';
        swfobject.embedSWF(link, "videoPlayerHolder", width, height, "6",'/swf/expressInstall.swf',{},{bgcolor:'#f2f2f2',wmode:'opaque',allowfullscreen:'true'},{});

        if (displayDescription) {
            current = element.attr("href").replace("&","&amp;");
            var title = element.parent().find('b').text();
            var info = element.parent().find('div').html();
            var re = new RegExp('Ten film obejrzano ([0-9]+) razy?\.');
            info = info.replace(re, 'Liczba wyświetleń: $1');            
            
            var directlink = 'http://'+location.host+'/apps/pbcs.dll/section?category='+section+'&amp;id='+id;
            var directlinkText = 'http://' + location.host.substr(0,7) + '..';
            $("#videoDescription").html('<h2>'+title+'</h2>'+info+'<p class="link">Link bezpośredni: <a href="'+directlink+'">'+directlinkText+'</a></p>');
        }

        // generate like and plusone functions
        if ($("#videoPlusone").length == 1) {
            gapi.plusone.render("videoPlusone", {"size": "medium", "count": "false", "href": pageLink});
        }
        if ($("#facebookLikeButton").length == 1) {
            var faceBookLikeOptions = {
                src: href="http://www.facebook.com/plugins/like.php?locale=pl_PL&amp;href="+encodeURIComponent(pageLink)+"&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;colorscheme=light&amp;height=20",
                attr: { scrolling: "no", frameborder: "0", style: "border:none; overflow:hidden; width:100px; height: 20px;", allowTransparency: "true" },
                width: 70,
                height: 20
            };
            $('a#facebookLikeButton').iframe(faceBookLikeOptions);
        }
    }
};

// set navigation
pagesNav = function (total) {
    var maxPages = 80; // YouTube don't returns indecies greater than 1000 when using q or orderby parameter
	var navigation = '';
    var next = start + count;
    var numPages = Math.ceil (total / count) ;
    var currentPage = (start + count -1) / count;
    if (numPages > maxPages)
    	numPages = maxPages;
    // back button
    if (start > 1) {
        navigation += '<a href="#" id="previous" title="Nowsze wideo">&laquo;&nbsp;Nowsze</a> ';
    } else {
    	navigation += '<span id="empty">&nbsp;</span>';
    }

    // pages
    navigation += '<span id="pages">';
	var showPages = 4;
	r = Math.floor(showPages/2);
	s = currentPage-r;
	f = currentPage+r;
	if (showPages%2 == 0) {
		s++;
	}
	while (f > numPages) {
		f--;
		s--;
	}
	while (s < 1) {
		s++;
		f++;
	}
    if (s >= 2) {
    	navigation += ' <a href="#" id="page'+1+'" title="Wideo strona '+1+'">'+1+'</a> ... ';
    }
    for (i=s; i<=f; i++) {
    	if (i > 0 && i <= numPages) {
            var active = '';
            if (i == currentPage) {
                active = 'class=active';
            }
            navigation += ' <a href="#" id="page'+i+'" '+active+' title="Wideo strona '+i+'">'+i+'</a> ';
    	}
    }
    if (f < numPages) {
    	navigation += ' ... <a href="#" id="page'+numPages+'" title="Wideo strona '+i+'">'+numPages+'</a> ';
    }
	navigation += '</span>';

    // forward button
    if (next < total) {
        navigation += ' <a href="#" id="next" title="Starsze wideo">Starsze &raquo;</a>';
    }
    // apply html
    $("#videoNavigation").html(navigation);
    // bind functions to buttons
    $('#next').click(function(){
        start += count;
        loadVideos();
        return false;
    });
    $('#previous').click(function(){
        start -= count;
        loadVideos();
        return false;
    });
    $('#pages a').click(function(){
        start = count * $(this).text() - count + 1;
        loadVideos();
        return false;
    });
};

// get and format all video entries
renderVideos = function (root) {
    var data = root.data;
    var total = data.totalItems;
    var html = [''];

    if (total>0) {
        for (var i = 0; i < data.items.length; ++i) {
            var item = data.items[i];
            var title = utf2iso(item.title);
            var link = '/apps/pbcs.dll/section?Category='+section+'&amp;id='+item.id;
            var image = item.thumbnail['sqDefault'];
            var seconds = item.duration%60;
            if (seconds < 10) seconds = '0'+seconds;
            var duration = '<p class="duration">Czas trwania: '+Math.floor(item.duration/60)+':'+seconds+'</p>';
            var date = '<p class="date">Dodano: '+item.uploaded.substring(0,10)+'<span>, '+item.uploaded.substring(11,16)+'</span>'+'</p>';
            var views = item.viewCount?'<p class="views">Ten film obejrzano '+item.viewCount+' raz'+getNumeralEnding(item.viewCount)+'.</p>':'';
            var active = '';
            if (current == link) {
                active = 'class="active"';
            }
			html.push('<li '+active+'><a href="'+link+'" title="'+title+'" class="image player"><img src="'+image+'" alt="'+title+'" title="'+title+'" /></a><a href="'+link+'" title="'+title+'" class="player"><b>'+title+'</b></a><div>'+date+duration+views+'</div></li>');
        }
        $('#videoList').html(html.join(""));
        // display pages navigation
        pagesNav (total);
        // set .player class functions
        $('.player').click(function(){
            showPlayer($(this),0,1,windowWidth,windowHeight);
            $('#videoList li').removeClass('active');
            $(this).parent().addClass('active');
            scroll(0,0);
            return false;
        });

        // show player for the first item
        var s = $('#videoDescription').html();
        s = s.replace(/<\!\-\- remote \-\->/i,"");
        s = s.replace(/\s+|\n+/i,"");
        if (s == "") {
            init = false;
            showPlayer($('.player:first'),0,1,windowWidth,windowHeight);
            $('.player:first').parent().addClass('active');
        } else {
        	// mark item when ID is given
        	var activeId = $('.link a').attr('href');
        	activeId = activeId.replace(/.*id=([A-Za-z0-9_\-]+).*/i,"$1");
        	$('.player').each(function() {
        		var href = $(this).attr('href');
        		if (href.indexOf(activeId) > 0) {
        			$(this).parent().addClass('active');
        		}
        	});
        }
    }
};

// calling youtube script
loadVideos = function () {
    if (!category || category=='Latest') {
        category=',';
    }
    var url = 'http://gdata.youtube.com/feeds/api/users/'+username+'/uploads?category='+category+'&q='+searchtext+'&orderby='+order+'&max-results='+count+'&start-index='+start+'&v=2&alt=jsonc&callback=renderVideos';
    var script=document.createElement('script');
    script.src=url;
    script.type="text/javascript";
    $('#videoScripts').html(script);
};

// get and format search results
renderSearchResults = function (root) {
	var data = root.feed;
    var total = data.totalItems;
    var html = [''];
    if (total>0) {
        for (var i = 0; i < data.items.length; ++i) {
            var item = data.items[i];
            var title = utf2iso(item.title);
            var link = '/apps/pbcs.dll/section?Category='+section+'&amp;id='+item.id;
            var image = item.thumbnail['sqDefault'];
            var seconds = item.duration%60;
            if (seconds < 10) seconds = '0'+seconds;
            var duration = '<p class="duration">Czas trwania: '+Math.floor(item.duration/60)+':'+seconds+'</p>';
            var date = '<p class="date">Dodano: '+item.uploaded.substring(0,10)+'<span>, '+item.uploaded.substring(11,16)+'</span>'+'</p>';            
            var views = item.viewCount?'<p class="views">Ten film obejrzano '+item.viewCount+'raz'+getNumeralEnding(item.viewCount)+'.</p>':'';
            html.push('<li><a href="'+link+'" title="'+title+'" class="player image"><img src="'+image+'" alt="'+title+'" /></a><a href="'+link+'" title="'+title+'" class="player"><b>'+title+'</b></a><div>'+date+duration+views+'</div></li>');
        }
        $('#videoList').html(html.join(""));
        pagesNav (total);
        // bind functions to buttons
        $('#next').click(function(){
            start += count;
            loadSearch();
            return false;
        });
        $('#previous').click(function(){
            start -= count;
            loadSearch();
            return false;
        });
        $('#pages a').click(function(){
            start = count * $(this).text() - count + 1;
            loadSearch();
            return false;
        });
    }
};

// calling youtube script
loadSearch = function () {
    if (!category || category=='Latest') {
        category=',';
    }
    var url = 'http://gdata.youtube.com/feeds/api/users/'+username+'/uploads?category='+category+'&q='+searchtext+'&orderby='+order+'&max-results='+count+'&start-index='+start+'&v=2&alt=jsonc&callback=renderSearchResults';
    var script=document.createElement('script');
    script.src=url;
    script.type="text/javascript";
    $('#videoScripts').html(script);
};

/*
 * Funkcja dostawia końcówkę, aby utworzyć odmianę słowa "raz" lub "razy"
 */
function getNumeralEnding(numeral) {
    if (numeral == 1)  
        return "";
    else
    	return "y";
}

$.fn.changeCategory = function() {
    $(this).click(function(){
        category = $(this).attr('id');
        order = "published";
        start = 1;
        loadVideos();
        $(this).parent().parent().find("li a").removeClass("active");
        $(this).addClass("active");
        $('#videoSort a').removeClass("active");
        $('#videoSort a:first').addClass("active");
        return false;
    });
};

$.fn.changeSortOrder = function() {
    $(this).click(function(){
        order = $(this).attr('id');
        start = 1;
        loadVideos();
        $(this).parent().find("a").removeClass("active");
        $(this).addClass("active");
        return false;
    });
};
