/*
-----------------------------------------------------------------------------------------
the-real-donkey-magic.js
-----------------------------------------------------------------------------------------
DONKEYMAGIC BASE JS
Email: richard@donkeymagic.co.uk
Created: 14 October 2009

--------------
NOTES
--------------


--------------
CONTENTS
--------------
## SOCIAL BOOKMARKS
## ANIMATE IMAGES
## PRELOAD IMAGES


--------------
EXTRA JQUERY PLUGINS
--------------
## JQUERY COOKIE
## BACKGROUND POSITION


-----------------------------------------------------------------------------------------
*/
if(typeof ($.DM) == "undefined") {
	$.DM = Object;
}


/*  ## SLIDEBG  ---------------------------------------------------------------------*/

$.DM.slidebg = {
	
	activate: function() {

		$('.blog-navigation ul li a')
		.css( {backgroundPosition: "-1000px 0"} )
		.mouseover(function(){
			var targetX = 1000 - $(this).width() -28;
			$(this).stop().animate({backgroundPosition:'(-' + targetX + 'px 0)'}, {duration:400})
		})
		.mouseout(function(){
			//alert($(this).html());
				$(this).stop().animate({backgroundPosition:"(-1000px 0)"}, {duration:400, complete:function(){
				//$(this).css({backgroundPosition: "-1000px 0"})
			}})
		})

	}

}

/*  ## PANELS  ----------------------------------------------------------------------*/
$.DM.panels = {
	
	moving: false,
	opened: false, 
	activePanel: null,
	targetHeightOpen: 100 + "px",
	targetHeightClosed: 32 + "px",
	speed: 200,
	
	init: function(){
		$.DM.panels.addPanels();
		$.DM.panels.activatePanels();
		$.DM.panels.popPanel();
		$.DM.skin.init();
	},

	addPanels: function() {
		$('#container').prepend('<div id="goodies"><div class="inner"><div class="content"><ol><li class="skin1"><a href="#skin1">Skin 1</a></li><li class="skin2"><a href="#skin2">Skin 2</a></li><li class="skin3"><a href="#skin3">Skin 3</a></li><li class="skin4"><a href="#skin4">Skin 4</a></li></ol></div><div id="tab"><a href="#" id="tab-open">+</a></div></div></div>');
		$("#goodies").css('height',$.DM.panels.targetHeightClosed);
	},
	
	activatePanels: function() {
		$(document).mouseup(function() {
			if (!$.DM.panels.moving && $.DM.panels.opened) {
				$.DM.panels.closePanels();
			}
		});
		$("#goodies").mouseup(function() {return false});

		$("#tab a").click(function() {
			if (!$.DM.panels.moving && !$.DM.panels.opened) {	
				$.DM.panels.openPanels();
				$.DM.panels.activePanel = 'bob';
			} else  {
				$.DM.panels.closePanels();
			}
			return false;
		});
	},
	
	openPanels: function() {
		$.DM.panels.moving = true;
		$("#goodies").animate({ 
			height: $.DM.panels.targetHeightOpen
		}, $.DM.panels.speed, function() {
			$.DM.panels.doneOpening();
		});
	},
	
	closePanels: function() {
		$.DM.panels.moving = true;
		$("#goodies").animate({ 
			height: $.DM.panels.targetHeightClosed
		}, $.DM.panels.speed, function() {
			$.DM.panels.doneClosing();
		});
	},
	
	doneOpening: function() {
		$.cookie('DM-goodies', null);
		$.cookie('DM-goodies', 'open');
		$.DM.panels.moving = false;
		$.DM.panels.opened = true;
	},
	
	doneClosing: function() {
		$.DM.panels.moving = false;
		$.DM.panels.opened = false;
		$.cookie('DM-goodies', null, { expires: -1 });
	},
	
	popPanel: function() {
		if($.cookie('DM-goodies')){
			$("#goodies").css('height',$.DM.panels.targetHeightOpen);
			$.DM.panels.doneOpening();
		}
	}
	
};

$.DM.skin = {

	DOMBgClass: null,
	currentBgClass: null,
	
	init:function() {
		this.DOMBgClass = $('body').attr('class');
		this.getBG();
		this.activate();
	},
	
	getBG: function() {
		this.currentBgClass = $.cookie('DM-bgClass');
		this.setBG(this.currentBgClass);
	},
	
	setBG: function(ref) {
		$('body').removeClass();
		$('body').addClass(this.DOMBgClass + ' ' + ref);
		$.cookie('DM-bgClass', null);
		$.cookie('DM-bgClass', ref, {expires: 30, path: '/'});
	},
	
	activate: function() {
		$('#goodies li a').click(function() {
			var href = $(this).attr('href');
			var bgClass = href.split('#')[1];
			//$('#goodies li').removeClass('selected');
			//$(this).parent().addClass('selected');
			$.DM.skin.setBG(bgClass);
			return false;
		});
	}

}


/*  ## SOCIAL BOOKMARKS  ------------------------------------------------------------*/
$.DM.share = {
	
	URL:null,
	title:null,
	before:true,
	target:null,
	
	init:function() {
		$.DM.share.getURL();
		$.DM.share.getTitle();
		$.DM.share.addBookmarks();
	},
	
	getURL:function() {
		$.DM.share.URL = escape(window.location);
	},
	
	getTitle:function() {
		$.DM.share.title = escape($('title').html());
	},
	
	addBookmarks:function() {
	
		var bookmarks = ' '
		+ '<div class="share"><h4>Share this page<\/h4><ul>'
		+ '<li class="linkedin"><a href="http://www.linkedin.com/shareArticle?mini=true&amp;url=' + $.DM.share.URL + '&amp;title=' + $.DM.share.title + '&amp;summary=&amp;source=">LinkedIn<\/a><\/li>'
		+ '<li class="facebook"><a href="http://www.facebook.com/sharer.php?u=' + $.DM.share.URL + '">Facebook<\/a><\/li>'
		+ '<li class="digg"><a href="http://digg.com/submit?phase=2&amp;url=' + $.DM.share.URL + '&amp;title=' + $.DM.share.title + '">digg<\/a><\/li>'
		+ '<li class="twitter"><a href="http://twitter.com/home/?status=' + $.DM.share.URL + '%20' + $.DM.share.title + '">Twitter<\/a><\/li>'
		+ '<li class="delicious"><a href="http://delicious.com/post?url=' + $.DM.share.URL + '&amp;title=' + $.DM.share.title + '">Delicious<\/a><\/li>'
		+ '<\/ul><\/div>';
		
		if($.DM.share.before) {
			$($.DM.share.target).prepend(bookmarks);
		} else {
			$($.DM.share.target).append(bookmarks);
		}
		
	}
}


/*  ## ANIMATE IMAGES  --------------------------------------------------------------*/
$.DM.animateImages = {
	
	target: null,
	images: null,
	count: 0,
	total: 0,
	timer: null,
	interval: 6000,
	speed: 500,
	
	init: function(target,images) {
		$.DM.animateImages.target = target;
		$.DM.animateImages.images = images;
		$.DM.animateImages.total = images.length;
		$.DM.animateImages.startTimer();
	},
	
	startTimer: function() {
		if($.DM.animateImages.total > 1) {
			$.DM.animateImages.timer = window.setInterval("$.DM.animateImages.fadeDown()",$.DM.animateImages.interval);
		}
	},
		
	fadeDown: function() {
		$($.DM.animateImages.target).fadeOut($.DM.animateImages.speed,
			function() {
				$.DM.animateImages.fadeUp();
			}
		);
	},
		
	fadeUp: function() {
		if($.DM.animateImages.count < $.DM.animateImages.total-1) {
			$.DM.animateImages.count = $.DM.animateImages.count + 1;
			//console.log($.DM.animateImages.count);
		} else {
			$.DM.animateImages.count = 0;
		}
		$($.DM.animateImages.target).attr({
			src: $.DM.animateImages.images[$.DM.animateImages.count][0],
			alt: $.DM.animateImages.images[$.DM.animateImages.count][1]
		});
		$($.DM.animateImages.target).fadeIn($.DM.animateImages.speed);
	}
	
};


/*  ## PRELOAD IMAGES  --------------------------------------------------------------*/
if(typeof ($.DM.images) == "undefined") {
	$.DM.images = Object;
}

$.DM.images.preloader = {
	
	images: null, 
	imageTotal: 0,
	callback: null,
	complete: false,
	imageObjects: new Array(),
	
	init: function(images,callback) {
		$.DM.images.preloader.images = images;
		$.DM.images.preloader.imageTotal = $.DM.images.preloader.images.length;
		$.DM.images.preloader.callback = callback;
		$.DM.images.preloader.loadImages();
	},
	
	loadImages: function() {
		for(var i = 0; i  < $.DM.images.preloader.imageTotal; i++) {
			$.DM.images.preloader.imageObjects[i] = new Image();
			$.DM.images.preloader.imageObjects[i].src = $.DM.images.preloader.images[i][0];
		}
		window.setTimeout("$.DM.images.preloader.checkLoaded()",1000);
	},
		
	checkLoaded: function() {
		var loadingComplete = true;
		for(var i = 0; i  < $.DM.images.preloader.imageTotal; i++) {
			if(!$.DM.images.preloader.imageObjects[i].complete) {
				loadingComplete = false;
			}
		}
		if(loadingComplete == true) {
			$.DM.images.preloader.complete = true;
			$.DM.images.preloader.callback();
		} else {
			window.setTimeout("$.DM.images.preloader.checkLoaded()",1000);
		}	
	}
};


/*  ## JQUERY COOKIE  ---------------------------------------------------------------*/
/**
 * 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
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * 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
 */

/*
 * Altered by Natalie Downe <nat@natbat.net> to make $cookie() with no arguments return an array of the set cookies
 * eg [["cookiename1", "cookievalue1"], ["cookiename2", "cookievalue2"]]
*/
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
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else if(typeof name != 'undefined') { // 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;
    } else {
		// not given anything
		var cookies = document.cookie.split(';');
		for (var i = 0; i < cookies.length; i++) {
            cookies[i] = jQuery.trim(cookies[i]).split('=')[0];
		}
		return cookies;
	}
};


/*  ## BACKGROUND POSITION  ---------------------------------------------------------*/
/**
 * @author Alexander Farkas
 * v. 1.02
 */
(function($) {
	$.extend($.fx.step,{
	    backgroundPosition: function(fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
			}
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

           function toArray(strg){
               strg = strg.replace(/left|top/g,'0px');
               strg = strg.replace(/right|bottom/g,'100%');
               strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
               var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
               return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
           }
        }
	});
})(jQuery);