/**
 * js extensions
 * 	- jQuery.ImageReplace
 * 	- jQuery.cookie
 * 	- StyleSwitcher
 * 	- Accessible select
 *  
 * @author arjen
 */

jQuery.log = function(message) {
	if (window.console) {
		console.debug(message);
	} else {
		alert(message);
	}
};

// extending objects
// ucfirst
String.prototype.ucfirst = function() {
	var f = this.charAt(0).toUpperCase();
	return f + this.substr(1, this.length-1);
}
	

/**
 * Image Replace
 * Appends some spans to selection, so with css nice IR can happen)
 * @author AK|Peppered
 */

jQuery.fn.ImageReplace = function(options) {
	var defaults = {
		hover: false
	};
	options = $.extend(defaults, options);
	if (document.styleSheets[0].disabled) return false;
	if (this.length < 1) return false;
	
	if (this.get(0).nodeName.toLowerCase() == 'body') {
		// old style replace via classnames
		$('.IR, .IR-anchors a').append('<span class="IR-aid"></span>');	// single element IR & descendant anchors of an element
		$('.IR.IR-hover span.IR-aid, .IR-anchors.IR-anchors-hover a span.IR-aid').append('<span></span>');	// append another span when it has a hover state
		$('.IR, .IR-anchors').addClass('IRActive');		
	}
	else {
		this.each(function() {
			//$.log(this);
			$(this).addClass('ir');		
			$(this).append('<span class="ir-aid"></span>');	
			if (options.hover == true) {
				$(this).children('span.ir-aid').addClass('ir-aid-hover');
				$(this).children('span.ir-aid').append('<span></span>');
			}
	
			$(this).addClass('irActive');
		});		
	}
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '; path=/';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
 * styleswitcher
 * based on: http://www.alistapart.com/stories/alternate/
 * adaption by Peppered
 * 
 */

var StyleSwitcher = {
	setActiveStyleSheet:function(title){
		if (!title) return false;
		var i, a, main;
		for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
			if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
				a.disabled = true;
				if(a.getAttribute("title") == title)
					a.disabled = false;
			}
		}
		// set parent li to class 'active'
		if ($('body').is('#bodySplash')) {
			var sId = 'textResize-';
			$('#textResizeBox a').removeClass('active');
		}
		else {
			var sId = 'snelmenu-tekst-';
			$('#snelmenu-tekst a').removeClass('active');
		}
		sId += title.substring(title.lastIndexOf(' ') + 1);
		$('#snelmenu-tekst li').removeClass('active');
		$('#' + sId).addClass('active');
		//$.log(title);
	},
	getActiveStyleSheet:function() {
		var i, a;
		for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
			if (a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled)
				return a.getAttribute("title");
		}
		return null;
	},
	getPreferredStyleSheet:function() {
		var i, a;
		for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
			if(a.getAttribute("rel").indexOf("style") != -1
				&& a.getAttribute("rel").indexOf("alt") == -1
				&& a.getAttribute("title")
			)
				return a.getAttribute("title");		
		}
		return null;
	}	
};


/**
 * autoSelect, jQuery plugin
 * 
 * Auto-submit forms when select options have changed
 * Smoothens out (almost) behavioural differences between browsers.
 * Inpsired on: http://themaninblue.com/writing/perspective/2004/10/19/
 * 
 * usage: $selection.autoSelect({options})
 * 
 * @author AK | Peppered
 * @version 1.0.3
 */	
;(function($) {	
$.fn.autoSelect = function(options) {
	options = $.extend({
	}, options);
			
	return this.each(function() {
		var $this = $(this);
					
		$this.validKeyChange = true;		// for browsers that trigger change event when option changed by keyboard (IE)
		$this.initValue = $(this).val();
		
		$this.change(function(){
			if ($this.validKeyChange && (this.value != $this.initValue)) {		
				$this.initValue = this.value;
				this.form.submit();
			}
		});
		
		$this.keydown(function(e){
			// 9=tab, 13=enter, esc=27
			if ((e.keyCode == 13) && this.value != $this.initValue) {						
				$this.validKeyChange = true;
				$this.change();
			}
			else {
				if (e.keyCode == 27 || ((e.keyCode == 13 || e.keyCode == 9) && this.value == $this.initValue)) {
					$this.validKeyChange = false;
					this.value = $this.initValue; // a.o. for Safari when opening select with mouse, using keys & tabbing off
				}
				else {
					$this.validKeyChange = false;
				}
			}
		});
		
		$this.blur(function(e){
			if (this.value != $this.initValue && $this.validKeyChange) {
				$this.initValue = this.value;
				this.form.submit();
			}
		});
	});
};
})(jQuery);
