var Stat = Class.create();
Stat.prototype = {
	initialize: function(product_id) {
		this.product_id = product_id;
        this.start_time = new Date().getTime();
        this.stopped = false;
        this.error = 0;
	},

    get_duration: function() {
        if(this.has_error())
            return 0;

        this.terminate();
        return Math.round((this.end_time - this.start_time)/1000);
    },

    get_product_id: function() {
        return this.product_id;
    },

    has_error: function() {
        return this.error;
    },

    set_error: function() {
        this.error = 1;
    },
    
    stop: function() {
        this.terminate();
        this.stopped = true;
    },
    
    terminate: function() {
        if(!this.is_stopped())
            this.end_time = new Date().getTime();
    },
    
    is_stopped: function() {
        return this.stopped;
    }
};

var AudiolibController = Class.create();
AudiolibController.prototype = {
	initialize: function(flash, language) {
		this.products = [];
		this.position = 0;
		this.currentAsset = null;
		this.audiolib = null;
		this.flash = flash;
		this.playPolicy = null;
		this.isPaused = false;
		this.isRadio = true;
    this.language = language;
    this.stats = $A();
        
    new PeriodicalExecuter(this.statsUpdater.bindAsEventListener(this), stats_commit_period);
	},
	
	setProducts: function(products) {
		this.products = [];
		for (i=0; i<products.length; i++) {
			prodId = parseInt(products[i]);
			this.products.push(prodId);
		}
		
	},
	
	setPosition: function(position) {
		this.position = parseInt(position);
	},
	
	setPlayPolicy: function(playPolicy) {
		this.playPolicy = parseInt(playPolicy);
	},
	
	audioLibListener: function(missingPluginListener, event_type, attribute, url) {
		updateStatusLine = true;
		if ('missingPlugin' == event_type || 'notSupportedProduct' == event_type) {
			missingPluginListener(event_type, attribute, url);
		} else {
			if ('pluginStatus' == event_type && 'playing' == attribute.toLowerCase()) {
				try {
					attribute = this.audiolib.description;
				} catch (err) {
				}
			}
			if ('pluginStatus' == event_type && 'WMPReplay' == attribute) {
			    updateStatusLine = false;
				attribute = __('Connecting');
				this.play();
			}
			if (updateStatusLine) {
				this.flash.UpdateStatusLine(attribute);
			}	
		}
	},
	
	getAudioLib: function(missingPluginListener) {
		if ('function' == typeof missingPluginListener) {
			this.audiolib = AudioLib.getPlayer(this.audioLibListener.bind(this, missingPluginListener), this.language);
		}
		return this.audiolib;
	},
	
	setCurrentAsset: function() {
		this.currentAsset = new ProductAsset("", "", "", 0);
	},
	
	setAtomicProduct: function(productId) {
		this.setProducts([productId]);
		this.setPosition(0);
		this.isRadio = true;
		//this.attemptToPlay();
	},
	
	setCompositeProduct: function(productIds, initialPosition, playPolicy) {
		this.setProducts(productIds);
		this.setPosition(initialPosition);
		this.setPlayPolicy(playPolicy);
		this.isRadio = false;
		//this.attemptToPlay();
	},
	
		
	setNewAsset: function(newAsset) {
		this.currentAsset = newAsset;
	},
	
	attemptToPlay: function() {
		if (null == this.audiolib) {
			return false;
		}
		//this.setCurrentAsset();
		if (!this.isPaused) {
		// setting .mov redirect for wma and asf radios
		try {
			this.currentAsset.getCodec();
		} catch (err) {
			this.currentAsset = new ProductAsset("", "", "", 0);
		}
		if ('wma' == this.currentAsset.getCodec().toLowerCase() || 'asf' == this.currentAsset.getCodec().toLowerCase()) {
			this.isRadio = false;
		}
		this.audiolib.setAsset(new Asset(this.currentAsset.getCodec(), this.currentAsset.getUrls(), this.isRadio));
		this.audiolib.description = this.currentAsset.getDescription();
		}
		this.stats.push(new Stat(this.currentAsset.getProductId()));
		try {
			this.audiolib.play();
		} catch(err) {}
	},

	play: function() {
		if (null != this.audiolib) {
			if (this.isPaused){
					this.audiolib.play();
			} else
			this.attemptToPlay();
			this.isPaused = false;
		}
	},
	
	stop: function() {
		this.isPaused = false;
		if (null != this.audiolib) {
			try {
			this.audiolib.stop();
		    if(this.stats.last())
			     this.stats.last().stop();
			 } catch(err){}
		}
	},
	
	pause: function() {
		this.isPaused = true;
		if (null != this.audiolib) {
			try {
			this.audiolib.pause();
			this.isPaused = true;
			if(this.stats.last())
                this.stats.last().stop();
			} catch(err){}
		}
	},
	
	setVolume: function(volume) {
		if (null != this.audiolib) {
			this.audiolib.setVolume(10 * volume);
		}
	},

	next: function() {
		if (this.products.length > (this.position + 1)) {
			this.position++;
			getAssetJSNI("", this.products[this.position]);
		}
	},
	
	previous: function() {
		if (this.position > 0) {
			this.position--;
			getAssetJSNI("", this.products[this.position]);
		}
	},
	
	statsUpdater: function() {
	   if(audio_player.stats.length > 0) {
	       var products = $A();
	       var durations = $A();
	       var errors = $A();
	       var active_product = -1;
	       	       
	       audio_player.stats.each(function(s) {
				 		if(s.get_duration() > 0) {
		           products.push(s.get_product_id());
		           durations.push(s.get_duration());
	  	         errors.push(s.has_error());
	           
	    	       if(!s.is_stopped())
	      	         active_product = s.get_product_id();
						 }
	       });
	       
	       audio_player.stats = $A();
	       if(active_product > 0)
	           audio_player.stats.push(new Stat(active_product));
	       pushStatsJSNI(products, durations, errors);
	   }
	}
}
