/* 	
	Plugin: iframe autoheight jQuery Plugin 
	Author: original code by NATHAN SMITH; converted to plugin by Jesse House
	File: jquery.iframe-auto-height.plugin.js
	Description: when the page loads set the height of an iframe based on the height of its contents
	Remarks: original code from http://sonspring.com/journal/jquery-iframe-sizing	
	Version: 1.0.0 - see README: http://github.com/house9/jquery-iframe-auto-height
*/
(function ($) {
	$.fn.iframeAutoHeight = function (options) {
		// set default option values
		var options = $.extend({
			heightOffset: 0
		}, options);

		// iterate over the matched elements passed to the plugin
		$(this).each(function () {
			// Check if browser is Opera or Safari(Webkit so Chrome as well)
			if (false){//$.browser.safari || $.browser.opera) {
				// Start timer when loaded.
				$(this).load(function () {
					var iframe = this;
					var delayedResize = function () {
						resizeHeight(iframe);
					};
					setTimeout(delayedResize, 10);
				});

				// Safari and Opera need a kick-start.
				var source = $(this).attr('src');
				$(this).attr('src', '');
				$(this).attr('src', source);
			}
			else {
				// For other browsers.
				$(this).load(function () {
					resizeHeight(this);
				});
			}

			// resizeHeight
			function resizeHeight(iframe) {
				// Set inline style to equal the body height of the iframed content plus a little
				var newHeight = iframe.contentWindow.document.body.offsetHeight + options.heightOffset;
				iframe.style.height = newHeight + 'px';
			}

		}); // end
	}
})(jQuery);

(function($) {

var applyWeather = function() {
	if (!Modernizr.canvas)
		return;

	var WIDTH = $('#nuli_movie').width();
	var HEIGHT = $('#nuli_movie').height();
	
	var Plane = function(speed, scale) {
		var p = new Path("M 10 10 L 7.5 20 L 5 12 L 30 20 z", {
			stroke: '#666',
			lineWidth: 3,
			fill: '#fff'
		}), p1 = new Path("M 10 10 L 30 20 L 5 30 L 10 10 L 7.5 20 L 30 20 L 5 30 z", {
			stroke: '#666',
			lineWidth: 3,
			fill: '#fff'
		});
		
		p.append(p1);
		p.scale = scale;
		
		var cps = this._getRandomCps(), oldRt = -1, this_ = this;
		p.addFrameListener(function(t, dt) {
			var rt = (t / speed) % 1;
			if (oldRt === -1 || oldRt > rt) {
				cps = this_._getRandomCps();
			};
			oldRt = rt;
			
			var point = Curves.cubicPoint(cps[0], cps[1], cps[2], cps[3], rt);
			var angle = Curves.cubicAngle(cps[0], cps[1], cps[2], cps[3], rt);
			this.x = point[0];
			this.y = point[1];
			this.rotation = angle;
		});
		
		this.p = p;
	};
	Plane.prototype.get = function() {
		return this.p;
	};
	Plane.prototype._getRandomCps = function() {
		var cps0 = (function() {
			var candidates = [[1000, 50 + parseInt(Math.random() * 100)], [700 + parseInt(Math.random() * 200), -50], [600 + parseInt(Math.random() * 100), 200]];
			return candidates[parseInt(Math.random() * candidates.length)];
		})();
		var cps1 = (function() {
			var candidates = [[cps0[0] - 100 - parseInt(Math.random() * 200), 0], [cps0[0] - 100 - parseInt(Math.random() * 200), 100]];
			return candidates[parseInt(Math.random() * candidates.length)];
		})();
		var cps2 = (function() {
			var x = cps1[0] - 100 - parseInt(Math.random() * 300);
			var candidates = [[x, -100], [x, 50]];
			return candidates[parseInt(Math.random() * candidates.length)];
		})();
		var cps3 = (function() {
			var x = cps2[0] - 100 - parseInt(Math.random() * 300);
			var candidates = [[x, 0], [x, 200]];
			if (x < 0) 
				candidates.push([x, 100]);
			return candidates[parseInt(Math.random() * candidates.length)];
		})();
		
		return [cps0, cps1, cps2, cps3];
	};
	
	var Balloon = function() {
		var c = new Circle(16, {
			x: 353,
			y: 82,
			fill: '#fe9',
			stroke: '#999',
			strokeWidth: 1
		});
		var p = new Path([['moveTo', [-11, 11]], ['bezierCurveTo', [-15, 15, -25, 20, -30, 45]]], {
			stroke: '#999',
			strokeWidth: 1,
			fill: 'none'
		});
		var p2 = new Path([['moveTo', [-13, 9]], ['bezierCurveTo', [-13, 0, 2, -12, 11, -12]], ], {
			stroke: '#999',
			strokeWidth: 1,
			fill: 'none'
		});
		var p3 = new Path([['moveTo', [-13, 9]], ['bezierCurveTo', [-13, 0, 2, -12, 11, -12]], ], {
			stroke: '#999',
			strokeWidth: 1,
			fill: 'none'
		});
		p3.rotation = 3.1;
		
		c.append(p);
		c.append(p2);
		c.append(p3);
		var animationSet = [[0, 0, 0], [.5, .5, -.025], [1, 1, -.05], [2, 2, -.075], [3, 3, -.1], [4, 4, -.125], [5, 5, -.15], [4, 4, -.125], [3, 3, -.1], [2, 2, -.075], [1, 1, -.05], [.5, .5, -.025]];
		c.addFrameListener(function(t, dt) {
			t = parseInt(t / 100, 10) % animationSet.length;
			c.x = 353 - animationSet[t][0];
			c.y = 82 - animationSet[t][1];
			c.rotation = animationSet[t][2];
		});
		
		this.c = c;
	};
	Balloon.prototype.get = function() {
		return this.c;
	};
	
	var cloud = function() {
		var $c1 = $('#nuli_movie .cloud'), $c2 = $c1.clone().appendTo('#nuli_movie'), x = 0, w = WIDTH;

		$c2.css('right', w);

		var animate = function() {
			x++;
			$c1.css('right', x);
			$c2.css('right', x-w);
			if (w === x)
				x = 0;
		};

		setInterval(animate, 50);
	};
	
	var pinWheel = function($img) {
		var x = 0;
		var rotate = function() {
			x = x == -359 ? 0 : x - 1;
			$img.css({
				'-moz-transform': 'rotate(' + x + 'deg)',
				'-webkit-transform': 'rotate(' + x + 'deg)',
				'-o-transform': 'rotate(' + x + 'deg)',
				'-ms-transform': 'rotate(' + x + 'deg)',
				'transform': 'rotate(' + x + 'deg)'
			});
		};
		
		setInterval(rotate, 50);
	};

	var rain = function() {
		var n = new CanvasNode();
		var mkdrop = function() {
			var size = 15+parseInt(Math.random()*15);
			var r = new Rectangle(size, 1);
			r.x = -100 + parseInt(Math.random()*WIDTH) + 100;
			r.y = -100 + parseInt(Math.random()*HEIGHT) + 100;
			r.rotation = 1.65 + (Math.random()/5);
			r.fill = '#FAFAFA';
			r.data = {
				speed: size/40 + Math.random()*1
			}
			r.addFrameListener(function(t) {
				if (this.y > HEIGHT) {
					this.x = -100 + parseInt(Math.random()*WIDTH) + 100;
					this.y = -50;
				} else {
					this.x -= this.data.speed*this.rotation/10;
					this.y += this.data.speed;
				};
			});
			return r;
		};
		
		for (var i=0; i<300; i++) {
			n.append(mkdrop());
		};
		return n;
	};
	
	var snow = function() {
		var n = new CanvasNode();
		var mkdrop = function() {
			var size = 2+parseInt(Math.random()*3);
			var c = new Circle(size,size);
			c.x = -100 + parseInt(Math.random()*WIDTH) + 100;
			c.y = -100 + parseInt(Math.random()*HEIGHT) + 100;
			c.fill = '#FFF';
			c.data = {
				speed: size/80 + Math.random()*.2
			}
			c.addFrameListener(function(t) {
				if (this.y > HEIGHT) {
					this.x = -100 + parseInt(Math.random()*WIDTH) + 100;
					this.y = -50;
				} else {
					//this.x -= this.data.speed;
					this.y += this.data.speed;
				};
			});
			return c;
		};

		for (var i=0; i<200; i++)
			n.append(mkdrop());

		return n;
	};

  var star = function (r,g,b, radius, x, y) {
    var g1 = new Gradient({
        type : 'radial',
        endX : 0, endY : 0,
        startRadius : 0,
        endRadius : radius,
        colorStops : [
          [0,   [255,255,255,1]],
          [0.3, [r,g,b, 0.5]],
          [0.5, [r,b,g, 0.8]],
          [0.6, [r,g,b, 0.4]],
          [0.8, [r,g,b, 0.7]],
          [1,   [r,g,b, 0]]
          ]
      }
    )
    var g2 = new Gradient({
        type : 'radial',
        endX : 0, endY : 0,
        startRadius : 0,
        endRadius : radius / 2,
        colorStops : [
          [0,   [255,255,255, 1]],
          [0.4, [r,g,b, 0.3]],
          [0.8, [r,g,b, 0.0]],
          [0.9, [r,g,b, 0.1]],
          [1,   [r,g,b, 0]]
          ]
      }
    )
    var star = new CanvasNode()
    var spokes = new CanvasNode()
    spokes.fill = g1
    var spoke1 = new Rectangle(radius*2,1)
    spoke1.centered = true
    var spoke2 = new Rectangle(1,radius*2)
    spoke2.centered = true
    var glow = new Circle(radius / 2)
    glow.fill = g2
    glow.zIndex = 1
    spokes.append(spoke1, spoke2)
    star.append(spokes, glow)
    var offset = Math.random() * 800
    star.rotating = false
    var th = this
    star.addFrameListener(function(t){
        var off = (0.2 + Math.sin(Math.pow(Math.random(),2) + (offset+t)/400)*0.2)
        this.scale = 0.3 + off
        this.opacity = 1 - (off/2)
        if (this.rotating) {
          if (this.rotation < 0.6 && this.rotation + 0.5 >= 0.6) {
            this.rotation = 0.6
            this.rotating = false
          } else {
            this.rotation += 0.5
            this.rotation = this.rotation % (Math.PI)
          }
        } else if (Math.random() < 0.002) {
          this.rotating = true
        }
        if (this.underCursor && this.contains(this.root.target)) {
          th.curves.x = this.x
          th.curves.y = this.y
        }
      }
    )
    star.x = x
    star.y = y
    star.zIndex = 0
    star.rotation = 0.6
    return star
  };

	var c = new Canvas(document.getElementById('nuli_movie'), WIDTH, HEIGHT);

	if ($('.main_welcome').hasClass('day')) {
		if((location.pathname == '/' || location.pathname == '/home_201105') &&
				location.search.indexOf('mid') === -1) {
			var plane1 = new Plane(8000, .9);
			var plane2 = new Plane(5000, .7);
			var plane3 = new Plane(7000, .5);
			var balloon1 = new Balloon();
			c.append(plane1.get());
			c.append(plane2.get());
			c.append(plane3.get());
			c.append(balloon1.get());

			new pinWheel($('.pinwheel1'));
			new pinWheel($('.pinwheel2'));
		};
		new cloud();
	};

	if ($('.main_welcome').hasClass('night')) {
		for (var i=0; i<20; i++) {
			c.append(star(
				200 + parseInt(Math.random() * 55),
				200 + parseInt(Math.random() * 55),
				100 + parseInt(Math.random() * 55),
				10 + parseInt(Math.random() * 20),
				10 + parseInt(Math.random() * 800),
				10 + parseInt(Math.random() * 200)
			));
		};

		c.append(stars[i]);
	};
	
	if ($('.main_welcome').hasClass('rain')) {
		c.append(rain());
	};
	
	if ($('.main_welcome').hasClass('snow')) {
		c.append(snow());
	};
};

var initWeather = function(next) {
	var weather = '';
	var h = new Date().getHours();
	weather = (h > 5 && h < 19 ? 'day' : 'night');

	if (location.search.indexOf('weather') > 0) {
		var s = location.search.replace(/^.*weather=([^\&]+).*$/, '$1');
		$('.main_welcome').addClass(s);
		next();
		return;
	};
	$('.main_welcome').addClass(weather);

	if (!Modernizr.geolocation) {
		next();
		return;
	}

	navigator.geolocation.getCurrentPosition(function(loc) {
		var latitude = loc.coords.latitude, longitude = loc.coords.longitude;
		
		$.getJSON('/2011_new/get_weather.php?latitude=' + latitude + '&longitude=' + longitude, function(data) {
			for (var i = 0; i < data.entry.length; i++) {
				weather = data.entry[i];
			};
			if (weather)
				$('.main_welcome').removeClass('day night').addClass(weather);

			next();
		});
	}, function(error) {
		var NHN_latutide = 37.359294, NHN_longitude = 127.106012;

		$.getJSON('/2011_new/get_weather.php?latitude=' + NHN_latutide + '&longitude=' + NHN_longitude, function(data) {
			for (var i = 0; i < data.entry.length; i++) {
				weather = data.entry[i];
			};
			if (weather)
				$('.main_welcome').removeClass('day', 'night').addClass(weather);

			next();
		});
	});
};

$(function() {
	if ($('#nuli_movie').css('display') !== 'none') {
		initWeather(function() {
			applyWeather();
		});
	};

	$('nav.fac_nav>h1').after('<span class="btn"><a href="javascript:;" role="button" class="fold"><span class="blind">UIO Factory 전체 메뉴</span> <span class="status">접기</span><span class="ico"></span></a></span>');
	$('nav.fac_nav a.fold').click(function() {
		var $target = $(this).parents('.fac_nav');
		$target.toggleClass('fac_navfd');

		var folded = $target.hasClass('fac_navfd');
		$('nav.fac_nav .status').text(folded ? '펼치기' : '접기');
	});

	$('#uio_factory iframe').iframeAutoHeight({heightOffset:50});
});

})(jQuery);

