/*globals window,jQuery */
/* ***********************************************************************************

	CJ Snow JavaScript framework

	Copyright (c) 2008, Doug Jones. All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions
	are met:
	
	a) Redistributions of source code must retain the above copyright
	   notice, this list of conditions and the following disclaimer.
	  
	b) 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. 
	  
	c) Neither the name of the Creative Juices, Bo. Co. 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.

	For further information, visit the Creative Juices website: www.cjboco.com.
	
	Version History
	
	1.0 (12-24-2009) - Initial release.

*********************************************************************************** */
(function ($) {
	$.fn.cjSnow = function (options) {

		var settings = {
			// user editable parameters
			num: 40,
			delay: 30,
			color1: "#bbdcea",
			color2: "#ffffff",
			steps: 6
		};

		var sys = {
			// system parameters
			version: '1.0',
			elem: null,
			box: null,
			timer: null,
			colorSteps: [],
			colors: []
		};

		function randomRange(a, b, d) {
			var r = a + (Math.random() * (b - a));
			return typeof d == 'undefined' ? parseInt(r, 10) : parseFloat(r.toFixed(d));
		}
		
		function colorParse(c, t) {
			var m = 1,
				col, num, base;
			c = c.toUpperCase();
			col = c.replace(/[\#rgb\(]*/, '');
			if (t === 'hex') {
				if (col.length === 3) {
					var i = col.substr(0, 1);
					var j = col.substr(1, 1);
					var k = col.substr(2, 1);
					col = i + i + j + j + k + k;
				}
				num = [col.substr(0, 2), col.substr(2, 2), col.substr(4, 2)];
				base = 16;
			} else {
				num = col.split(',');
				base = 10;
			}
			if (t === 'rgbp') {
				m = 2.55;
			}
			return ([parseInt(num[0], base) * m, parseInt(num[1], base) * m, parseInt(num[2], base) * m]);
		}

		function colorMixer() {
			var i, c1 = colorParse(settings.color1, 'hex'),
				c2 = colorParse(settings.color2, 'hex');
			settings.color1 = {
				r: c1[0],
				g: c1[1],
				b: c1[2]
			};
			settings.color2 = {
				r: c2[0],
				g: c2[1],
				b: c2[2]
			};
			sys.colorSteps[0] = (settings.color2.r - settings.color1.r) / settings.steps;
			sys.colorSteps[1] = (settings.color2.g - settings.color1.g) / settings.steps;
			sys.colorSteps[2] = (settings.color2.b - settings.color1.b) / settings.steps;
			for (i = 0; i <= settings.steps; i++) {
				var r = parseInt(settings.color1.r + (sys.colorSteps[0] * i), 10);
				var g = parseInt(settings.color1.g + (sys.colorSteps[1] * i), 10);
				var b = parseInt(settings.color1.b + (sys.colorSteps[2] * i), 10);
				sys.colors[i] = "rgb(" + r + "," + g + "," + b + ")";
			}
		}

		/* 
			initialize our plug-in
		***************************************/

		function init() {
			var i;
			// create our color pallette
			colorMixer();

			// add our snowflakes to the document
			for (i = 0; i < settings.num; i++) {
				var size = randomRange(7, 24, 0),
					elem;
				$(sys.elem).append('<div id="cjSnowFlake' + i + '">');
				$('div#cjSnowFlake' + i).css({
					"position": "absolute",
					"top": randomRange(0, $(sys.box).height(), 0) + "px",
					"left": randomRange(0, $(sys.box).width(), 0) + "px",
					"display": "block",
					"width": size + "px",
					"height": size + "px",
					"color": sys.colors[randomRange(0, sys.colors.length - 1, 0)],
					"font-family": '"Times New Roman", Times, serif',
					"text-align": "center",
					"font-size": size + "px",
					"line-height": size + "px",
					"opacity": Math.random(),
					"overflow": "hidden",
					"z-index": 29999
				});
				$('div#cjSnowFlake' + i).html("*");
				elem = $("div#cjSnowFlake" + i).get(0);
				elem.currStep = 0;
				elem.fall = (1 - (size / 100)) * (size / 9);
				elem.drift = randomRange(0.05, 1 - size / 100, 15);
				elem.size = size;
				elem.snow = function (e) {
					var o = elem;
					return function () {
						var obj = o,
							posX, posY;
						obj.timer = window.clearTimeout(obj.timer);
						if (Math.random() < 0.5) {
							posX = parseInt($(obj).css("left"), 10) + (obj.fall * Math.cos(obj.currStep / obj.size / 2));
						} else {
							posX = parseInt($(obj).css("left"), 10) + (obj.fall * Math.acos(obj.currStep / obj.size / 2));
						}
						posY = parseInt($(obj).css("top"), 10) + obj.fall;
						if (posX >= $(sys.box).width() - obj.size || posY >= $(sys.box).height() - obj.size) {
							posY = obj.size * -1;
							posX = Math.random() * ($(sys.box).width() - obj.size - 1);
							obj.fall = (1 - (obj.size / 100)) * (obj.size / 9);
							obj.drift = randomRange(0.05, 1 - obj.size / 100, 15);
						}
						$(obj).css({
							"top": Math.round(posY + $(sys.box).scrollTop()) + "px",
							"left": Math.round(posX + $(sys.box).scrollLeft()) + "px"
						});
						obj.currStep += obj.drift;
						obj.timer = window.setTimeout(obj.snow, settings.delay);
					};
				} (i);
				elem.timer = window.setTimeout(elem.snow, settings.delay);
			}

		}
		/* 
			set up any user passed variables
		***************************************/
		if (options) {
			$.extend(settings, options);
		}

		/* 
			begin
		***************************************/
		return this.each(function () {
			if (typeof this.tagName === "undefined" || (typeof this.tagName === "object" && this.tagName === "BODY")) {
				sys.elem = $('body');
				sys.box = $(window);
			} else {
				sys.elem = this;
				sys.box = this;
			}
			// vallidate our user settings
			if (typeof settings.steps !== "number" || settings.steps < 2) {
				settings.steps = 2;
			}
			init();
		});

	};
})(jQuery);