var petal = 1;

var Petal = function(id){
	this.wrp;
	this.img_wrp;
	this.img;
	this.scale = Math.ceil(Math.random()*20) + 80;
	this.tw;
	this.id = "pet_"+id;
	
	this.init = function(){
		this.create();
	};
	
	this.create = function(){
		
		var left = Math.floor(Math.random() * $('body').width());
		var top = -100;
		
		this.wrp = $('<div />');
		this.wrp.attr('id', this.id);
		
		this.wrp.css({
			position: 'absolute',
			top:  top,
			left:  0,
			opacity: 0.95,
			overflow: "visible"
		});
		
		this.wrp.appendTo('#petal-wrp');
		
		this.img_wrp = $('<div />');
		this.img_wrp.css({
			position: "relative",
			marginLeft: left,
			overflow: "visible",
			width: "150px",
			height: "100px"
		});
		
		this.img_wrp.appendTo(this.wrp);
		
		this.createPetal()
	}
	
	this.createPetal = function(){
	
		var src = "common/img/index/petal_"+Math.floor(Math.random()*5)+".gif";
		
		this.img = $('<img />');
		this.img.attr('src', src);
		this.img.appendTo(this.img_wrp);
		this.img.css({
			position: "absolute",
			opacity: 0
		});
		
		this.img.fadeTo(1000, 1);
	};
	
	
	this.init();
}

function setTween(o){
	var w = o.wrp;
	var i = o.img_wrp;
	var h = $(document).height();
	
	w.animate({ 
    top: parseInt(w.css("top")) + h + "px"
  }, Math.random()*4000 + 5000, 'easeInQuad' , function(){callback(o)});
  
  var r = (Math.random() * 600) - 300;
  
  i.animate({ 
    marginLeft: (parseInt(i.css("marginLeft")) + r) + "px"
  }, Math.random()*2000 + 2500, 'easeInOutBack', function(){swapPetal(o)});
  
};

function callback(o){
	//alert(parseInt(o.wrp.css("top")))
	if(parseInt(o.wrp.css("top")) < $("body").height()){
		setTween(o)
	}else{
		 //o.remove();
	}
}

function swapPetal(o){
  var r = (Math.random() * 600) - 300;
	o.img_wrp.animate({ 
    marginLeft: (parseInt(o.img_wrp.css("marginLeft")) + r) + "px"
  }, Math.random()*2000 + 2500, 'easeInOutBack', function(){swapPetal(o)});
  
	var i = o.img;
  o.createPetal();
	i.fadeTo(1000, 0, function(){
		i.remove();
	})
}

function showRoses(){
	$('#petal-wrp').fadeOut(1000);
	$("#rose-wrp").show();
	if(!$.browser.msie){
		$("#rose-wrp").fadeTo(200000, 100)
	}
}

$(function(){
	$("#petal-wrp").click(function(){
		$.resume();
		showRoses();
	})
	$("#petal-wrp").show();
	$('#petal-wrp').height(1400);
	setTween(new Petal(0));
	
	for(var i=1; i < 12; i++){
		$('#petal-wrp').delay(function(){
			setTween(new Petal(i));
		});
	}
	
	
	$('#petal-wrp').delay(showRoses);
	
	$.resume(600);
});