var l, pw, ph, prevh, prevw, thumb, hash, tid, t, relink, content, oldhash = "", settings = {};
var click = true;
var url = window.location.href;

$(function () {
	
	var isPrivate = url.indexOf("kundenprojekte");
	
	if (isPrivate != "-1") {	
		$("body").addClass("privatePost").addClass("paged");
		// init private Page
		initPage();		  
        // init video
        VideoJS.setupAllWhenReady(); 
	} else {	
		// redirect real urls
		if(window.location.hash == "#redirected") {
			// browser-back: go back from where you came
			history.go(-2);
		} else if (!window.location.hash && !$('body').hasClass("home")) { // if hash and body has not class home
			redirect();
		} else {
			initPage();
		}	
	}		

});


// redirect for right page
function redirect() {
	url = url.split("/");
	url = url.pop();
	var newUrl = 'http://'+window.location.host+'#'+url;
	window.location.hash = "redirected";
	window.location.href = newUrl;	
}

// init page
function initPage() {
	
	dur = $('#content').find('.post').size() * settings.speed;

    // search funktionality in rollover
    $('.search').mouseenter(function () {
        if ($(this).val() == 'Search') $(this).val('');
        $(this).focus();
    })
    $('.search').mouseleave(function () {
        if ($(this).val() == '') {
            $(this).val('Search');
            $(this).blur();
        }
    })
    
    // hide page
    $('#theLogo').hover(
    	function() {
    		$('#theInfo,#theFilter,#theSearch,#page,.hit,#footer,#privatePost').stop().animate({opacity: "0"},200,"easeOutQuad");
    	},
    	function() {
    		$('#theInfo,#theFilter,#theSearch,#page,.hit,#footer,#privatePost').stop().animate({opacity: "1"},400,"easeOutQuad");    	
    	}
    );
    
    // show navigation 
    $('.navigation').hide();
    $('.navigation_content').css({opacity: "0"});    
    $('.browse').click(function () {    
    	var $thisNav = $(this).next('.navigation');
    	var $otherNav = $('.navigation').not($thisNav);    	
        if ($(this).hasClass('down')) {
    		$thisNav.children('.navigation_content').animate({opacity: "1"},200);
        	$thisNav.slideDown(200, function () {
        		$("#content").grid(settings);
            	$thisNav.prev().removeClass('down').addClass('up');
            });            
            $otherNav.slideUp(200, function () {
            	 $(this).prev().removeClass('up').addClass('down');
            });
            $otherNav.children(".navigation_content").animate({opacity: "0"},200);           
        } else {
        	$thisNav.slideUp(300, function () {
        		$("#content").grid(settings);
            	$thisNav.prev().removeClass('up').addClass('down');
            });
            $thisNav.children(".navigation_content").animate({opacity: "0"},200);           	
        }
    });
    
    // post hover
	
	if (!$.browser.msie && !$.browser.version <= 7) { // not for IE7 and below	
    	$('.postBox img.wp-post-image').css({opacity: "0.2"}); 
    	$('.post').hover(function(){
    			$(this).find("img.wp-post-image").stop().animate({opacity: "1"},300, "easeOutQuad");
    			$(this).find(".postTitle span").stop().animate({opacity: "0"},200);
    		},
    		function(){
    			if($(this).hasClass(".filtered")) {
    				$(this).find("img.wp-post-image").stop().animate({opacity: "0.1"},600, "easeOutQuad");    		
    			} else {
    				$(this).find("img.wp-post-image").stop().animate({opacity: "0.2"},600, "easeOutQuad");    			
    			}
    			$(this).find(".postTitle span").stop().animate({opacity: "1"},1200);    
    		}
    	);
    }
    
    // filtering
    $("#categories a").not(".removeFilter a").click(function() {
		$theClass = $(this).html();
		$(this).addClass("active");
		$("#categories a").not(this).removeClass("active");
		filterPosts($theClass);
    	return false;
    });
    $(".removeFilter a").click(function() {
    	$('.postBox img.wp-post-image').css({opacity: "0.2"});
		$(".post").removeClass("filtered");
		$("#categories a").removeClass("active");
		$(".removeFilter").slideUp(200, function() {
			$("#content").grid(settings);
		});
    	return false;
    });   
    
    // what to do at resize
    var resizeTimer = null;
    $(window).bind('resize', function () {
        if (resizeTimer) clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () {
            $("#content").grid(settings, '', false, false);
        }, 100);
    });
    $(".thumbimg").live("mouseenter", function () {
        $(this).fadeTo('fast', 1);
    }).live("mouseleave", function () {
        $(this).fadeTo('slow', 0.3);
    });
    
    // disable animation at start
    settings.animateUpdate = false;
    $("#content").grid(settings, '', false, true);
    // enable animation
    settings.animateUpdate = true;
    
    // ajax loading
    $(".page > a[rel='history']").live('click', function (e) {
        var hash = this.href;
        var page = this.id;
        hash = hash.replace(/^.*#/, '');
        $.historyLoad(hash, page);
        $("#loader").css('top', e.pageY - 10);
        $("#loader").css('left', e.pageX - 10);
        $("#loader").fadeIn(100);
    });
    $("#content div > a[rel='history']").live('click', function (e) {
        if(click===true){
        	click = false;
        	var hash = this.href;
	        hash = hash.replace(/^.*#/, '');
	        $.historyLoad(hash);
	        $("#loader").css('top', e.pageY - 10);
	        $("#loader").css('left', e.pageX - 10);
	        $("#loader").fadeIn(100);
	        return true;
        } else {
        	return false;
        }
    });
    
    if(window.location.hash != "#redirected") {
    	$.historyInit(pageload);
	} else {
		history.go(-2);
	}
	
}

// filter posts 
function filterPosts(theClass) {
	$("."+theClass).addClass("filtered");
    $("."+theClass).find('img.wp-post-image').css({opacity: "0.1"});
	$(".post").not("."+theClass).removeClass("filtered");
	$(".removeFilter").slideDown(200, function() {
		$("#content").grid(settings, '.'+theClass+':first', false, true);
	});    
}

// init content functions
function initContent() {
    // close project
    $(".closeProject").click(function() {
    	closeProject();
        return false;
    });
    // close page
    $(".closePage").click(function() {
    	closePage();
        return false;
    });
}

// close project
function closeProject() {   
    $(t).fadeOut(settings.speed, function () {
            $(this).empty();
            $(this).append(relink);
            $(this).removeClass('open opencols');
    });    
    $(t).fadeIn(function(){
    	$("#content").grid(settings, t, false, true);        
    });	
}

// close project
function closePage() {
	$('#page').removeClass('post').empty();
	window.setTimeout(function() {
    	$("#content").grid(settings, '#theLogo', false, true); 
	
	}, 200); 
}

// init ajax
function pageload(hash, page) {
	if (page) is_menu = 1; else is_menu = 0;
    l = t;
    t = '#hit-' + hash;
    relink = content;
    h = $(t).height();
    w = $(t).width();
    if (!page) {
        the_url = $(t).find('a').attr('id');
    } else {
        the_url = page;
    }
    if ($(t).length == 0) {
        the_url = $('a[href$="#' + hash + '"]').attr('id');
        page = the_url;
        $('#page').addClass('post').empty();
    }
    if (hash) {
        $.ajax({
            url: the_url,
            cache: false,
            success: function (html) {
                $(l).fadeOut(settings.speed, function () {
                        $(this).empty();
                        $(this).append(relink);
                        $(this).removeClass('open opencols');
                });
                $(l).fadeIn();
                prevh = $(t).height();
                prevw = $(t).width();
                ph = $(t).find('img').height();
                pw = $(t).find('img').width();
                $("#loader").fadeOut(settings.duration + 100, function () {
                    if (!page) { // show projects
                        $('#page').removeClass('post').empty();
                        content = $(t).html();
    					relink = content;
                        tid = $(t).find('a').attr('id');
                        thumb = $(t).find('img').attr('src');
                        oldhash = $(t).find('a').attr('href');
                        $(t).empty();
                        $(t).append(html);
                        _height = $("#hit-" + hash).height();
                        $("#hit-" + hash + ' .single').fadeTo(0, 0);
                        $(t).addClass('open opencols');
                        $("#content").grid(settings, t, false, true);
                        click = true;
                        // change background (custom)
                        window.setTimeout(function(){
                        	$("body").removeClass('paged');                        
                        },1300); 
                        window.setTimeout(function(){   
                        	// init video (custom)
                        	VideoJS.setupAllWhenReady();                      
                        },300);                  
                        initContent();
                        initGallery();
				        return true;
                    } else { // show pages
                        $('#page').addClass('post').empty();
                        $('#page').append(html).fadeTo(0, 0);
                        $('#page .single').fadeTo(0, 0);
                        // change background (custom)
                        window.setTimeout(function(){
                        	$("body").addClass('paged');                        
                        },1300);                        
                        initContent();
                        $("#content").grid(settings, '#page', false, true);
                    }
                });
            }
        });
        trackPiwik("http://www.mightymovies.de/#"+hash,hash);
    } else {
        $(t).empty();
    }
}

// gallery
function initGallery() {
	// init navigation
	$(".imgGal img").not(".imgGal img.active").css({opacity: "0.2"});
	$('.nextImg').click(function() {	
		nextImg("next");
	});
	$('.prevImg').click(function() {
		nextImg("prev");
	});
	$('.prevImg').hover(
		function() {
			$('.prevImg span').fadeIn(200);
			$('.nextImg span').fadeOut(200);
		},
		function() {
			$('.prevImg span').fadeOut(200);
			$('.nextImg span').fadeIn(200);
		}
	);
}

function nextImg(next) {	
	if(!$("body").hasClass("imaging")) {
	
		$("body").addClass("imaging");
    	var $active = $('.imgGal img.active');     	
    	    	
    	// determine next image
    	if(next == "next") {
    		$next = $active.next();    	
    		var $activeW = $active.attr("width"); 
    		 
   			$active.animate({marginLeft: "-"+$activeW+"px", opacity: "0.2"},600, "easeOutQuad", function() {
   				$active.remove().css({marginLeft: "0px"}).removeClass("active");
   				$(".myImgs").append($active);   				
   			});
    		$next.animate({opacity: "1"},800, "easeOutQuad").addClass("active");
    			
    	} else {     		
    		$next = $('.imgGal img:last');   	
    		var $nextW = $next.attr("width");
    		
    		$next.remove(); 
    		$(".myImgs").prepend($next);
    		
    		$next.css({marginLeft: "-"+$nextW+"px"}).animate({marginLeft: "0",opacity: "1"},600, "easeOutQuad", function() {
    			$next.addClass("active");	
    		});
    		
   			$active.animate({opacity: "0.2"},600, "easeOutQuad").removeClass("active");
    	}    
    	             
		window.setTimeout(function() {
			$("body").removeClass("imaging");
		}, 600);  
    	
		  
	}
}

// tracking
function trackPiwik(url,title) {
	window.setTimeout(function() { 
		try {	   
		    piwikTracker.setCustomUrl(url);	   
		    piwikTracker.setDocumentTitle(title);	   
		    piwikTracker.trackPageView();	   
		    piwikTracker.enableLinkTracking();	   		
		}	catch(err) {	   
		    //Piwik funktioniert nicht	   
		}
	}, 1200);
}	
