(function ($) {
    // Monkey patch jQuery 1.3.1+ css() method to support CSS 'transform'
    // property uniformly across Safari/Chrome/Webkit, Firefox 3.5+, IE 9+, and Opera 11+.
    // 2009-2011 Zachary Johnson www.zachstronaut.com
    // Updated 2011.05.04 (May the fourth be with you!)
    function getTransformProperty(element)
    {
        // Try transform first for forward compatibility
        // In some versions of IE9, it is critical for msTransform to be in
        // this list before MozTranform.
        var properties = ['transform', 'WebkitTransform', 'msTransform', 'MozTransform', 'OTransform'];
        var p;
        while (p = properties.shift())
        {
            if (typeof element.style[p] != 'undefined')
            {
                return p;
            }
        }
        
        // Default to transform also
        return 'transform';
    }
    
    var _propsObj = null;
    
    var proxied = $.fn.css;
    $.fn.css = function (arg, val)
    {
        // Temporary solution for current 1.6.x incompatibility, while
        // preserving 1.3.x compatibility, until I can rewrite using CSS Hooks
        if (_propsObj === null)
        {
            if (typeof $.cssProps != 'undefined')
            {
                _propsObj = $.cssProps;
            }
            else if (typeof $.props != 'undefined')
            {
                _propsObj = $.props;
            }
            else
            {
                _propsObj = {}
            }
        }
        
        // Find the correct browser specific property and setup the mapping using
        // $.props which is used internally by jQuery.attr() when setting CSS
        // properties via either the css(name, value) or css(properties) method.
        // The problem with doing this once outside of css() method is that you
        // need a DOM node to find the right CSS property, and there is some risk
        // that somebody would call the css() method before body has loaded or any
        // DOM-is-ready events have fired.
        if
        (
            typeof _propsObj['transform'] == 'undefined'
            &&
            (
                arg == 'transform'
                ||
                (
                    typeof arg == 'object'
                    && typeof arg['transform'] != 'undefined'
                )
            )
        )
        {
            _propsObj['transform'] = getTransformProperty(this.get(0));
        }
        
        // We force the property mapping here because jQuery.attr() does
        // property mapping with jQuery.props when setting a CSS property,
        // but curCSS() does *not* do property mapping when *getting* a
        // CSS property.  (It probably should since it manually does it
        // for 'float' now anyway... but that'd require more testing.)
        //
        // But, only do the forced mapping if the correct CSS property
        // is not 'transform' and is something else.
        if (_propsObj['transform'] != 'transform')
        {
            // Call in form of css('transform' ...)
            if (arg == 'transform')
            {
                arg = _propsObj['transform'];
                
                // User wants to GET the transform CSS, and in jQuery 1.4.3
                // calls to css() for transforms return a matrix rather than
                // the actual string specified by the user... avoid that
                // behavior and return the string by calling jQuery.style()
                // directly
                if (typeof val == 'undefined' && jQuery.style)
                {
                    return jQuery.style(this.get(0), arg);
                }
            }

            // Call in form of css({'transform': ...})
            else if
            (
                typeof arg == 'object'
                && typeof arg['transform'] != 'undefined'
            )
            {
                arg[_propsObj['transform']] = arg['transform'];
                delete arg['transform'];
            }
        }
        
        return proxied.apply(this, arguments);
    };
})(jQuery);

(function ($) {
    // Monkey patch jQuery 1.3.1+ to add support for setting or animating CSS
    // scale and rotation independently.
    // 2009-2010 Zachary Johnson www.zachstronaut.com
    // Updated 2010.11.06
    var rotateUnits = 'deg';
    
    $.fn.rotate = function (val)
    {
        var style = $(this).css('transform') || 'none';
        
        if (typeof val == 'undefined')
        {
            if (style)
            {
                var m = style.match(/rotate\(([^)]+)\)/);
                if (m && m[1])
                {
                    return m[1];
                }
            }
            
            return 0;
        }
        
        var m = val.toString().match(/^(-?\d+(\.\d+)?)(.+)?$/);
        if (m)
        {
            if (m[3])
            {
                rotateUnits = m[3];
            }
            
            $(this).css(
                'transform',
                style.replace(/none|rotate\([^)]*\)/, '') + 'rotate(' + m[1] + rotateUnits + ')'
            );
        }
        
        return this;
    }
    
    // Note that scale is unitless.
    $.fn.scale = function (val, duration, options)
    {
        var style = $(this).css('transform');
        
        if (typeof val == 'undefined')
        {
            if (style)
            {
                var m = style.match(/scale\(([^)]+)\)/);
                if (m && m[1])
                {
                    return m[1];
                }
            }
            
            return 1;
        }
        
        $(this).css(
            'transform',
            style.replace(/none|scale\([^)]*\)/, '') + 'scale(' + val + ')'
        );
        
        return this;
    }

    // fx.cur() must be monkey patched because otherwise it would always
    // return 0 for current rotate and scale values
    var curProxied = $.fx.prototype.cur;
    $.fx.prototype.cur = function ()
    {
        if (this.prop == 'rotate')
        {
            return parseFloat($(this.elem).rotate());
        }
        else if (this.prop == 'scale')
        {
            return parseFloat($(this.elem).scale());
        }
        
        return curProxied.apply(this, arguments);
    }
    
    $.fx.step.rotate = function (fx)
    {
        $(fx.elem).rotate(fx.now + rotateUnits);
    }
    
    $.fx.step.scale = function (fx)
    {
        $(fx.elem).scale(fx.now);
    }
    
    /*
    
    Starting on line 3905 of jquery-1.3.2.js we have this code:
    
    // We need to compute starting value
    if ( unit != "px" ) {
        self.style[ name ] = (end || 1) + unit;
        start = ((end || 1) / e.cur(true)) * start;
        self.style[ name ] = start + unit;
    }
    
    This creates a problem where we cannot give units to our custom animation
    because if we do then this code will execute and because self.style[name]
    does not exist where name is our custom animation's name then e.cur(true)
    will likely return zero and create a divide by zero bug which will set
    start to NaN.
    
    The following monkey patch for animate() gets around this by storing the
    units used in the rotation definition and then stripping the units off.
    
    */
    
    var animateProxied = $.fn.animate;
    $.fn.animate = function (prop)
    {
        if (typeof prop['rotate'] != 'undefined')
        {
            var m = prop['rotate'].toString().match(/^(([+-]=)?(-?\d+(\.\d+)?))(.+)?$/);
            if (m && m[5])
            {
                rotateUnits = m[5];
            }
            
            prop['rotate'] = m[1];
        }
        
        return animateProxied.apply(this, arguments);
    }
})(jQuery);


/*!
 * common.js
 * v3.0.3
 */
 
var base = {
	log : true,
	fixpng : false
}

if(typeof console === 'undefined') {
    var console = {
        log: function(message) {},
        info: function(message) {},
        warn: function(message) {},
        error: function(message) {
            alert(message);
        }
    }
}

var runTime = (function(){
	var startTime = new Date();
	base.browser = navigator.userAgent;
	base.platform = navigator.platform;
	return function(){
		var endTime = new Date();
		var elapsedTime = Number(endTime-startTime);
		base.runtime = Number(elapsedTime/1000);
	}
})();

function log(a){
	if(!base.log) return false;
	runTime();
	console.log('['+base.runtime+']',a);
}

if(jQuery) log('jQuery '+jQuery.fn.jquery);

if($.browser.msie && $.browser.version <= 6 && base.fixpng && DD_belatedPNG) {
	DD_belatedPNG.fix('.fixpng');
}

function random(min, max)
{
	return Math.random()*(max-min)+min;
}

function isValidEmail(email)
{
	return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
}

var isiPad = navigator.userAgent.match(/iPad/i) != null;		
var isiPhone = navigator.userAgent.match(/iPhone/i) != null;
var isiPod = navigator.userAgent.match(/iPod/i) != null;

/*!
 * function PLACEHOLDER 
 * $('input[placeholder], textarea[placeholder]').placeholder();
 */
function Placeholder(input) {
	this.input = input;
	if (input.attr('type') == 'password') {
		this.handlePassword();
	}
	$(input[0].form).submit(function() {
		if (input.hasClass('placeholder') && input[0].value == input.attr('placeholder')) {
			input[0].value = '';
		}
	});
}
Placeholder.prototype = {
	show : function(loading) {
		if (this.input[0].value === '' || (loading && this.valueIsPlaceholder())) {
			if (this.isPassword) {
				try {
					this.input[0].setAttribute('type', 'text');
				} catch (e) {
					this.input.before(this.fakePassword.show()).hide();
				}
			}
			this.input.addClass('placeholder');
			this.input[0].value = this.input.attr('placeholder');
		}
	},
	hide : function() {
		if (this.valueIsPlaceholder() && this.input.hasClass('placeholder')) {
			this.input.removeClass('placeholder');
			this.input[0].value = '';
			if (this.isPassword) {
				try {
					this.input[0].setAttribute('type', 'password');
				} catch (e) { }
				this.input.show();
				this.input[0].focus();
			}
		}
	},
	valueIsPlaceholder : function() {
		return this.input[0].value == this.input.attr('placeholder');
	},
	handlePassword: function() {
		var input = this.input;
		input.attr('realType', 'password');
		this.isPassword = true;
		if ($.browser.msie && input[0].outerHTML) {
			var fakeHTML = $(input[0].outerHTML.replace(/type=(['"])?password\1/gi, 'type=$1text$1'));
			this.fakePassword = fakeHTML.val(input.attr('placeholder')).addClass('placeholder').focus(function() {
				input.trigger('focus');
				$(this).hide();
			});
			$(input[0].form).submit(function() {
				fakeHTML.remove();
				input.show()
			});
		}
	}
};
var NATIVE_SUPPORT = !!("placeholder" in document.createElement( "input" ));
$.fn.placeholder = function() {
	return NATIVE_SUPPORT ? this : this.each(function() {
		var input = $(this);
		var placeholder = new Placeholder(input);
		placeholder.show(true);
		input.focus(function() {
			placeholder.hide();
		});
		input.blur(function() {
			placeholder.show(false);
		});

		if ($.browser.msie) {
			$(window).load(function() {
				if(input.val()) {
					input.removeClass("placeholder");
				}
				placeholder.show(true);
			});
			input.focus(function() {
				if(this.value == "") {
					var range = this.createTextRange();
					range.collapse(true);
					range.moveStart('character', 0);
					range.select();
				}
			});
		}
	});
}



/*!
 * function BLACKOUT v0.2
 * action = init || show || hide
 * context = object styles || duration
 * $(selector).blackout(action, context);
 */
function blackout(parent, action, css){
	var self = this;
	this.parent = parent;
	this.duration = 500;
	this.height = '100%';
	this.css = $.extend({
		position : 'absolute',
		left : 0,
		top : 0,
		width : '100%',
		height : self.height,
		background : '#000',
		opacity : 0.7,
		zIndex : 1000,
		display : 'none'
	},css);
	this.html = $('<div class="blackout"></div>');
	this.init();
}
blackout.prototype = {
	init : function(){	
		if(typeof this.parent.data('blackout') != 'object')
		{
			this.html.appendTo(this.parent);
		}
		if(this.parent[0].nodeName === 'BODY')
		{
			var winHeight = $(window).height();
			var bodyHeight = this.parent.outerHeight();
			this.css.height = bodyHeight < winHeight ? winHeight : bodyHeight;
		} else {
			this.css.height = this.parent.outerHeight();
		}
		this.html.css(this.css).height(this.css.height);
	},
	show : function(){
		this.html.fadeIn(this.duration);
	},
	hide : function(){
		this.html.fadeOut(this.duration);
	}
}
$.fn.blackout = function(action, css) {
	return this.each(function(){
		var self = $(this),
			proto = self.data('blackout');
			
		if(typeof proto == 'object')
		{
			if(typeof css == 'object')
			{
				proto.css = css;
			}
			else
			{
				proto.duration = css;
			}
			proto[action]();
		} else {
			proto = new blackout(self,action,css);
			self.data('blackout',proto);
		}
	});
}









function scrollScene(){
	var scroll = $('#scroll');
	var canvas_width = $('#scroll').width();
	var slide = $('#slide');
	var scroll_move = $('#scroll_move');
	var scroll_move_width = 98;
	var scroll_width = 816;
	var self = this;
	var wheel = [0,20];
	var animateInterval;
	
	this.s = {
		move_pageX : 0,
		current_pageX : 0,
		rate : 0
	}
	
	scroll_move.bind('mousedown touchstart MozTouchDown', function(e){
		clearInterval(animateInterval);
		self.s.move_pageX = self.s.current_pageX;
		e = fixTouchEvent(e);
		scroll_move.addClass('active');
		var pageX = e.pageX;
		$('body').bind('mousemove touchmove MozTouchMove',function(e){
			e = fixTouchEvent(e);	
			scroll_move.css({left:correctionScroll(e.pageX-pageX+self.s.move_pageX)});
			positionScene();
			startFrame();
			return false;
		});		
		return false;
	});
	
	$(window).load(function(){
		animateInterval = setInterval(function(){
			scroll_move.css({left:correctionScroll(self.s.current_pageX+0.4)});
			positionScene();
			startFrame();
		},10);
	});

	
	function correctionScroll(a){
		self.s.current_pageX = a <= 0 ? 0 : a >= scroll_width ? scroll_width : a;
		self.s.rate = self.s.current_pageX/(scroll_width+30)*100;
		return self.s.current_pageX;
	}	
	
	var scene = $('#scene');
	
	$('#slide').bind('touchstart MozTouchDown', function(e){
		clearInterval(animateInterval);
		self.s.move_pageX = self.s.current_pageX;
		e = fixTouchEvent(e);
		var pageX = e.pageX;
		$('body').bind('mousemove touchmove MozTouchMove',function(e){
			e = fixTouchEvent(e);	
			scroll_move.css({left:correctionScroll(e.pageX-pageX+self.s.move_pageX)});
			positionScene('revert');
			startFrame();
			return false;
		});		
		return false;
	});

	$('body').bind('mouseup touchend MozTouchRelease',function(){
		self.s.move_pageX = self.s.current_pageX;
		$(this).unbind('mousemove touchmove');
		scroll_move.removeClass('active');
	});

	var scene_width = scene.width();
	function positionScene(action, duration){
		if(action == 'animate')
		{
			scene.animate({left:-self.s.rate*(scene_width-canvas_width)/100},duration,'linear');
		} else if(action == 'revert'){
			scene.css({left:-self.s.rate*(scene_width-canvas_width)/100});
		} else {
			scene.css({left:-self.s.rate*(scene_width-canvas_width)/100});
		}
	}
	
	/*
	slide.mousewheel(function(objEvent, intDelta){
		var shag = scroll_width/wheel[1];
		if (intDelta > 0){

		}
		else if (intDelta < 0){
			wheel[0]++;
			
			scroll_move.animate({left:correctionScroll(shag*wheel[0])},500,'linear');
			positionScene('animate',500);
			startFrame('animate');
		}
		return false;
	});
	*/

	this.frame = [];
	
	this.animate = function(property, params, result){
				
		if(params['timeAfter'] && this.s.rate < params['timeAfter'])
		{
			return false;
		}
		
		var procent = (this.s.rate-params['timeStart'])/(params['timeEnd']-params['timeStart'])*100;
				
		if(this.s.rate > params['timeStart'] && this.s.rate <= params['timeEnd'])
		{		
			var a = Math.abs(params['valueStart']);
			var b = Math.abs(params['valueEnd']);	
			var c = a > b ? a-b : b-a;
			var d = procent*c/100;
			
			if(params['valueStart'] > params['valueEnd'])
			{
				result = params['valueStart']-d;
			}
			 else if(params['valueStart'] < 0 && params['valueEnd'] > params['valueStart']) 
			{
				result = d-a;
			} else{
				result = d;
			}
			
		} else if(this.s.rate <= params['timeStart'])
		{
			result = params['valueStart'];
		} else {
			result = params['valueEnd'];
		}

		//if(params['log']) log(this.s.rate)
		if(property == 'rotate')
		{
			params['node'].rotate(result);
		}
		else 
		{
			if(self.frameAnimate)
			{
				var g = {};
				g[property] = result;
				params['node'].animate(g,{queue:false,duration:500});
			} else {
				var g = {};
				g[property] = result;
				params['node'].css(g);
			}
		}
		
		return this;
	}
	
	function startFrame(action){
		for(var i=0; i<self.frame.length; i++)
		{
			if(typeof self.frame[i] === 'function')
			{
				if(action == 'animate')
				{
					self.frameAnimate = true;
				} else {
					self.frameAnimate = false;
				}
				self.frame[i].call(self);
			}
		}
	}
	
}




function fixTouchEvent(e){
    if(e.originalEvent.touches && e.originalEvent.touches.length) {
        return e.originalEvent.touches[0];
    } else if(e.originalEvent.changedTouches && e.originalEvent.changedTouches.length) {
        return e.originalEvent.changedTouches[0];
    } else {
		return e;
	}
}












