/* ---------------------------------- */
/* document ready */
jQuery(function($) {
    $('[data-controller]').Instantiate();
	
	$mobile = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));
	
	if ($mobile) {
		$('body').addClass('mobile');
	}
	
    $.nyroModalSettings({
        bgColor : '#ffffff',
        endFillContent : function(res) {
            var hasClose = $(res.content).find('a.closeBtn').length;
            if(hasClose === 0) {
                $(res.content).prepend('<a title="close" href="#" class="closeBtn nyroModalClose">Close</a>');
            }
           	$('.JM_objNewsletter').setNewsletterForm();
        },
        endShowContent : function() {
            $('#nyroModalContent .scroll-pane').jScrollPane({
                showArrows : true
            });
        }
    });

    $("#JM_objTree").animateSprite({
        speed : 160,
        step : 455,
        end : -3640
    });

    $("#JM_objBird").animateSprite2({
        speed : 160,
        step : 166,
        end : -1660
    });

    $("#JM_objFish").animateSprite2({
        speed : 160,
        step : 189,
        end : -2835
    });

    $("#JM_objLogo").animateSprite2({
        speed : 60,
        step : 153,
        end : -7191
    });
    
  	$("#JM_objBee").animateSpriteSpecial({
        speed : 60,
        step : 46,
        end : -46
    });
    
    $('.JM_objNewsletter').setNewsletterForm();
    $('#mailform').setContactForm();
    
    $('#JM_objContent .JM_objNewsletter .closeBtn').bind('click',function(){
    	$('.JM_objNewsletter').hide();
    })
    
    $(window).bind("smartresize", function() {
    	var $el = $('[data-controller="centerElement"]');
    	var $wHeight = $(window).height();
        var $eHeight = $el.height();
        
        if ($wHeight >= ($eHeight + 305)) {
       		$el.animate({'marginTop':155},200,'swing');
        }
        else {
       		$el.animate({'marginTop':0},200,'swing');        	
        } 
    });
    
    // auto start sprites (on idle, only on home)
    if ($('.JM_homeVisual').length>0){
    	$(document).bind("idle.idleTimer", $.fn.autoAnimateSprites);
    	$.idleTimer(Math.floor(Math.random()*8000+2000)); // start timer
    }
    
    
});
/* ---------------------------------- */
/* Auto Instantiate */
(function($) {
    $.fn.Instantiate = function(settings) {
        var config = {};
        if(settings)
            $.extend(config, settings);
        this.each(function() {
            var $self = $(this);
            var $controller = $self.attr('data-controller');
            if($self[$controller]) {
                $self[$controller]();
            }
        });
    }
})(jQuery);

/* ---------------------------------- */
/* sprite animation */
$.fn.animateSprite = function() {
    var $that = $(this), args = arguments[0] || {}, speed = args.speed || animSpeed, step = args.step || 0, end = args.end || 0;
    var bgString = "background-position";
    var $mobile = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));
	var $hitarea = $that.find('span')
	var counter;
	
    if($mobile) {
        $hitarea.bind('mousedown touchstart MozTouchDown', function() {
            $.doTimeout('loop', speed, function() {
                var bgPos = $that.css(bgString) || $that.css(bgString + "-x") + " " + $that.css(bgString + "-y");
                var curBGPos = bgPos.split(" ");
                if(parseInt(curBGPos[1]) !== (($that.hasClass('clicked')) ? 0 : end)) {
                    $that.css(bgString, curBGPos[0] + " " + (parseInt(curBGPos[1]) - (($that.hasClass('clicked')) ? -step : step)) + "px");
                    return true;
                } else {
                	$that.toggleClass('clicked');
                    return false;
                }
                return true;
            });
        });
    } else {
        $hitarea.bind("mouseover mouseout", function(e) {
            $.doTimeout('loop', speed, function() {
                var bgPos = $that.css(bgString) || $that.css(bgString + "-x") + " " + $that.css(bgString + "-y");
                var curBGPos = bgPos.split(" ");
                if(parseInt(curBGPos[1]) !== ((e.type === "mouseout") ? 0 : end)) {
                    // move logo if tree is animated
                    if($that.attr('id')==='JM_objTree') {
                		var $el = $('#JM_objLogo');
                		if (parseInt(curBGPos[1]) < - 2*step && parseInt(curBGPos[1]) > (end + 2*step)) {
                			$el.css({top:((e.type === "mouseout") ? ($el.position().top-2): ($el.position().top+2))});
                		}
                    }                	
                    $that.css(bgString, curBGPos[0] + " " + (parseInt(curBGPos[1]) - ((e.type === "mouseout") ? -step : step)) + "px");
                    return true;
                } else {
                    return false;                    
                }
                return true;
            });
        });
    }
};

/* ---------------------------------- */
/* sprite animation without mouseout  */
(function($) {
    $.fn.animateSprite2 = function(settings) {
        return this.each(function() {
            var $that = $(this), args = settings || {}, speed = args.speed, step = args.step || 0, end = args.end || 0;
            var bgString = "background-position";
            var $hitarea = $that.find('span');
            
            $hitarea.bind("mouseover mousedown touchstart MozTouchDown", function(e) {
                $(this).doTimeout('loop', speed, function() {
                    var bgPos = $that.css(bgString) || $that.css(bgString + "-x") + " " + $that.css(bgString + "-y");
                    var curBGPos = bgPos.split(" ");
                    if(parseInt(curBGPos[1]) !== end) {
                        $that.css(bgString, curBGPos[0] + " " + (parseInt(curBGPos[1]) - step) + "px");
                        return true;
                    } else {
                        $that.css(bgString, curBGPos[0] + " 0px");
                        return false;
                    }
                    return true;
                });
            });
        })
    };
})(jQuery);


/* ---------------------------------- */
/* special sprite animation  */

(function($) {
    $.fn.animateSpriteSpecial = function(settings) {
        return this.each(function() {
            var $that = $(this), args = settings || {}, speed = args.speed, step = args.step || 0, end = args.end || 0;
            var bg = "background-position";
            var $hitarea = $that.find('span');
            var animationEnd;
			var bezierSteps = [];
			var counter = 0;
			var $mobile = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));
			var $landscape = (($mobile && window.orientation == 90) || ($mobile && window.orientation == -90)) ? true : false;

            var bezierTLBR = {
                start : {x : 180,y : ($landscape ? 67 : 90),angle : 100},
                end : {x : 840,y : ($landscape ? 467 : 490),angle : -50,length : 0.25}
            };
            
            var bezierBRML = {
            	start : bezierTLBR.end,
            	end: {x : 240,y : ($landscape ? 277 : 300),angle : -50,length : 0.25}
            }
            
            var bezierMLBL = {
            	start : bezierBRML.end,
            	end: {x : 140,y : ($landscape ? 467 : 490), angle : -50,length : 0.25}
            }

            var bezierBLTL = {
            	start : bezierMLBL.end,
            	end: bezierTLBR.start
            }
            
            bezierSteps.push(bezierTLBR);
            bezierSteps.push(bezierBRML);
            bezierSteps.push(bezierMLBL);
            bezierSteps.push(bezierBLTL);
            
            $hitarea.bind("mouseover mousedown touchstart MozTouchDown", function(e) {
                animationEnd = false;
                $(this).doTimeout('loop', speed, function() {
                    $that.toggleClass('on');
                    if(animationEnd) {
                        return false;
                    }
                    return true;
                });

                $that.stop(false,true).animate({
                    path : new $.path.bezier(bezierSteps[counter])
                }, 1000, 'swing', function() {
                    animationEnd = true;
                    counter++;
                    if (counter === bezierSteps.length ) {
                    	counter = 0;
                    }
                })
            });
        })
    };
})(jQuery);


/* ---------------------------------- */
/* auto start sprite animation */

(function($) {
    $.fn.autoAnimateSprites = function() {
    	
    	var $mobile = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));
    	var sprites = [
    	               $("#JM_objBird"),
    	               $("#JM_objFish"),
    	               $("#JM_objLogo"),
    	               $("#JM_objBee")
    	              ];

    	var randomSprite = sprites[Math.floor(Math.random()*sprites.length)].find('span');
    	if ($mobile)
    		randomSprite.trigger('mousedown').trigger('touchstart').trigger('MozTouchDown');
    	else
    		randomSprite.trigger('mouseover');
   		
   		$.idleTimer(Math.floor(Math.random()*8000+2000)); // update timer
    }
})(jQuery);


/* ---------------------------------- */
/* function to center elements */
(function($) {
    $.fn.centerElement = function() {
        var $self = $(this);
        var $wHeight = $(window).height();
        var $sHeight = $self.height();
        var $sTop = $self.position().top;
        
        if ($wHeight > ($sHeight + 305)) {
       		$self.css({'marginTop':155});
        }        
    }
})(jQuery);

/* ---------------------------------- */
/* disable nyromodal if mobile */
(function($) {
    $.fn.disableModal = function() {
        var $self = $(this);
		var $mobile = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));
        
        if($mobile) {
        	$self.unbind('click');
        }   
    }
})(jQuery);

/* ---------------------------------- */
/* prepare newsletter formular */
(function($) {
    $.fn.setNewsletterForm = function() {
        var $self = $(this);
        var $form = $self.find('form');
        var $formSelect = $form.find('select');
		var $mobile = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i)));
		
		$form.find('input[type="text"]').attr('maxLength','45');
		
	    $formSelect.each(function() {
            $(this).find('option:first').each(function() {
                if($(this).attr('value') === '') {
                    $(this).html('');
                }
            });
        });

        $form.validate({
            invalidHandler : function(e, validator) {
                var errors = validator.numberOfInvalids();
                if(errors) {
                    $(".newsletter_errorText").show();
                }
            },
            errorPlacement : function(error, element) {
                if(element[0].nodeName === 'SELECT') {
                    element.parent().find('.dk_theme_dedonisland').addClass('error');
                }
            },
            errorClass : "error"
        });
		
		if (!$mobile) {
	        $formSelect.dropkick({
        	    theme : 'dedonisland',
            	width : 320
    	    });
       }
    }
})(jQuery);


/* ---------------------------------- */
/* prepare contact formular */
(function($) {
    $.fn.setContactForm = function() {
        var $self = $(this);
        
        $self.find('input[type="text"], textarea').addClass('required');
        $self.find('input#mailformemail').addClass('email');
        $self.find('input[type="text"]').attr('maxLength','45');
        $self.find('textarea').bind('keydown',function(e){

       		if(e.keyCode == 13 && $(this).val().split("\n").length >= 6) { 
        		return false;
    		}
    		
    		if (e.keyCode === 8 || e.keyCode === 46 || e.keyCode === 37 || e.keyCode === 39) {
    			return true;
    		}
    		
    		if ($(this).val().length > 280) {    			
    			return false;
    		}
        })
        
        $self.validate({
            invalidHandler : function(e, validator) {
                var errors = validator.numberOfInvalids();
                if(errors) {
                    $(".csc-mailform-error-text").show();
                }            	
            },
            errorPlacement : function(error, element) {
                
            },
            errorClass : "error"
        });

    }
})(jQuery);


/* ---------------------------------- */
/* smartresize */
(function($) {
    var event = $.event, resizeTimeout;
    event.special["smartresize"] = {
        setup : function() {
            $(this).bind("resize", event.special.smartresize.handler);
        },
        teardown : function() {
            $(this).unbind("resize", event.special.smartresize.handler);
        },
        handler : function(event, execAsap) {
            // Save the context
            var context = this, args = arguments;
            // set correct event type
            event.type = "smartresize";
            if(resizeTimeout)
                clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(function() {
                jQuery.event.handle.apply(context, args);
            }, execAsap === "execAsap" ? 0 : 300);
        }
    }
    $.fn.smartresize = function(fn) {
        return fn ? this.bind("smartresize", fn) : this.trigger("smartresize", ["execAsap"]);
    };
})(jQuery);



