// ==UserScript==
// @name           dAudible
// @namespace      Zikes
// @include        http://chat.deviantart.com/chat/*
// ==/UserScript==

unsafeWindow.sounds=sounds=[
	'http://gm.thezikes.org/daudible/sound1.wav',
	'http://gm.thezikes.org/daudible/sound2.wav',
	'http://gm.thezikes.org/daudible/sound3.wav',
	'http://gm.thezikes.org/daudible/sound4.wav',
	'http://gm.thezikes.org/daudible/sound5.wav',
	'http://gm.thezikes.org/daudible/sound6.wav',
	'http://gm.thezikes.org/daudible/sound7.wav',
	'http://gm.thezikes.org/daudible/sound8.wav',
	'http://gm.thezikes.org/daudible/sound9.wav',
	'http://gm.thezikes.org/daudible/sound10.wav',
	'http://gm.thezikes.org/daudible/sound11.wav'
];
var $=function(str){return document.getElementById(str)}
var $S=function(str){return document.createTextNode(str)};
var $E=function(){
	function applyObj(to, obj){
		for(prop in obj) if(obj.hasOwnProperty(prop)){
			if(typeof(obj[prop])=='object'){
				applyObj(to[prop], obj[prop]);
			}else{
				to[prop]=obj[prop];
			}
		}
	}
	if(arguments.length==0) return;
	var elm=document.createElement(arguments[0]);
	[arguments[1], arguments[2]].forEach(function(arg,idx,ary){
		if(typeof(arg)=='object'){
			if(arg instanceof Array){
				arg.forEach(function(append,idx,ary){
					if(typeof(append)=='string'){
						append=$S(append);
					}
					elm.appendChild(append)
				});
			}else{
				for(prop in arg) if(arg.hasOwnProperty(prop)){
					if(prop=='events'){
						var events=arg[prop];
						for(evt in events) if(events.hasOwnProperty(evt)){
							elm.addEventListener(evt.replace(/^on/,''), events[evt], false);
						}
					}else{
						if(typeof(arg[prop])=='object'){
							applyObj(elm[prop], arg[prop]);
						}else{
							elm[prop]=arg[prop];
						}
					}
				}
			}
		}
	});
	return elm;
}

unsafeWindow.$E=$E;
unsafeWindow.$S=$S;

function showPrefs(){
	GM_log('Showing Preferences');
	var PrefsWindowWidth=370;
	var PrefsWindowHeight=150;
	var body=document.getElementsByTagName('body')[0];
	
	GM_log('Making Header');
	var prefsHeader=$E('div',{id:'dAudible_PrefsHeader'},[
		$E('a',{id:'dAudible_PrefsWindowClose',events:{
			'click':function(evt){
				body.removeChild($('dAudible_PrefsWindowBackdrop'));
			}
		}},[
			$E('img',{src:'data:image/gif;base64,R0lGODlhDwAPAJEAAP////X09EdSS////yH5BAEHAAMALAAAAAAPAA8AAAIrnC2Zx6O/GJxnWpRAUAEox2lCt1mjJpoJqa5oabHsp6TnB7ZC1TZqw8MdCgA7'})
		]),
		'dAudible',
		$E('span',['Preferences'])
	]);
	
	GM_log('Making Select');
	var soundSelect=$E('select',{
		id:'dAudible_selSound',
		events:{
			change:function(evt){
				var sound=this.options[this.selectedIndex].value;
				GM_log(sound)
				$('dAudible_txtSound').value=sound;
			}
		}
	},
		(function(){
			var out=[];
			sounds.forEach(function(itm,idx){
				var sel=$E('option',{value:itm},['Sound '+(idx+1)]);
				if(itm==startSound){sel.selected='selected'}
				out.push(sel);
			});
			return out;
		})()
	);
	
	GM_log('Making Button');
	var changeButton=$E('button',{
		style:{styleFloat:'right'},
		events:{
			click:function(evt){
				var opt=$('dAudible_txtSound').value;

				startSound=opt;
				GM_setValue('sound',opt);
				body.removeChild($('dAudible_PrefsWindowBackdrop'));
			}
		}
	},[
		'Change'
	]);
	
	GM_log('Making Window');
	body.appendChild(
		$E('div',{id:'dAudible_PrefsWindowBackdrop'},[
			$E('div',{id:'dAudible_PrefsWindow',style:{
				width:PrefsWindowWidth+'px',
				height:PrefsWindowHeight+'px',
				left:((document.documentElement.clientWidth/2) - (PrefsWindowWidth/2))+'px',
				top:((document.documentElement.clientHeight/2) - (PrefsWindowHeight/2))+'px'
			}},[
				prefsHeader,
				$E('div',{id:'dAudible_PrefsBody'},[
					soundSelect,
					$E('br'),
					$E('input',{id:'dAudible_txtSound',value:startSound}),
					$E('button',{events:{click:function(evt){play($('dAudible_txtSound').value)}}},['>']),
					$E('br'),
					changeButton
				])
			])
		])
	);
	GM_log('Window Made');
}
//unsafeWindow.showPrefs=showPrefs;

GM_registerMenuCommand("dAudible Preferences",showPrefs);
var startSound=GM_getValue('sound',sounds[0])
unsafeWindow.startSound=startSound;

var play=function(sound){
	sound=sound || startSound;
	//var embed=$E('embed',{src:sound,loop:false,style:{visibility:'hidden',height:'0px',width:'0px'}});
	
	//<object type="audio/wav" data="sound.wav" width="0" height="0"></object>
	var embed=$E('object',{type:'audio/'+(sound.match(/wav$/) ? 'wav' : 'mpeg'), data:sound, width:0, height:0},[$E('param',{name:'autostart',value:'true'})]);
	
	document.getElementsByTagName('body')[0].appendChild(embed);
	window.setTimeout(function(){remove(embed)},10000);
};
unsafeWindow.play=play;

function remove(el){
	el.parentNode.removeChild(el);
}
unsafeWindow.remove=remove;

function embed(){
	(function(){
		var $=function(str){return document.getElementById(str)};

		/* onMsg */
		var old_dAmnChanChat_onMsg=window.dAmnChanChat.prototype.onMsg;
		window.dAmnChanChat.prototype.onMsg=function(from, body){
			var style; 
			if(-1 != from.search(RegExp('\\b'+dAmn_Client_Username+'(s|\'s)?\\b','i'))) 
				style = 'self-hl'; 
			else if(-1 != body.search(RegExp('\\b'+dAmn_Client_Username+'(s|\'s)?\\b','im')))
				style = 'other-hl'; 

			old_dAmnChanChat_onMsg.call(this, from, body);

			if(style=='other-hl'){
				play();
			}
		}

		/* onAction (/me) */
		var old_dAmnChanChat_onAction=dAmnChanChat.prototype.onAction;
		window.dAmnChanChat.prototype.onAction=function(from,body){
			old_dAmnChanChat_onAction.call(this, from, body);
			if(-1 != body.search(RegExp(dAmn_Client_Username,"im"))) play();
		}
	})();
}

var head=document.getElementsByTagName('head')[0];
var script=document.createElement('script');
	script.type="text/javascript";
	script.appendChild(document.createTextNode(String(embed).replace(/^[^\n]+\n|\}$/g,'')));
head.appendChild(script);

var styles=[
	'#dAudible_PrefsWindowBackdrop{position:fixed; top:0; left:0; bottom:0; right:0; background-image:url("http://st.deviantart.com/styles/minimal/minish/bg-fade.png"); z-index:251;}',
	'#dAudible_PrefsWindow{position:fixed; -moz-border-radius: 8px !important; background:url(http://st.deviantart.com/minish/main/bg-bubblb3.gif) repeat-x #BACAB8 0px -35px; border:none; border-top:1px #BEC9BF solid; z-index:300;}',
	'#dAudible_PrefsBody{padding:3px 10px;}',
	'#dAudible_PrefsHeader{height:25px; padding:12px 20px 28px;color:#94a59b;color:#333333;font-family:Trebuchet MS; font-size:22px;font-weight:bolder;cursor:default;}',
	'#dAudible_PrefsHeader span{display:block; font-size:11pt; color:rgb(85,85,85); font-weight:normal;}',
	'#dAudible_PrefsWindowClose{position:absolute;top:10px; right:10px;cursor:pointer;text-decoration:none !important}',
	'#dAudible_txtSound{width:300px;}'
];

head.appendChild($E('style',{type:'text/css'},[styles.join('\n')]))
