var Wave = new function() {
	var _this;
	var _w;
	var _wi;
	var _h;
	var _s;
	var _window;
	var _canvas;
	var _width;
	var _height;
	var _context;
	var _image;
	var _timer;
	var _offset;
    var _delay;
	
	{
		_this = this;
		var agent = navigator.userAgent;
		if(agent && agent.match(/(iphone)|(ipad)|(ipod)|(android)|(blackberry)|(webos)|(windows phone)|(zune)|(bada)/i)){ _w = 12; _delay = 50; }
		else { _w = 4; _delay = 60; }
		_wi = _w/2;
		_h = 6;
		_s = 8*Math.PI;
	}
	
	function resizeHandler(event) {
		_width = _window.width()/2;
		_canvas.attr({width: _width});
	};
	
	function loadHandler(event) {
		_image = this;
	}
	
	function animateWave() {
		if(_image) {
			_context.clearRect(0, 0, _width, _height);
			var j = _offset%_image.width;
			if(j < 0) j += _image.width;
			var v;
			var jn;
			for(var i = 0; i < _width; i += _wi) {
				v = (Math.sin(i/_s)+1)*_h;
				jn = j+_w;
				if(jn > _image.width) {
					var wn = _image.width-j;
					var win = wn/2;
					_context.drawImage(_image, j, 0, wn, _image.height, i, v, win, _height);
					jn = _w-wn;
					_context.drawImage(_image, 0, 0, jn, _image.height, i+win, v, _wi-win, _height);
				}
				else {
					_context.drawImage(_image, j, 0, _w, _image.height, i, v, _wi, _height);
				}
				j = jn%_image.width;
			}
			_offset = (_offset-3)%_image.width;
		}
		_timer = setTimeout(animateWave, _delay);
	}
	
	_this.init = function(selector, height) {
		if(_timer) {
			clearTimeout(_timer);
			_timer = null;
		}
		_window = $(window).resize(resizeHandler);
		_height = height;
		height += _h*2;
        
        try{
        _canvas = $(selector).attr({height: height}).css({width: "100%", height: height+"px"});
        resizeHandler();
        if(_canvas){ _context = _canvas.get(0).getContext('2d');}
        }catch(e){}
        
		if(_context && !agent.match(/(iphone)|(ipad)|(ipod)|(android)|(blackberry)|(webos)|(windows phone)|(zune)|(bada)/i)) {
			_image = null;
			_offset = 0;
			animateWave();
		}
	}
	
	_this.animate = function(img) {
        if(_context && !agent.match(/(iphone)|(ipad)|(ipod)|(android)|(blackberry)|(webos)|(windows phone)|(zune)|(bada)/i)){
            $("<img>").one("load", loadHandler).attr("src", img);
        } else {
            $('#stage').parent().css({"background-image": "url("+img+")", "background-repeat": "repeat-x"});
        }
	};
}
