/*
- jQuery.timers - Timer abstractions for jQuery
Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)

- DBJ-SOUND 1.0.2 by Dusan Jovanovic ( http://dbj.org )
Licensed under the MIT license http://www.opensource.org/licenses/mit-license.php

*/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

/**
 * DBJ-SOUND 1.0.2
 * jQuery dbj_sound plugin (no flash, or any other simillar control used)
 * 
 * Loosely inspired on code by Joern Zaefferer (also Jules Gravinese http://www.webveteran.com/ ) 
 * 
 * Copyright (c) 2009 Dusan Jovanovic ( http://dbj.org ) 
 * 
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 ************************************************************************************   
 * Crash course:
 * 
 * return sound file url from host element
 * host must be valid html element with attribute href present
 * $.dbj_sound.url( host_element )
 *
 * play a sound as defined by the href of the host_element
 * if looping arg present, then loop
 * $.dbj_sound.play( host_element, looping )
 *
 * play "forever" a sound as defined by the href of the host_element
 * $.dbj_sound.loop( host_element )
 *
 * stop a playback of the sound from the href of the host_element
 * $.dbj_sound.stop( host_element )
 * 
 * return true if sounds are on and sound defined by href of the host_element
 * is playing
 * $.dbj_sound.playing( host_element )
 * 
 * toggle on/off all sounds on the current page, controlled by this plugin
 * $.dbj_sound.enabledisable( host_element )
 * 
 */

(function($) {

    $.dbj_sound = {
        tracks: {},
        enabled: true,
        
        url : function ( host_element ) {
             var url = $(host_element).attr("href") ;
             if ( "undefined" == typeof(url) ) throw new Error(0xFF,"DBJ-SOUND EXCEPTION: host element invalid or missing a valid HREF attribute") ;
             return url ;
         },
        
        loop: function ( host_element ) { this.play (host_element,true) ; },

        play: function(host_element, looping ) {
            //
        var sound_jq = function(src) {

        /* I might introduce this for very old browsers, or ... ?
        if ($.browser.msie)
        return $('<bgsound/>').attr({ src: options.track,
        loop: "infinite", // dbj changed from 1
        autostart: true
        }); */
                //
                return $('<embed />').attr({
                    style: "height:0",
                    loop: ( looping ? "true" : "false" ) ,
                    src: options.track,
                    autostart: "true",
                    hidden: "true"
                });
            }

            // sanity checks
            if (!this.enabled) return;
            if (!host_element) return;

            var options = { track: this.url(host_element) }; 

            if (this.tracks[options.track]) {
                var current = this.tracks[options.track];
                current.remove();
            }

            var element = sound_jq();
                element.appendTo(document.body);
                    this.tracks[options.track] = element;
            return element; // which is jQuery object 
        }

        // DBJ added
        , stop: function(host_element) {
            var url = this.url(host_element);
            if (this.tracks[url]) {
                var current = this.tracks[url];
                // Check when Stop is avaiable, but not on a jQuery object
                if ('undefined' != typeof [0].Stop) current[0].Stop();
                else if ('undefined' != typeof current[0].stop) current[0].stop();
                current.remove();
                this.tracks[url] = null;
            }
        }

        // DBJ added
        , playing: function(host_element) {
            if (!$.dbj_sound.enabled) return false;
            return this.tracks[this.url(host_element)] != null;
        }

        // DBJ added
        , enabledisable: function() {
            this.enabled = !this.enabled;
            if (this.enabled == false)
                for (var j in this.tracks) {
                if (this.tracks[j]) {
                    this.tracks[j].remove();
                    this.tracks[j] = null;
                }
            }
            return this.enabled;
        }

    };
	
    // 1.0.3 addition
    // preload sounds into the local cache
    $.dbj_sound.cache = function() {
    delete $.dbj_sound.cache.list;
    $.dbj_sound.cache.list = [];
    for (var i = 0; i < arguments.length; i++) {
            $("<embed />").attr("src", arguments[i]);
            $.dbj_sound.cache.list.push(arguments[i]);
        }
    }
    $.dbj_sound.cache.list = []; // length == 0

})(jQuery);


var soundhost = 'http://static.esato.com/board/sound/';
var pmcount = 0;
$(document).ready(function(){
	$('#dingi').attr('href', soundhost + 'ding.wav');
	$(document).everyTime(60000, "pmcheck", function(t){
		sjekkpm();
	}, 720);
});


var otitle = '';
function sjekkpm(){
	$.getJSON(ajaxserver + "/ajax_get_pm.1.1.php",
		{
		r : Math.random()
		},
		function(j){
			if(j.status == 'ok'){
				if(j.pmcount > 0){
					var ha = $('#dingi');
					if(j.pmcount > 1){
						thes = 's';
					}
					else{
						thes = '';
					}
					htmlout = '<a href="http://www.esato.com/board/viewpmsg.php" style="color:#FF0000">' + j.pmcount + ' New PM'+thes+'!</a>';
					if(j.username != '' && j.username != 'Unknown'){
						htmlout = htmlout + ' Latest from ' + j.username;
					}
					$("#pmw").html(htmlout);
//					otitle = document.title;
					$(document).attr('title', j.pmcount + ' New PM'+thes+' @ Esato');
					if(pmcount < j.pmcount){
						pmcount = j.pmcount;
						pingsound(ha);
						$("#pmw").slideDown("slow");
					}
				}
				else{ // pm count = 0
					if($('#pmw').is(':visible')){
						$('#pmw').hide();
//						$(document).attr('title', otitle);
						pmcount = 0;
					}
				}
			}
			else if(j.status == 'guest'){
				$(document).stopTime("pmcheck");
			}
		}
	);

}

function pingsound(ha){
	if ($.dbj_sound.playing(ha)){
		$.dbj_sound.stop(ha);
	}
	else{
		$.dbj_sound.play(ha);
	}
}



