$(function() {
    function flowers(opts,starstate) {
    	var any = false;
    	if (starstate) {
			$.each(starstate,function(i,e) {
				if (e == null) return;
				var star = e.el;
				any |= true;
				e.top += e.vel;
				var left = Math.round( e.left + Math.sin( e.swayp + (e.top / e.end) * Math.PI) * e.vel * e.sway);
				if (e.top > e.end) {
					starstate[i] = null;
				} else if (e.top > -16) {
					star.css('top',e.top + "px");
					star.css('left',left + "px");
				}
			});
			
    	} else {
    		any = true;
    		var star = $(".flower");
    		var parent = star.parent();
    		var width = parent.width();
    		var startLeft =  $.browser.msie ? 0 : parent.offset().left;
    		starstate = [];
			for (var i = 0; i < opts.num; i++) {
				var s = star.clone().show().appendTo(star.parent());	
				var top = randInt(opts.start.top,opts.start.trand);
				var left = randInt(startLeft,width); 
				var state = {
					el : s,
					vel : randInt(3,5),
					end : randInt(opts.end.top,opts.end.rand),
					top : top,
					left: left,
					sway : randInt(2,4),
					swayp : randInt(0,.5)
				};
				starstate.push( state );
				s.css('top', top + "px");
				s.css('left', left + "px");
				kickEnable(s,state);
				
			}
    	}
    	if (any) {
			setTimeout(function() {
				flowers(opts,starstate);
			},opts.time);
		}
		
    }
    function kickEnable(el,state) {
    	el.mousemove(function(ev) {
			if (state.me) {
				var s = $(this);
				var dy = ev.pageY - state.me.pageY;
				var dx = ev.pageX - state.me.pageX;
				state.top += dy; 
				state.left += dx;
				s.css('top', state.top  + "px");
				s.css('left', state.left + "px");
				delete state.me;
			}
			state.me = ev;
		});
    }
    
    function randInt(s,w) {
    	return Math.round(s + (Math.random() * w));
    }
    
    
   	flowers({
   			num: 7,
   			time: 50,
   			start: {
   				top: -280,
   				left: 0,
   				trand: 280, 
   				lrand: 800
   			},
   			end : {
   				top: 160,
   				rand: 20
   			}
   		});
    
    $("h2,h3").each(function() {
    	if (Math.random() > .5) {
    		$(this).css('background-image','url("images/header2.jpg")');
    	}
    });
   
});

