YUI({
		combine:true, 
		timeout:10000, 
		modules:{
			'poller':{
				fullpath:'http://uus.fitness.ee/oksjon/js/yui/build/poller/poller-min.js',
				requires:['io-base','base']
			}
		}
	}
).use('base','anim', 'async-queue', 'poller', 'io-base', 'json-parse',function (Y){
 
var Oksjon = {

	NAME : 'FIT OKSJON',
 
    q : new Y.AsyncQueue(),
 
    nodes : {
        root    : null,
        status  : null,
        content : null
    },

    _renderFramework : function (container) {
        var root = Oksjon.nodes.root = Y.one(container);
        
        root.setContent(
                '<h1>FIT.OKSJON</h1>'+
		    	'<div class="wrapper">'+
		    		'<div class="clock"></div>'+
		    		'<div class="product">' +
			    		'<img alt="" src="" class="picture" width="90" height="90" /><br />' +
						'<a href="" class="name"></a>' +
		    		'</div>'+
		    		'<div class="bet">'+
		    			'<div class="price_holder show">'+
		    				'<div class="price_pre">hetke<br />hind</div>'+
		    				'<div class="price"></div>'+
		    				'<div class="price_after">fitti</div>'+
		    			'</div>'+
		    			'<div class="action">'+
		    			
			    			'<div class="login hide">'+
								'<span>Osalemiseks logi sisse</span>'+
							'</div>'+

							'<div class="prebet hide">'+
								'<span><button class="prebetbutton button">Paku &uuml;le</button></span>'+
							'</div>'+
	    					
			    			'<div class="makebet hide">'+
				    			'<fieldset>'+
				    				'<legend>Sinu pakkumine</legend>'+
				    				'<input class="betamount" type="text" size="1" value="" name="amount" /> fitti '+
				    				'<button class="betsubmit button">Ok</button>'+
				    				'<div class="betinfo">'+
				    					'<span class="fitamount">Sul on <span class="fitcount"></span> fitti |</span> '+
				    					'<a href="#" class="quitbuttton">Loobu</a>'+
				    				'</div>'+
				    			'</fieldset>'+
			    			'</div>'+

			    			'<div class="loadbet hide">'+
				    			'<fieldset>'+
				    				'<legend>Saadan</legend>'+
				    				'<div>'+
				    				'</div>'+
				    			'</fieldset>'+
		    				'</div>'+

		    				'<div class="thnks hide">'+
				    			'<fieldset>'+
				    				'<legend>T&auml;name</legend>'+
				    				'<div class="lastbet">'+
				    					'Pakkusid <span class="justbet"></span> fitti'+
				    				'</div>'+
				    				'<div class="betinfo">'+
			    						'Sul on veel <span class="fitcount"></span> fitti. <a href="#" class="quitbuttton">Ok</a>'+
			    					'</div>'+
				    			'</fieldset>'+
	    					'</div>'+

	    					'<div class="error hide">'+
				    			'<fieldset>'+
				    				'<legend>Viga</legend>'+
				    				'<div class="status_message">'+
				    					'Proovi hiljem uuesti'+
				    				'</div>'+
				    				'<div class="betinfo">'+
			    						'<a href="#" class="quitbuttton">Ok</a>'+
			    					'</div>'+
				    			'</fieldset>'+
	    					'</div>'+

			    		'</div>'+
		    			'<div class="info"></div>'+
		    			'<div class="reults"><a href="http://www.fitness.ee/?act=auction_list">Oksjoni tulemused</a></div>'+
		    		'</div>'+
		    	'</div>');

        Oksjon.nodes.wrapper = root.one('div.wrapper');
        Oksjon.nodes.clock = root.one('div.clock');
        
        Oksjon.nodes.product = root.one('div.product');
        Oksjon.nodes.product.image = Oksjon.nodes.product.one('img.picture');
        Oksjon.nodes.product.url = Oksjon.nodes.product.one('a.name');
        
        Oksjon.nodes.price = root.one('div.price');
        Oksjon.nodes.priceholder = root.one('div.price_holder');
        
        Oksjon.nodes.action = root.one('div.action');

        //login div
        Oksjon.nodes.login = root.one('div.login');
        //Oksjon.nodes.login.submit = root.one('button.loginbutton');
        
        //pakkumise nupu div
        Oksjon.nodes.prebet = root.one('div.prebet');
        Oksjon.nodes.prebet.raise = root.one('span.fittobet');
        Oksjon.nodes.prebet.submit = root.one('button.prebetbutton');
        
        //pakkumise tegemise div
        Oksjon.nodes.bet = root.one('div.makebet');
        Oksjon.nodes.bet.amount = Oksjon.nodes.bet.one('input.betamount');
        Oksjon.nodes.bet.submit = Oksjon.nodes.bet.one('button.betsubmit');
        Oksjon.nodes.bet.credit = Oksjon.nodes.bet.one('span.fitcount');
        Oksjon.nodes.bet.cancel = Oksjon.nodes.bet.one('a.quitbuttton');

        //loading
        Oksjon.nodes.loading = root.one('div.loadbet');

        //thanks
        Oksjon.nodes.thnks = root.one('div.thnks');
        Oksjon.nodes.thnks.credit = Oksjon.nodes.thnks.one('span.fitcount');
        Oksjon.nodes.thnks.lastbid = Oksjon.nodes.thnks.one('div.lastbet');
        Oksjon.nodes.thnks.bid = Oksjon.nodes.thnks.one('span.justbet');
        Oksjon.nodes.thnks.cancel = Oksjon.nodes.thnks.one('a.quitbuttton');

        //error
        Oksjon.nodes.error = root.one('div.error');
        Oksjon.nodes.error.message = Oksjon.nodes.error.one('div.status_message');
        Oksjon.nodes.error.cancel = Oksjon.nodes.error.one('a.quitbuttton');

        //tekstikast
        Oksjon.nodes.info = root.one('div.info');
        
        //fitikastid
        Oksjon.nodes.shopFitBalanceHdr = Y.one('#shopFitBalanceHdr');
		Oksjon.nodes.shopFitBalanceTop = Y.one('#shopFitBalanceTop');
		Oksjon.nodes.shopFitBalanceBtm = Y.one('#shopFitBalanceBtm');
        
        Oksjon.nodes.wrapper.setStyle('opacity',0);
        Oksjon.setStatus('Paku alates <span class="fittobet">'+Oksjon.fittobet+'</span> fitist');
    },
    
	pad : function(number) {
	    return (number < 10) ? '0' + number : number;
	},

	setCountDown : function(data){
		//first occourance of login status, decide to show login button if needed
		if(!data.user.logged_in){
			Oksjon.changeFocus(null, Oksjon.nodes.login);
		} else {
			Oksjon.changeFocus(Oksjon.nodes.login, Oksjon.nodes.prebet);
		}
		
		if(!Oksjon.countdown){
			Oksjon.endTime = data.response.Auction.end;

			Oksjon.currentUnixTimeStamp = data.response.timestamp;;

			Oksjon.countdown = data.response.Auction.end-(Oksjon.currentUnixTimeStamp);
			Oksjon.countDownTick();
			Oksjon.clockVariable = Y.later(1000, this, Oksjon.countDownTick, null, true);
		}
	},
	countDownTick : function(){
		Oksjon.countdown = Oksjon.countdown-1;
		Oksjon.nodes.clock.setContent(Oksjon._secondsToTime(Oksjon.countdown));
	},
    
	_secondsToTime : function(sec){
		
		var sec = parseInt(sec);
		var years, months, days, hours, minutes, seconds, content;
		
		if(sec < 0){
			return 'L&otilde;ppenud.';
		}
		
		if(sec>31556926){
			years = parseInt(sec/31556926); 
			sec = sec-(years*31556926);		
		}
		if(sec>2629743){
			months = parseInt(sec/2629743); 
			sec = sec-(months*2629743);	
		}
		if(sec>86400){
			days = parseInt(sec/86400); 
			sec = sec-(days*86400);
		}
		if(sec>3600){
			hours = parseInt(sec/3600);
			sec = sec-(hours*3600);
		} else {
			hours = '0';
		}
		if(sec>60){
			minutes = parseInt(sec/60);
			sec = sec-(minutes*60);
		} else {
			minutes = '0';
		}
	
		content = '';
		
		if(years)content+=this.pad(years)+':';
		if(months){ if(content)content+=''; content+=this.pad(months)+':'; }
		if(days){ if(content)content+='';  content+=this.pad(days)+':'; }
		if(hours||days){ if(content)content+=''; content+=this.pad(hours)+':'; }
		if(content)content+=''; content+=this.pad(minutes)+':'+this.pad(sec);
	
		return content;
		
	},

    render : function (container, data) {
	   
        if (Oksjon.nodes.root) {
            Oksjon.q.stop();
            Oksjon._renderContent
            return false;
        }
        
        Oksjon.q.add(
            // pass the container param to the callback using Y.bind
            Y.bind(Oksjon._renderFramework, Oksjon, container),
            Y.bind(Oksjon.setCountDown, Oksjon, data),
            Y.bind(Oksjon.mapData, Oksjon, data),
            Oksjon._renderContent
            
         ).run();
    },
 
    setStatus : function (message) {
        Oksjon.nodes.info.setContent(message);
    },

    changeFocus : function (current,target) {
    	Oksjon.activeDiv = target;
    	if(current){
        	current.replaceClass('show','hide');
    	}
        if(target){
        	target.replaceClass('hide','show');
        }
        
    },

    submitBet : function(e) {
		
    	var value = Oksjon.nodes.bet.amount.get('value');
		var betStart = Oksjon.fittobet;
		
		if(value < betStart){
			Oksjon.nodes.bet.amount.addClass('red');
			Oksjon.nodes.info.addClass('red');
		} else {
			
            Oksjon.setStatus('Salvestame sinu pakkumist');
            Oksjon.changeFocus(Oksjon.nodes.bet, Oksjon.nodes.loading);
			Oksjon.nodes.bet.amount.removeClass('red');
			
			var cfg = {
				method: "POST",
				headers: { 'X-Transaction': 'New Bet'},
				on: {
					complete: function(id, r){	
						Oksjon.doUpdate(id, null , r);
					}
				}
			};
			var auction = Oksjon.data.response.Auction.id;
			var betRequest = Y.io('/oksjon/json/bet/' + value + '/' + auction, cfg);
			
		}
	},

	doRequest : function (tx) {
		//console.log('doRequest');
		//console.log(tx);
	},
	
	doResponse : function (e, txId, r, args ) {
		//console.log(args);
	},
	
	doUpdate : function (txId, r, args ) {
		
		data = Y.JSON.parse(args.responseText);
		Oksjon.data = data;
		if(data.response.Auction != undefined){
			Oksjon.fittobet = parseInt(data.response.Auction.price_step)+parseInt(data.response.Auction.price);
	
			requestStatus = args.getResponseHeader('Bet');
			
			//if we hav a active auction node
			if (!Oksjon.nodes.root) {
				
				Oksjon.render('#auction', data);
				
	        } else {
	        	
	        	
	        	
	        	//first occourance of login status, decide to show login button if needed
	    		if(!data.user.logged_in){
	    			Oksjon.changeFocus(Oksjon.activeDiv, Oksjon.nodes.login);
	    		} else {
	    			
	    			//update fit count if needed
    				if(Oksjon.nodes.shopFitBalanceHdr){
    					Oksjon.nodes.shopFitBalanceHdr.setContent(Oksjon.data.user.fit_count);
					}
    				//update fit count if needed
					if(Oksjon.nodes.shopFitBalanceTop){
						Oksjon.nodes.shopFitBalanceTop.setContent(Oksjon.data.user.fit_count);
					}
					//update fit count if needed
					if(Oksjon.nodes.shopFitBalanceBtm){
						Oksjon.nodes.shopFitBalanceBtm.setContent(Oksjon.data.user.fit_count);
					}
					
	    			//if session as ended and somehow restored , hide login and display prebet
	    			if(Oksjon.nodes.login.getStyle('display') == 'block'){
	    				Oksjon.changeFocus(Oksjon.nodes.login, Oksjon.nodes.prebet);
	    			}
	    			//console.log(requestStatus);
	    			//if we have a betrequest, decide upon answer
	    			if(requestStatus == 'true'){
		    			//if betresponse has errors display error message
		    			if(Oksjon.data.status == 0){
		    				Oksjon.nodes.error.message.setContent(data.status_message);
		    				Oksjon.setStatus('Pakkumine ei &otilde;nnestunud!');
		    				Oksjon.changeFocus(Oksjon.nodes.loading, Oksjon.nodes.error);
		    			} else {
		    				Oksjon.nodes.thnks.lastbid.addClass('green');
		    				Oksjon.nodes.info.addClass('green');
		    				Oksjon.nodes.thnks.bid.setContent(Oksjon.data.user.last_bet);
		    				Oksjon.setStatus('Pakkumine on salvestatud');
		    				Oksjon.changeFocus(Oksjon.nodes.loading, Oksjon.nodes.thnks);	
		    			}
	    			}
	    			
	    			//@TODO refactor this logic to countDownTick method
	    			if(Oksjon.endTime!=data.response.Auction.end || data.response.Auction.end < data.response.timestamp ){
	    				Oksjon.endTime = data.response.Auction.end;
	    				Oksjon.currentUnixTimeStamp = data.response.timestamp;
	    				Oksjon.countdown = data.response.Auction.end-(Oksjon.currentUnixTimeStamp);
	    				Oksjon.clockVariable.cancel();
	    				Oksjon.clockVariable = Y.later(1000, this, Oksjon.countDownTick, null, true);
	    			}
	    			
	    			Oksjon.mapData(data, data.status_message);
	        	}
	        	
	        }
		}
	},
	
	mapData : function(data, status) {
				
		Oksjon.nodes.product.image.set('src',data.response.Auction.product_image);
		Oksjon.nodes.product.url.set('href',data.response.Auction.product_link);
		Oksjon.nodes.product.url.setContent(data.response.Auction.product_name);
		Oksjon.nodes.price.setContent(data.response.Auction.price);
	
		if(data.user.fit_count){
			Oksjon.nodes.bet.credit.setContent(data.user.fit_count);
			Oksjon.nodes.thnks.credit.setContent(data.user.fit_count);
		} else {
			Oksjon.nodes.bet.credit.setContent('0');
			Oksjon.nodes.thnks.credit.setContent('0');
		}
	},
	 
    _renderContent : function () {
        var content = Oksjon.nodes.action;
 		var wrapper = Oksjon.nodes.wrapper;
 
       	new Y.Anim({
            node : wrapper,
            to :   { opacity : 1 },
            duration : .4
        }).run();


       	//provide login functionality
       	/*
        Y.on('click',function (e) {
            e.preventDefault();
        }, Oksjon.nodes.login.submit);
        */

        //submit your bet
        Y.on('click',function (e) {
            e.preventDefault();
            Oksjon.changeFocus(Oksjon.nodes.priceholder);
            Oksjon.changeFocus(Oksjon.nodes.prebet,Oksjon.nodes.bet);
            Oksjon.nodes.bet.amount.setAttribute('value',Oksjon.fittobet);
            Oksjon.setStatus('Paku alates <span class="fittobet">'+Oksjon.fittobet+'</span> fitist');
        }, Oksjon.nodes.prebet.submit);

        Y.on('click',function (e) {
            e.preventDefault();
            Oksjon.submitBet();
        }, Oksjon.nodes.bet.submit);

        //cancel bet
        Y.on('click',function (e) {
	        e.preventDefault();
	        Oksjon.changeFocus(Oksjon.nodes.bet,Oksjon.nodes.prebet);
	        Oksjon.changeFocus(null,Oksjon.nodes.priceholder);
        }, Oksjon.nodes.bet.cancel);

        //cancel thnks message
        Y.on('click',function (e) {
            e.preventDefault();
            Oksjon.changeFocus(Oksjon.nodes.bet,Oksjon.nodes.prebet);
            Oksjon.nodes.info.removeClass('green');
            Oksjon.setStatus('Paku alates <span class="fittobet">'+Oksjon.fittobet+'</span> fitist');
            Oksjon.changeFocus(Oksjon.nodes.thnks,Oksjon.nodes.priceholder);
        }, Oksjon.nodes.thnks.cancel);

        //cancel errormessageh
        Y.on('click',function (e) {
            e.preventDefault();
            Oksjon.changeFocus(null,Oksjon.nodes.priceholder);
            Oksjon.changeFocus(Oksjon.nodes.error,Oksjon.nodes.prebet);
            Oksjon.setStatus('Paku alates <span class="fittobet">'+Oksjon.fittobet+'</span> fitist');
        }, Oksjon.nodes.error.cancel);
    },

    init : function(){

		if (Oksjon.nodes.root) {
			return false;
        }

		ticker = new Y.Poller({ url:'/oksjon/json', interval:4000, pauseInactive:true });
		ticker.on('request', Oksjon.doRequest );
		ticker.on('response', Oksjon.doResponse );
		ticker.on('modified', Oksjon.doUpdate );
		ticker.start();
    }
};

Y.on('click',function (e) {
	
    e.preventDefault();

    Oksjon.init();
},'#init');

if(Y.one('#auction')){
	Oksjon.init();
}

// expose the app structure
YUI.app = { Oksjon : Oksjon };
	
});
