﻿/// <reference path="MicrosoftAjax.debug.js" />
/// <reference path="cookies.js" />

Type.registerNamespace('Insys');

Insys.AudioPlayer = function() 
{
}

Insys.AudioPlayer.prototype =
{
	handleLoad: function(control, userContext, rootElement) 
	{
	    this._isResumed = false;
		this.control = control;
		this._media = control.content.findName("MediaElement");
		this._infoText = control.content.findName("InfoText");
		this._bufferingText  = control.content.findName("BufferingText");
		this._playButton  = control.content.findName("PlayTrackButton");
		this._pauseButton  = control.content.findName("PauseTrackButton");
		
		this._initTextTop = this._infoText.GetValue("Canvas.Top");
		
		this._media.addEventListener("CurrentStateChanged", Function.createDelegate(this, this._handleMediaStateChanged));
		this._media.addEventListener("MediaOpened",  Function.createDelegate(this, this._handleMediaOpened));
		this._media.addEventListener("MediaEnded",  Function.createDelegate(this, this._playNextTrack));
		this._media.addEventListener("BufferingProgressChanged", Function.createDelegate(this, this._bufferProgressChanged));

		this._label = $get("errorLocation");
		control.content.findName("PlayPauseButton").addEventListener("MouseLeftButtonDown", Function.createDelegate(this, this._togglePlayPause));
		control.content.findName("NextTrackButton").addEventListener("MouseLeftButtonDown", Function.createDelegate(this, this._playNextTrack));
		control.content.findName("PreviousTrackButton").addEventListener("MouseLeftButtonDown", Function.createDelegate(this, this._playPreviousTrack));
		control.content.findName("VolumeUpButton").addEventListener("MouseLeftButtonDown", Function.createDelegate(this, this._volumeUp));
		control.content.findName("VolumeDownButton").addEventListener("MouseLeftButtonDown", Function.createDelegate(this, this._volumeDown));

		$addHandler(window, "unload", Function.createDelegate(this, this._saveState));

		this._tracklist = new Array();
		this._currentTrackIndex = 0;	
	    this._currentTrack = null;
	    
	    var resumeVolume = readCookie("opener_audio_volume");
	    if (resumeVolume != null && resumeVolume != '') {
	        this._media.Volume = resumeVolume;
	    }
	    
	    this._initTracklist();
	},

    _loadTrack: function(index) {
        if (index == null) {
            index = 1;
        }
        this._currentTrackIndex = index;
        this._currentTrack = this._tracklist[index];
        this._media.Source = this._currentTrack.Url;
        this._infoText.Text = this._currentTrack.Artist + ' - ' + this._currentTrack.Title
        
        var newTop = ((this._infoText.Height - this._infoText.ActualHeight) / 2) + this._initTextTop;
        this._infoText.SetValue("Canvas.Top", newTop);
    },
    
    _volumeUp: function() {
        this._media.Volume += 0.1;
    },
    
    _volumeDown: function() {
        this._media.Volume -= 0.1;        
    },
    
    _playNextTrack: function() {
        var next = ((this._currentTrackIndex + 1) % this._tracklist.length);
        //this._label.innerHTML += 'Index: ' + next + '<br/>';
        this._loadTrack(next);
    },
    
    _playPreviousTrack: function() {
        var prev = ((this._currentTrackIndex - 1) % this._tracklist.length);
        if (prev == -1) {
            prev = this._tracklist.length - 1;
        }
        //this._label.innerHTML += 'Index: ' + prev + '<br/>';
        this._loadTrack(prev);
    },
    
    _findTrackIndex: function(trackId) {
        for (var i = 0; i < this._tracklist.length; i++) {
            if (this._tracklist[i].TrackId == trackId) {
                return i;
            }
        }
        
        return 1;
    },
    
    _initTracklist: function() {
        Insys.Opener2008.Frontend.OpenerWS.GetAudioTracks(Function.createDelegate(this, this._tracklistLoaded), null, this);
    },
    
    _tracklistLoaded: function(result, eventArgs) {
        this._tracklist = result;

        var resumeTrackId = readCookie("opener_audio_track");
        if (resumeTrackId != null) {
            this._loadTrack(this._findTrackIndex(resumeTrackId));
        }
        else {
            this._loadTrack();
        }
    },
        
    _saveState: function() {
        if (this._media.CurrentState == "Playing") {
            createCookie("opener_audio_position", this._media.Position.seconds);
            createCookie("opener_audio_track", this._currentTrack.TrackId);
            createCookie("opener_audio_volume", this._media.Volume);
        } else {
            eraseCookie("opener_audio_position");
            eraseCookie("opener_audio_track");
            eraseCookie("opener_audio_volume");
        }
    },
    
    _resume: function() {
        if (this._isResumed) {
            return;
        }
        this._isResumed = true;
        var resumeSeconds = readCookie("opener_audio_position");
        if (resumeSeconds) {
            this._togglePlayPause();
            var position = this._media.Position;
            position.seconds = resumeSeconds;
            this._media.Position = position;
            
            
//            this._label.innerHTML += 'CookiePos: ' + resumeSeconds + '<br/>';
//            this._label.innerHTML += 'MediaPos: ' + this._media.Position.seconds + '<br/>';
//            this._label.innerHTML += 'RESUMED <br/>';
        }
        //alert(resumeSeconds);
    },
    
    _handleMediaOpened: function() {
        this._resume();
    },
    
    _handleMediaStateChanged: function() {
//        this._label.innerHTML += this._media.CurrentState + '(' + this._media.Position.seconds + ') <br/>';
//        if (!this._isResumed && this._media.CurrentState == 'Stopped') {
//            this._resume();
//        }
    },
    
	_togglePlayPause: function() {
		if (this._media.CurrentState == 'Paused' || this._media.CurrentState == 'Stopped') {
		    this._media.AutoPlay = true;
            this._media.Play();
            this._playButton.Visibility = 'Collapsed';
            this._pauseButton.Visibility = 'Visible';
		} else if (this._media.CurrentState == 'Playing') {
            this._media.AutoPlay = false;
            this._media.Pause();
            this._playButton.Visibility = 'Visible';
            this._pauseButton.Visibility = 'Collapsed';
		}
	},

    _bufferProgressChanged: function(sender, eventArgs) {
        
        this._bufferingText.Text = Math.round(sender.bufferingProgress * 100).toString() + "%";

        if (sender.bufferingProgress == 1.0 || sender.bufferingProgress == 0.0)
        {
            this._bufferingText.Visibility = "Collapsed";
        }
        else
        {
            this._bufferingText.Visibility = "Visible";
        }
    }
}


function createAudioPlayer()
{
    if (!Silverlight.isInstalled('1.0')) {
        return false;
    }
	var scene = new Insys.AudioPlayer();
	Silverlight.createObjectEx({
		source: "/xaml/AudioPlayer.xaml",
		parentElement: $get("radioHost"),
		id: "AudioPlayerSilverlightControl",
		properties: {
			width: "267px",
			height: "42px",
			version: "1.0",
			isWindowless: "true",
			background: "transparent"
		},
		events: {
			onLoad: Function.createDelegate(scene, scene.handleLoad),
			onError: null
        }
	});
	
	return true;
}