/**
 * @author Wrzasq <wrzasq@gmail.com>
 * @copyright 2008 - 2009 (C) by Wrzasq
 * @package WrzasqCMF
 * @version 0.0.1
 */

// portfolio preview
var portfolio;

// switches list page
function getPortfolioPageSwitcher(page)
{
    return function(event) {
    	portfolio.pagination.page = page;

    	portfolio.reload();

        event.stop();
    };
}

// initializes JavaScript interface
document.observe("dom:loaded", function() {
	portfolio = $("portfolio");

    // pagination
	$(portfolio.parentNode).getElementsBySelector(".pagination").each( function(element) {
		portfolio.pagination = element;
    } );

    // if not exists create new node
    if(!portfolio.pagination)
    {
    	portfolio.pagination = new Element("div", {
    		"class": "pagination"
    	} );
        $(portfolio.parentNode).insert(portfolio.pagination);
    }

    portfolio.pagination.page = 1;

    // checks current page
    portfolio.pagination.getElementsBySelector("span").each( function(element) {
    	$A(element.childNodes).each( function(child) {
    		if(child.nodeType == 3)
    		{
    			portfolio.pagination.page = child.nodeValue;
    		}
    	} );
    } );

    // pager
    portfolio.pagination.getElementsBySelector("a").each( function(element) {
    	element.observe("click", getPortfolioPageSwitcher( element.href.toQueryParams().page ) );
    } );

    // fetches list
    portfolio.reload = function() {
		new Ajax.Request("/ajax.php", {
			parameters: {
                action: "Portfolio",
                page: this.pagination.page
            },
			onSuccess: function(transport) {
				var list = transport.responseJSON.Portfolio.data;
				
		        // cleans list
				this.update();

				var site;
				var element;

		        // adds portfolio project
		        for(var id in list.sites)
		        {
		    		site = list.sites[id];

		    		element = new Element("div");
		    		
		    		// thumbnail
		    		if(site.image && site.image.length > 0)
		    		{
		    			element.insert( new Element("img", {
		    				src: site.image,
		    				alt: site.name
		    			} ) );
		    		}

		    		this.insert( element.insert( new Element("h1").update( new Element("a", {
		    			href: "/portfolio/" + id + ".html",
		    			title: site.name
		    		} ).update(site.name) ) ).insert( new Element("p").update(site.content + "…") ).insert( new Element("a", {
		    			href: site.url
		    		} ).update("Strona projektu") ) );
		        }
		        
		        // clears old pager content
		        this.pagination.update();

		        // checks if paginaton should be added
		        if(list.pages.count > 1)
		        {
		            this.pagination.paginate( parseInt(list.pages.count), parseInt(list.pages.current), list.pages.link, getPortfolioPageSwitcher);
		        }
			}.bindAsEventListener(this)
		} );
    };
} );

