/*
Copyright (c) 2006, Gustavo Ribeiro Amigo
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

*/

    function Sound(options) {
        
        this.options = options;
        if(this.options == undefined) this.options = new Object();
        
        if(!this.options.swfLocation) {
            this.options.swfLocation = "/SoundBridge.swf";
        }
    
        if(Sound.id_count == undefined) {
            Sound.id_count = 1;
        } else {
            Sound.id_count ++;
        }
        
        if(Sound.instances == undefined) {
            Sound.instances = new Object();
        }
        
        this.object_id = 'object_id_' + Sound.id_count;
        
        Sound.instances[this.object_id] = this;
        
        movie_swf = this.options.swfLocation;
        movie_id = this.object_id;
        
        movie_element = "";
        movie_element += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="0" height="0"'; 
        movie_element += ' id="' + movie_id+ '"'; 
        movie_element += ' align="middle">';
        movie_element += '<param name="movie" value="'+movie_swf+'" />';
        movie_element += '<param name="quality" value="high" />';
        movie_element += '<param name="bgcolor" value="#ffffff" />';
        movie_element += '<param name="FlashVars" value="id='+ movie_id +'"/>';
        movie_element += '<param name="allowScriptAccess" value="always"/>';
        movie_element += '<embed src="'+movie_swf+'" FlashVars="id='+ movie_id +'"'; 
        movie_element += ' allowScriptAccess="always" quality="high" bgcolor="#ffffff" width="0" height="0"'; 
        movie_element += ' name="' + movie_id + '" align="middle" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
        movie_element += '</object>';    

        if( document.getElementById('__sound_flash__') == undefined) {
            var element = document.createElement("div");
            element.id = "__sound_flash__";
            document.body.appendChild(element);
        }
        
        document.getElementById('__sound_flash__').innerHTML += movie_element;         
    }
    
    Sound.prototype.loadSound = function(url, streaming) {
        return Sound.__call('loadSound',this.object_id, url, streaming);
    }
    
    Sound.prototype.start= function() {
        return Sound.__call('start', this.object_id);
    }

    Sound.prototype.stop = function() {
        return Sound.__call('stop', this.object_id);
    }
    
    Sound.prototype.getId3 = function() {
        return Sound.__call('id3', this.object_id);
    }
    
	Sound.prototype.getPan = function() {
    	return Sound.__call('getPan', this.object_id);
	}
	
	Sound.prototype.getTransform = function() {
		return Sound.__call('getTransform', this.object_id);
	}
	
	Sound.prototype.getVolume = function(){
		return Sound.__call('getVolume', this.object_id);
	}
	
	Sound.prototype.setPan = function(value){
    	return Sound.__call('setPan', this.object_id, value);	
	}
	
	Sound.prototype.setTransform = function(transformObject){
    	return Sound.__call('setTransform', this.object_id, transformObject);
	}
	
	Sound.prototype.setVolume = function(value){
    	return Sound.__call('setVolume', this.object_id, value);
	}
	
	Sound.prototype.start = function(secondOffset, loops){
	    return Sound.__call('start', this.object_id, secondOffset, loops);
	}
	
	Sound.prototype.getDuration = function(){
	    return Sound.__call('getDuration', this.object_id);
	}
	
	Sound.prototype.setDuration = function(value){
	    return Sound.__call('setDuration', this.object_id, value);	
	}
	
	Sound.prototype.getPosition = function(){
        return Sound.__call('getPosition', this.object_id);		
	}
	
	Sound.prototype.setPosition = function(value){
	    return Sound.__call('setPosition', this.object_id, value);		
	}

	Sound.prototype.getBytesLoaded = function(){
	    return Sound.__call('getBytesLoaded', this.object_id);		
	}
	
	Sound.prototype.getBytesTotal = function(){
        return Sound.__call('getBytesTotal', this.object_id);			
	}
	
	Sound.prototype.onLoad = function(success){
        Sound.trace('Sound:onLoad('+success+') event triggered');
	}	
    
    Sound.onLoad = function(object_id, success) {
        //Sound.trace('Sound.onLoad('+success+') object_id=' + object_id);
        Sound.instances[object_id].onLoad(success);
    }
    
	Sound.prototype.onSoundComplete = function(){
        Sound.trace('Sound:onSoundComplete() event triggered');
	}	    
    
    Sound.onSoundComplete = function(object_id) {
        Sound.instances[object_id].onSoundComplete;
    }   
    
	Sound.prototype.onID3 = function(){
        Sound.trace('Sound:onID3() event triggered');
	}	    
    
    Sound.onID3 = function(object_id) {
        Sound.instances[object_id].onID3();        
    }    
    
    Sound.trace = function(value, isJavascript) {
        if(document.getElementById('sound_tracer') != undefined) {
            if(isJavascript == undefined || isJavascript == true) {
                document.getElementById('sound_tracer').value += 'Javascript: ' + value + '\n';            
            } else {
                document.getElementById('sound_tracer').value += value + '\n';            
            }
        }
    }  
    
    Sound.__thisMovie = function(movieName) {
        if (navigator.appName.indexOf("Microsoft") != -1) {
            return window[movieName]
        }
        else {
            return document[movieName]
        }
    }
    
    Sound.__call = function () {
        Sound.trace('Sound.__call '+ arguments[0]+ ' on object_id ' + arguments[1] );    
        var functionname = arguments[0];
        var object_id = arguments[1];        
        var justArgs = new Array();
        if (arguments.length > 1)   {
           for (var i = 2; i < arguments.length; i++ ) {
             justArgs.push(arguments[i]);
           }
        }
        return Sound.__thisMovie(object_id).proxyMethods(functionname, justArgs);
    } 
    
    Sound.userAgent =  function() {
		var UNDEF = "undefined",
			OBJECT = "object",
			SHOCKWAVE_FLASH = "Shockwave Flash",
			SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
			FLASH_MIME_TYPE = "application/x-shockwave-flash",
			EXPRESS_INSTALL_ID = "SWFObjectExprInst",
			
			win = window,
			doc = document,
			nav = navigator;
			
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF && typeof doc.appendChild != UNDEF && typeof doc.replaceChild != UNDEF && typeof doc.removeChild != UNDEF && typeof doc.cloneNode != UNDEF,
			playerVersion = [0,0,0],
			d = null;
		if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
			d = nav.plugins[SHOCKWAVE_FLASH].description;
			if (d) {
				d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
				playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
				playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			var a = null, fp6Crash = false;
			try {
				a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
			}
			catch(e) {
				try { 
					a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
					playerVersion = [6,0,21];
					a.AllowScriptAccess = "always";  // Introduced in fp6.0.47
				}
				catch(e) {
					if (playerVersion[0] == 6) {
						fp6Crash = true;
					}
				}
				if (!fp6Crash) {
					try {
						a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
					}
					catch(e) {}
				}
			}
			if (!fp6Crash && a) { // a will return null when ActiveX is disabled
				try {
					d = a.GetVariable("$version");  // Will crash fp6.0.21/23/29
					if (d) {
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				catch(e) {}
			}
		}
		var u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = false,
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u);
		/*@cc_on
			ie = true;
			@if (@_win32)
				windows = true;
			@elif (@_mac)
				mac = true;
			@end
		@*/
		return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
	};
var Base64 = function() {
            var _key = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
            var _keyRe = new RegExp("[^" + _key + "=]", "g");
            return {
                encode: function(input) {
                    var output = "";
                    var len = input.length, i = 0, padding = 3 - (len % 3);
                    while (i < len) {
                        var byte1 = input.charCodeAt(i++);
                        var byte2 = input.charCodeAt(i++) || 0;
                        var byte3 = input.charCodeAt(i++) || 0;
                        var index1 = byte1 >> 2;
                        var index2 = (byte1 & 3) << 4 | byte2 >> 4;
                        var index3 = (byte2 & 15) << 2 | byte3 >> 6;
                        var index4 = byte3 & 63;
                        output += _key.charAt(index1) + _key.charAt(index2) + _key.charAt(index3) + _key.charAt(index4);
                    }
                    if (padding)
                        output = output.slice(0, output.length - padding) + (padding == 1 ? "=" : "==");
                    return output;
                },
                decode: function(input) {
                    input = input.replace(_keyRe, "");
                    var output = "";
                    var i = 0, len = input.length, padding = (input.indexOf("=")>0) ? (len - input.indexOf("=")) : false;
                    while (i < len) {
                        var byte1 = _key.indexOf(input.substr(i++, 1));
                        var byte2 = _key.indexOf(input.substr(i++, 1));
                        var byte3 = _key.indexOf(input.substr(i++, 1));
                        var byte4 = _key.indexOf(input.substr(i++, 1));
                        var char1 = byte1 << 2 | byte2 >> 4;
                        var char2 = ((byte2 & 15) << 4) | (byte3 >> 2);
                        var char3 = ((byte3 & 3) << 6) | byte4 & 63;
                        output += String.fromCharCode(char1) + String.fromCharCode(char2) + String.fromCharCode(char3);
                    }
                    if (padding)
                        output = output.substr(0, output.length - padding);
                    return output;
                }
            };
        } ();
var snd = false;
var ringtone = false;
var updateTimer = false;
var updateProgress = function(){
    if(snd.loading && ((!snd.getBytesTotal()) || (snd.getBytesLoaded()>snd.getBytesTotal()/3))){
        snd.start(0); 
        snd.loading = false; 
    }
    width = this.getElement('.progress').getSize().size.x - 2;
    if(snd.getBytesLoaded()==snd.getBytesTotal()) snd.fileDuration = snd.getDuration();
    if(snd.getPosition()==snd.fileDuration){
            clearInterval(updateTimer);
            $$('#ringtones .ringtone, #ringtone .playing').removeClass('playing');
            $$('#ringtones .progress div, #ringtone .progress div').setStyle('width', 0);
            snd.start(0);
            snd.stop();
    } else {
        this.getElement('.progress div div').setStyle('width', snd.getPosition()/snd.fileDuration*width);
        if(snd.getBytesTotal()) 
            this.getElement('.progress div').setStyle('width', snd.getBytesLoaded()/snd.getBytesTotal()*width);
        else
            this.getElement('.progress div').setStyle('width', width);
    }
}

window.addEvent('domready', function(){
    snd = new Sound({swfLocation : '/Static/js/lib/sound/SoundBridge.swf'});
    if(Sound.userAgent().pv[0]>7){
        $$('#ringtones a.play, #ringtone a.play').addEvent('click', function(ev){
            this.blur();
            (new Event(ev)).preventDefault();
            var playing = this.getParent().hasClass('playing');
            clearInterval(updateTimer);
            snd.start(0);
            snd.stop();
            $$('#ringtones .ringtone, #ringtone .playing').removeClass('playing');
            $$('#ringtones .progress div, #ringtone .progress div').setStyle('width', 0);
            if(!playing){
                ringtone = Base64.decode(this.rel);
                snd.loadSound(ringtone, true);
                if(snd.getBytesTotal()!=undefined) snd.stop();
                snd.loading = true;
                snd.fileDuration = this.getProperty('duration');
                updateTimer = setInterval( updateProgress.bind(this.getParent()), 500);
                updateProgress.bind(this.getParent())();
                this.getParent().addClass('playing');
            }
        });
        $$('#homeringtones a span').addEvent('click', function(ev){
			(new Event(ev)).preventDefault().stop().stopPropagation();
            clearInterval(updateTimer);
            snd.start(0);
            snd.stop();
            var playing = this.hasClass('playing');
            $$('#homeringtones a span').removeClass('playing');
            if(!playing){
                snd.loadSound(Base64.decode(this.getProperty('rel')), true);
                snd.loading = true;
                snd.fileDuration = this.getProperty('duration');
                this.addClass('playing');
                updateTimer = setInterval(function(){
				    if(snd.getBytesLoaded()==snd.getBytesTotal()) snd.fileDuration = snd.getDuration();
					if((snd.getPosition()==snd.fileDuration) && (snd.getBytesLoaded()==snd.getBytesTotal())){
			            clearInterval(updateTimer);
						snd.stop();
						snd.setPosition(0);
			            $$('#homeringtones a span').removeClass('playing');
					}
                }, 500);
            }
        });
    } else {
        $('flashwarning').setStyle('display', 'block');
    }
});
