var LP = LP || {
    settings:{
        current : [],
        basePath : "http://pillmann.com/"
    },
    cache:{},
    imgCache : [],
};

$(function(){
    LP.cache.current = [];
    LP.init();
	
    //VideoJS.setupAllWhenReady();

    $(window).hashchange( function(){
        // Alerts every time the hash changes!
        LP.parseHash();
    })
    $(window).hashchange();
    $(window).resize(function() {
        LP.redraw();
    });
    $('#fullscreen-navi .prev').click(function(event){
        event.preventDefault();
        LP.navigate("left");
    });
    $('#fullscreen-navi .next').click(function(event){
        event.preventDefault();
        LP.navigate("right");
    });
    $('#fullscreen-navi .close').click(function(event){
        event.preventDefault();
        LP.closeFullscreen();
    });
    $('#fullscreen-navi .menu').click(function(event){
        event.preventDefault();
        LP.showMenu();
    });
    $('#fullscreen-navi .menu').mouseover(function(event){
        event.preventDefault();
        LP.showMenu();
    });
    $('#fullscreen-navi .menu').mouseout(function(event){
        event.preventDefault();
        LP.cache.menuTimeout = setTimeout(function(){
            LP.hideMenu();
        }, 5000);
    });
	
    $('#video-navi .close').click(function(event){
        event.preventDefault();
        LP.closeVideo();
    });
    $('#video-navi .menu').click(function(event){
        event.preventDefault();
        LP.showMenu();
    });
    $('#video-navi .menu').mouseover(function(event){
        event.preventDefault();
        LP.showMenu();
    });
    $('#video-navi .menu').mouseout(function(event){
        event.preventDefault();
        LP.cache.menuTimeout = setTimeout(function(){
            LP.hideMenu();
        }, 5000);
    });
    $(LP.cache.fullscreen).mousemove(function(e){
        LP.mousePosition(e.pageX);
        //$('#status').html( +', '+ e.pageY);
    });
	
    $("#sendMail").click(function(event) {
        event.preventDefault();
        LP.sendMail();
    });
});

LP.sendMail = function(){
    var email = $("input#email").val();
    if(email != '' && LP.IsValidEmail(email)){
        var dataString = 'email=' + email;
        //console.log(dataString);return false;
        $('.email-error').hide();
        $.ajax({
            type: "POST",
            url: "assets/bin/process.php",
            data: dataString,
            success: function() {
                $('#contact_form').html("<p id='message'></p>");
                $('#message').html("<span>Contact Form Submitted!</span>")
                .hide()
                .fadeIn(1500);
            }
        });
    }else{
        $('.email-error').show();
    }
	
    return false;
}

LP.IsValidEmail = function(email){
    var filter = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
    return filter.test(email);
}



LP.init = function(){
    $('#navigation-inner').append('<ul id="menu"></ul>')
    $('.folder:not([title="Intro"])').each(function(){
        _this = this;
        if( $(this).attr("images") != undefined ){
            link = $('<li title="'+$(this).attr('title')+'"><a href="#/Gallery/'+$(this).attr('title')+'">'+$(this).attr('title')+'</a></li>').appendTo('#menu');
            LP.parseFolder($(this));
        }
    });
    $('<li title="contact & info"><a href="#/Static/Contact">Contact & Info</a></li>').appendTo('#menu');
	
    LP.cache.folders = $('.folder');
    LP.cache.static = $('#about');
    LP.cache.fullscreen = $('#fullscreen');
    LP.cache.videoBox = $(".video-js-box");
}

LP.parseHash = function(){
    temp = decodeURIComponent((location.hash).replace(/\+/g, '%20'));
    LP.hash = temp.split("/");
    $("#container p.loading").hide();
    if(LP.hash[1] == "Intro"){
        LP.showIntro();
    } else if(LP.hash.length > 2){
        if(LP.cache.current == LP.hash){
            return;
        }else if(LP.hash[1] == "Static"){
            LP.showStatic();
        }else if(LP.hash[1] == "Gallery"){
            LP.showGallery();
        }
    }else{
        window.location = "#/Intro";
    }
    LP.cache.current = LP.hash;
}

LP.parseFolder = function(folder){
    images = $('span.image', $(folder));
    _this = folder;
    if(folder.attr("title") == "Film"){
        $('span.image', $(folder)).each(function(i){
            //console.log(c % 12);
            $(this).wrap('<a href="#/Gallery/'+$(folder).attr('title')+'/Video_'+(i+1)+'" title="Video_'+(i+1)+'" />');
        });
    }else{
        $('span.image', $(folder)).each(function(i){
            //console.log(c % 12);
            $(this).wrap('<a href="#/Gallery/'+$(folder).attr('title')+'/Image_'+(i+1)+'" title="Image_'+(i+1)+'" />');
        });
    }
    $('a', $(folder)).each(function(){
        $(this).mouseover(function(){
            $(this).find('span.image-title').stop().show();
        });
        $(this).mouseout(function(){
            $(this).find('span.image-title').stop().hide();
        });
    });
}

LP.showIntro = function(){
    LP.cache.static.fadeOut();
    LP.cache.folders.fadeOut();
    $("#navigation").css("bottom", "-55px");
    $("#menu").hide();
    var folder = LP.cache.folders.filter('[title="'+LP.hash[1]+'"]');
    //select random
    var rand = Math.floor(Math.random() * parseInt(folder.attr("images")))
    var img = folder.find('span:eq('+rand+')');
    //show random pseudo fullscreen
    if(LP.cache.fullscreen.hasClass("open") == false){
        LP.cache.fullscreen.addClass("open");
    }
    //LP.cache.fullscreen.find("p.loading").show();
    $.loadImages(img.attr("full"), function(){
        //animate out new news element
        //LP.cache.fullscreen.find("p.loading").hide();
        if(LP.cache.fullscreen.find(".fullscreen").length >= 1){
            var old = LP.cache.fullscreen.find(".fullscreen");
            $(old).fadeOut(1000, function(){
                LP.releaseImg($(this).find("img"));
                $(this).remove();
            });
        }
        //animate in new news element
        LP.cache.fullscreen.find("#fullscreen-navi").hide();
        var newEl = $('<div class="fullscreen intro"><img src="'+img.attr("full")+'" ></div>');
        LP.cache.fullscreen.prepend(newEl);
        LP.redraw();
        $(newEl).hide().fadeIn(1000);	
    });
    //hide menu
    setTimeout(function(){
        LP.showMenu();
    }, 1000);
}

LP.showGallery = function(){
    LP.cache.static.fadeOut();
    var folder = LP.cache.folders.filter('[title="'+LP.hash[2]+'"]');
	
    $('#menu li').removeClass("active");
    $('li[title="'+LP.hash[2]+'"]').addClass("active");
	
    var gal = '';
    if(LP.cache.current.length > 2){
        gal = LP.cache.current[2]
    }
	
    if(gal == LP.hash[2]){
        LP.cache.folders.filter(':not([title="'+LP.hash[2]+'"])').hide();
        folder.show();
    }else{
        LP.cache.folders.filter(':not([title="'+LP.hash[2]+'"])').fadeOut();
        folder.fadeIn();
        for(n=0;n<LP.imgCache.length;n++){
            LP.releaseImg($(LP.imgCache[n]));
        }
        LP.animateInPage(folder);
    }
	
    image = -1;
    for(i=0;i<LP.hash.length; i++){
        if(LP.hash[i].indexOf('Image') != -1) image = i;
    }
    if(image != -1){
        LP.showFullscreen(folder, 3);	
    }else{
        LP.closeFullscreen();
    }
	
    video = -1;
    for(i=0;i<LP.hash.length; i++){
        if(LP.hash[i].indexOf('Video') != -1) video = i;
    }
    if(video != -1){
        LP.showVideo(folder, 3);	
    }else{
        LP.closeVideo();
    }
}

LP.animateInPage = function(folder){
    var spans = folder.find("span.image");
    for(k=0;k<spans.length;k++){
        $(spans[k]).append('<img src="'+$(spans[k]).attr("src")+'" />');			
        $(spans[k]).hide().delay(k*100).fadeIn();
    }
    LP.imgCache = spans.find("img");
	
    setTimeout(function() {
        myScroll.refresh();
    }, (spans.length*150));
}

LP.releaseImg = function(img){
    img.detach();
    img.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
    setTimeout(function() {
        img = null;
    }, 5000);
}

LP.showFullscreen = function(folder, seg){
    if(LP.cache.fullscreen.hasClass("open") == false){
        LP.cache.fullscreen.addClass("open");
        LP.cache.fullscreen.find("#fullscreen-navi").show();
    }
    LP.cache.fullscreen.find("p.loading").show();
    var img = folder.find('a[title="'+LP.hash[seg]+'"] span');
    $.loadImages(img.attr("full"), function(){
        //animate out new news element
        LP.cache.fullscreen.find("p.loading").hide();
        if(LP.cache.fullscreen.find(".fullscreen").length >= 1){
            var old = LP.cache.fullscreen.find(".fullscreen");
            $(old).fadeOut(500, function(){
                LP.releaseImg($(this).find("img"));
                $(this).remove();
            });
        }
        LP.hideMenu();
        //animate in new news element
        var newEl = $('<div class="fullscreen"><img src="'+img.attr("full")+'" ></div>');
        LP.cache.fullscreen.prepend(newEl);
        LP.redraw();
        $(newEl).hide().fadeIn(500);
    });
}

LP.closeFullscreen = function(){
    if(LP.cache.fullscreen.hasClass("open") == false){
        return;
    }
    if(LP.cache.fullscreen.find(".fullscreen").length >= 1){
        var old = LP.cache.fullscreen.find(".fullscreen");
        $(old).fadeOut(1000, function(){
            LP.releaseImg($(this).find("img"));
            $(this).remove();
            LP.cache.fullscreen.removeClass("open");
            LP.showMenu();
        });
    }
    clearTimeout(LP.cache.menuTimeout);
    if(LP.cache.current.length > 2){
        if(LP.cache.current == LP.hash){
            window.location = LP.cache.current[0]+'/'+LP.cache.current[1]+'/'+LP.cache.current[2];
        }
    }
}

LP.createVideo = function(node){
    /*var vid = node.attr("full").slice(0, -3) + "m4v";
	var videoString = '<!-- Begin VideoJS --> ' +
	'<div id="video-js-box"> ' +
  		'<div class="video-js-box">' +
    		'<video class="video-js" width="'+node.attr("full_width")+'" height="'+node.attr("full_height")+'" controls preload poster="'+node.attr("full")+'">' +
      			'<source src="'+vid+'" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />' +
      			'<object class="vjs-flash-fallback" width="'+node.attr("full_width")+'" height="'+node.attr("full_height")+'" type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf">' +
        			'<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />' +
        			'<param name="allowfullscreen" value="true" />' +
        			'<param name="flashvars" value=\'config={"playlist":["'+LP.settings.basePath+'/'+node.attr("full")+'", {"url": "'+LP.settings.basePath+'/'+vid+'","autoPlay":false,"autoBuffering":true}]}\' />' +
        			'<img src="'+node.attr("full")+'" alt="Poster Image" title="No video playback capabilities." />' +
      			'</object>' +
    		'</video>' +
  		'</div>' +
	'</div>' +
  	'<!-- End VideoJS -->"';
     */
    LP.cache.VideoBaseWidth = node.attr("full_width");
    LP.cache.VideoBaseHeight = node.attr("full_height");
    var videoString = '<iframe src="'+node.attr("full")+'" id="" name="" height="'+node.attr("full_height")+'" width="'+node.attr("full_width")+'" frameborder="0" marginwidth="0" marginheight="0" ></iframe>';
    
    return videoString;
}

LP.showVideo = function(folder, seg){
    if($("#video-container").hasClass("open") == false){
        $("#video-container").addClass("open");
    }
    //LP.cache.fullscreen.find("p.loading").show();
    var img = folder.find('a[title="'+LP.hash[seg]+'"] span');
    $("#video-container").append($(LP.createVideo(img)));
	
    //VideoJS.DOMReady(function(){
    //    LP.cache.myPlayer = VideoJS.setup($("#video-container").find(".video-js"));
    //});
    LP.hideMenu();
    LP.redraw();
}

LP.closeVideo = function(){
    if($("#video-container").hasClass("open") == false){
        return;
    }
    $("#video-container").removeClass("open");
    $("#video-container iframe").remove();
	
    clearTimeout(LP.cache.menuTimeout);
    LP.showMenu();
    if(LP.cache.current.length > 2){
        if(LP.cache.current == LP.hash){
            window.location = LP.cache.current[0]+'/'+LP.cache.current[1]+'/'+LP.cache.current[2];
        }
    }
}

LP.hideMenu = function(){
    $("#menu").fadeOut(400, function(){
        $("#navigation").animate({
            bottom : -55
        }, 400);
    });
}

LP.showMenu = function(){
    $("#navigation").animate({
        bottom : 0
    }, 400, function(){
        $("#menu").fadeIn();
    });
}

LP.showStatic = function(){
    LP.closeFullscreen();
    LP.closeVideo();
    LP.cache.folders.fadeOut();
    LP.cache.static.fadeIn();
    LP.redraw();
}

LP.redraw = function(){
    LP.cache.h = $(window).height();
    LP.cache.w = $(window).width();
	
    LP.cache.static.css("height", LP.cache.h-60+"px");
    LP.cache.static.css("width", LP.cache.w-30+"px");
    $("#video-container").css("height", LP.cache.h-30+"px");
    $("#video-container").css("width", LP.cache.w-30+"px");
	
    if(LP.cache.fullscreen.find(".fullscreen").length > 0){
        LP.cache.fullscreen.find(".fullscreen").css("height", LP.cache.h-30+"px");
        LP.cache.fullscreen.find(".fullscreen").css("width", LP.cache.w-30+"px");
        var imgW = LP.cache.fullscreen.find(".fullscreen img").width();	
        var imgH = LP.cache.fullscreen.find(".fullscreen img").height();	
        if(LP.cache.fullscreen.find(".intro").length > 0){
            if(imgW > LP.cache.w){
                LP.cache.fullscreen.find(".fullscreen img").css("height", "100%");
                LP.cache.fullscreen.find(".fullscreen img").css("width", "auto");
            }else{
                LP.cache.fullscreen.find(".fullscreen img").css("width", "100%");
                LP.cache.fullscreen.find(".fullscreen img").css("height", "auto");
            }
        }else{
            if(imgW > LP.cache.w){
                LP.cache.fullscreen.find(".fullscreen img").css("width", "100%");
                LP.cache.fullscreen.find(".fullscreen img").css("height", "auto");
            }else{
                LP.cache.fullscreen.find(".fullscreen img").css("height", "100%");
                LP.cache.fullscreen.find(".fullscreen img").css("width", "auto");
            }
        }
    }
	
	
    if($("#video-container iframe").length > 0){
        var vb = $("#video-container").find("iframe");
        
        console.log(vb);
        if(LP.cache.VideoBaseHeight > $("#video-container").height()){
            vb.height($("#video-container").height());
            vb.width(LP.cache.VideoBaseWidth * $("#video-container").height() / LP.cache.VideoBaseHeight);
            vb.css({marginTop:0});
        }else{
            vb.height(LP.cache.VideoBaseHeight);
            vb.width(LP.cache.VideoBaseWidth);
            vb.css({marginTop: (LP.cache.h - LP.cache.VideoBaseHeight - 30)/2 +"px"});
        }
        
        if(LP.cache.VideoBaseWidth > $("#video-container").width()){
            vb.width($("#video-container").width());
            vb.height(LP.cache.VideoBaseHeight * $("#video-container").width() / LP.cache.VideoBaseWidth);
            vb.css({marginTop: (LP.cache.h - vb.height() - 30)/2 +"px"});
        }
        
        
            //marginLeft: (LP.cache.w - LP.cache.VideoBaseWidth - 30)/2 +"px",
            
            //width: LP.cache.VideoBaseWidth+"px"
        
    }
}

LP.mousePosition = function(pageX){
    var half = LP.cache.w / 2;
    var side = '';
    var old = '';
    (half < pageX) ? side = "left" : side = "right";
    if(old != side){
        if(side == "left"){
            $('#fullscreen-navi .prev').fadeOut();
            $('#fullscreen-navi .next').fadeIn();
        }else{
            $('#fullscreen-navi .prev').fadeIn();
            $('#fullscreen-navi .next').fadeOut();
        }
    }
    old = side;
}

LP.navigate = function(dir){
    var flg = $('div[title="'+LP.cache.current[2]+'"] span').length;
    image = -1;
    for(i=0;i<LP.cache.current.length; i++){
        if(LP.cache.current[i].indexOf('Image') != -1) image = i;
    }
    if(image != -1){
        //we are in fullscreen mode
        var im = LP.cache.current[image].split("_");
        if(dir == "right"){
            parseInt(im[1]) >= flg ? im[1] = 1 : im[1] = parseInt(im[1])+1;
        }else{
            parseInt(im[1]) == 1 ? im[1] = flg : im[1] = parseInt(im[1])-1;
        }
        LP.cache.current[image] = im[0]+'_'+im[1];
        window.location = LP.cache.current[0]+'/'+LP.cache.current[1]+'/'+LP.cache.current[2]+'/'+LP.cache.current[3];
    }
}
