var Concertmedia = (function() {
    var files = new Array();
    
    var detectCollision = function(targ, mouseX, mouseY){
        var pos = targ.offset();
        return pos.left + targ.outerWidth() > mouseX && mouseX  >= pos.left && pos.top + targ.outerHeight() > mouseY && mouseY >= pos.top;
    }
	
	var minutes = function(seconds){
		var mins = Math.floor(seconds / 60);
		var secs = seconds >= 60 ? Math.floor(seconds - mins * 60) : Math.floor(seconds);
		mins = mins < 10 ? '0' + mins : mins;
		secs = secs < 10 ? '0' + secs : secs;
	return mins + ':' + secs;
	}
    
    var File = function(obj){
        this.id = 'player_' + files.length;
        this.type = obj.type;
        this.playerContainer = $('<div id="'+this.id+'" />');
		this.flContainer = $('<div class="flash-container"/>');
		this.flContainer.prepend(this.playerContainer);
        obj.container.prepend(this.flContainer);
        this.controlsContainer = $(controlsTemplate);
        this.controls = this.controlsContainer.find('.jp-interface');
        
        obj.container.append(this.controlsContainer);
        var scope = this;
		
		this.init = function(){
			scope.controls.find('.jp-current-time').text('00:00');
		}
		
        this.buffer = function(args){
            scope.controls.find('.jp-seek-bar').css('width', Math.round(args.bufferPercent)+'%');
        }
        
        this.isPlaying = function(){
            $.each(files, function(i, item){
                if(item.id != scope.id && (jwplayer(item.id).getState() == "PLAYING" || jwplayer(item.id).getState() == "BUFFERING")){
                    jwplayer(item.id).pause(true);
                }
            });

            scope.controls.find('.jp-play').hide().closest('.jp-controls').find('.jp-pause').show();
			
            try{
                //console.log('player state:'+jwplayer(scope.id).getState())
            }catch(err){}
        }
        
        this.isPaused = function(){
            if(jwplayer(scope.id).getState() == "IDLE"){
                scope.controls.find('.play-bar').css('width', '0');
            }
            scope.controls.find('.jp-pause').hide().closest('.jp-controls').find('.jp-play').show();
        }
        
        this.progress = function(args){
            var percentPlayed = 100 / args.duration * args.position;
            var newWidth = scope.controls.find('.jp-progress').outerWidth() / 100 * percentPlayed;
            scope.controls.find('.jp-play-bar').css('width', newWidth+'px');
			scope.controls.find('.jp-current-time').text(minutes(args.position));
			scope.controls.find('.jp-duration').text(minutes(args.duration));
        }
        
        this.seek = function(event){
            var pos = event.pageX - $(this).offset().left;
            var percent = 100 / $(this).outerWidth() * pos;
            var length = jwplayer(scope.id).getDuration();
            var newTime = length / 100 * percent;
            jwplayer(scope.id).seek(newTime);
        }
    
        this.outputError = function(args){
            try{
                console.log(args.message)
            }catch(err){}
        }
        
        this.controls.find('.jp-pause').hide();
        
        this.controls.find('.jp-play').click(function(){
            jwplayer(scope.id).play();
            scope.isPlaying();
            
            return false;
        });
        
        this.controls.find('.jp-pause').click(function(){
            jwplayer(scope.id).pause(true);
            scope.isPaused();
            
            return false;
        });
		
		this.controls.find('.jp-stop').click(function(){
			jwplayer(scope.id).stop();
		});
        
        this.controls.find('.jp-progress').click(this.seek);
        
        //Player Setup
        jwplayer(this.id).setup({
            'flashplayer': '/media/js/jw_player/player.swf',
            'id': this.id,
            'width': '1',
            'height': '1',
            'file': obj.url,
            'controlbar.position': 'none'
        })
		.onReady(this.init)
        .onPlay(this.isPlaying)
        .onTime(this.progress)
        .onPause(this.isPaused)
		.onIdle(this.isPaused)
        .onComplete(this.isPaused)
        .onBufferChange(this.buffer)
        .onError(this.outputError)
    };
    
    var controlsTemplate =  '<div class="jp-audio">'+
		'<div class="jp-type-single">' +
			'<div class="jp-gui jp-interface">' +
				'<ul class="jp-controls">' +
					'<li><a href="javascript:;" class="jp-play" tabindex="1">play</a></li>' +
					'<li><a href="javascript:;" class="jp-pause" tabindex="1">pause</a></li>' +
					'<li><a href="javascript:;" class="jp-stop" tabindex="1">stop</a></li>' +
				'</ul>' +
				'<div class="jp-progress">' +
					'<div class="jp-seek-bar">' +
						'<div class="jp-play-bar"></div>' +
					'</div>' +
				'</div>' +
				'<div class="jp-time-holder">' +
					'<div class="jp-current-time"></div>' +
					'<div class="jp-duration"></div>' +
				'</div>' +
			'</div>' +
			'<div class="jp-no-solution">' +
				'<span>Update Required</span>' +
				'To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>.' +
			'</div>' +
		'</div>' +
		'</div>'
    return {
        addFile: function(obj){
            files.push(new File(obj));
            //$('.video div').css('position', 'absolute');
        }
    }
})();
