var n = {
	debug	: 0,
	
	domain		: '',

        url         : 'index.php?eID=n',
	
	log 	: function(){
		if( !this.debug)return;
		
		for( i=0; i<arguments.length; i++)
			console.log(i+' : '+arguments[i]);
	},	

        doAjax  : function(el){
            new Ajax.Request(n.url, {
                    onSuccess	: function(tr){
                        el.update(n.getData(tr.responseText));
                    },
                    onCreate	: function(){
                          el.update(n.displaySpinner());
                    },

                    parameters	: { 'data' : $H({
                            'doAjax'		: el.getAttribute('doajax')
                    }).toJSON() }
            });
            return false;
        },

	displaySpinner	: function(){
		return '<img src="'+this.domain+'fileadmin/templates/img/spinner.gif" />';
	},

        sendData    : function(data){
            return '***json***'+data+'***json***';
        },

        getData     : function(data){
            data = data.split('***json***');
            return data[1];
        },

        refreshDomElements  : function(){
            $$('.doAjax').each(function(el){
                el.stopObserving('click');
                    el.observe('click',function(event){
                        n.doAjax(event.element());
                    });
            });
        },

	/**
	 * display confirm alert
	 */
	confirm	: function(confirmMSG){
	    return confirm(confirmMSG);
	}
}


var Cookies = Class.create({
    initialize: function(path, domain) {
        this.path = path || '/';
        this.domain = domain || null;
    },
	
    // Sets a cookie
    set: function(key, value, days) {
        if (typeof key != 'string') {
            throw "Invalid key";
        }
        if (typeof value != 'string' && typeof value != 'number') {
            throw "Invalid value";
        }
        if (days && typeof days != 'number') {
            throw "Invalid expiration time";
        }
        var setValue = key+'='+escape(new String(value));
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var setExpiration = "; expires="+date.toGMTString();
        } else var setExpiration = "";
        var setPath = '; path='+escape(this.path);
        var setDomain = (this.domain) ? '; domain='+escape(this.domain) : '';
        var cookieString = setValue+setExpiration+setPath+setDomain;
        document.cookie = cookieString;
    },
    // Returns a cookie value or false
    get: function(key) {
        var keyEquals = key+"=";
        var value = false;
        document.cookie.split(';').invoke('strip').each(function(s){
            if (s.startsWith(keyEquals)) {
                value = unescape(s.substring(keyEquals.length, s.length));
                throw $break;
            }
        });
        return value;
    },
    // Clears a cookie
    clear: function(key) {
        this.set(key,'',-1);
    },
    // Clears all cookies
    clearAll: function() {
        document.cookie.split(';').collect(function(s){
            return s.split('=').first().strip();
        }).each(function(key){
            this.clear(key);
        }.bind(this));
    }
});

var ratings = Class.create({
	cookies	: new Cookies(),
	
	url		: 'index.php?eID=n_ratings',

	mouseOut	: function(el){
		var parent = el.parentNode.parentNode.parentNode;
		var voteValue = el.getAttribute('class').replace('vote_link_','');
		var ref = parent.id.replace('_vote','').replace('tx_nratings_pi1_','');

                //n.log(voteValue,ref);
                $('tab_tx_nratings_pi1_'+ref).update('');



		return false;
	},

	mouseOver	: function(el){
		var parent = el.parentNode.parentNode.parentNode;
		var voteValue = el.getAttribute('class').replace('vote_link_','');
		var ref = parent.id.replace('_vote','').replace('tx_nratings_pi1_','');

                //n.log(voteValue,ref);
                //$('tab_tx_nratings_pi1_'+ref).update('<img src="fileadmin/templates/img/vote_'+voteValue+'.png" />');
                $('tab_tx_nratings_pi1_'+ref).update('<span class="vote-value-'+voteValue+'">&nbsp;</span>');
                
		return false;
	},

	saveVote	: function(el){
		var parent = el.parentNode.parentNode.parentNode;
		var voteValue = el.getAttribute('class').replace('vote_link_','');
		var ref = parent.id.replace('_vote','').replace('tx_nratings_pi1_','');
		
		new Ajax.Request(ratings.url, {
			onSuccess	: function(tr){
				ratings.checkView();
			},
			onCreate	: function(){
				parent.update(n.displaySpinner());
			},
			
			parameters	: { 'data' : $H({
				'ref'		: ref,
				'voteValue'	: voteValue
			}).toJSON() }
		});		
		
		return false;
	},
			
	/**
	 * na podstawie ciasteczka wyświetla widok głosowania lub wyniki
	 */
	checkView	: function(){
		$$('.ratings_vote').each(function(el){
			var ref = el.id.replace('_vote','');
			
			if( ratings.cookies.get(ref) ){
				// już głosowano
                                n.log(ref+' glosowano');
				el.hide();
                                n.log('jus glosowano');
				$(ref+'_results').select('span')[0].style.width = parseInt(ratings.cookies.get(ref))*(16)+'px';
				$(ref+'_results').show();

                                //$(ref+'_results').select('.r_tab')[0].update('<img src="fileadmin/templates/img/vote_'+parseInt(ratings.cookies.get(ref))+'.png" />');
                                $(ref+'_results').select('.r_tab')[0].update('<span class="vote-value-'+parseInt(ratings.cookies.get(ref))+'">&nbsp;</span>');

			} else {
				el.show();
                                n.log(ref+' nie glosowano');
				$(ref+'_results').hide();				
			}
		});		
	},	
			
	/**
	 * szuka wszystkich ocen na stronie i odsłania/zasłania wyniki na podstawie ciasteczka
	 */
	init	: function(){
		/**
		 * obserwować wszystkie linki z elementów z klasą vote_links
		 */
		$$('.vote_links a').each(function(el){
			el.observe('click',function(event){event.stop();ratings.saveVote(event.element());},false);
                        el.observe('mouseover',function(event){event.stop();ratings.mouseOver(event.element());},false);
			el.observe('mouseout',function(event){event.stop();ratings.mouseOut(event.element());},false);
		});
		this.checkView();

		
	}
	
});

var nAjax = Class.create({
    url     : 'index.php?eID=n',
    
    initialize: function(){   
    },

    elements    : Array(),

    updatePage  : function(boxes){
        for(i=0; i<nAjax.elements.length; i++){
            if( boxes[i] ){
                $(nAjax.elements[i]).update(boxes[i]);
            }
        }
    },

    init: function(){
        $$('.ajax').each(function(el){
           nAjax.elements.push(el.getAttribute('id'));
        });
n.log( 'pobieram: '+nAjax.elements.join(', '));

        new Ajax.Request(nAjax.url, {
                onSuccess	: function(tr){
                    tr = tr.responseText;
                    nAjax.updatePage(n.getData(tr).split('|'));
                    n.refreshDomElements();
                },
                onCreate	: function(){
                },

                parameters	: { 'data' : $H({
                        'elements'	: nAjax.elements.join(','),
                        'ajax_info'     : $('ajax_info').innerHTML
                }).toJSON() }
        });
        
    }
});

document.observe("dom:loaded", function(){		
	ratings = new ratings();
	ratings.init();

        //nAjax = new nAjax();
        //nAjax.init();

        n.refreshDomElements();
});