// 
//  page.js
//  roskilde_app_site
//  
//  Created by Mads Hartmann Jensen on 2011-06-21.
//  Copyright 2011 Sideways Coding. All rights reserved.
// 

var MAX_WIDTH = 1920,
    IMAGES_PR_ROW = 10,
    ROW_HEIGHT = 160,
    IMAGE_WIDTH = 160;

var create_image = function(src,link){
    return $('<a href="'+link+'" target="_blank">'+
                '<div class="opaque"></div>'+
                '<div class="front"><img src="'+src+'" alt="'+link+'"/></div>'+
                '<div class="back"><img src="'+src+'" alt="'+link+'"/></div>'+
            '</a>');
};

var repeat = function(x,f){
    for (var i = 0; i <= x; i++) { f(i); }
};

var resize = function(){
    $('#images').height($(window).height() - $('#top').height()); // 36 is the padding of #top
};

var flip = function() {
    
    var max_visible  = Math.floor((($(window).height() - $('#top').height()) / ROW_HEIGHT) * IMAGES_PR_ROW),
        take_from = Math.floor(Math.random()*$('.image_container').size()),
        new_src = $('.image_container .front img').eq(take_from).attr('src'),
        new_href = $('.image_container .front img').eq(take_from).attr('alt'), 
        number = Math.ceil(Math.random()*max_visible);
            
    new_image_container = $('.image_container').eq(number);
    
    var action = function() {
        if (new_image_container.hasClass('flip')) {
            new_image_container.removeClass('flip');
        } else {
            new_image_container.addClass('flip');
        }
    };
    
    new_image_container.find('.back img').attr('src',new_src);
    new_image_container.find('a').attr('href',new_href);
    new_image_container.find('.opaque').animate({'opacity':0},500, function() {
        setTimeout(function() { action(); }, 500);
    });
    
    setTimeout(function() {
        new_image_container.find('.opaque').animate({'opacity':0.5},500);
    }, 1500);
       
    setTimeout(function() {flip();}, 3000);
};

var callback = function(data) {
    
    $(document).ready(function() {

        var $container = $('.image_container'),
            top_offset = 0, 
            left_offset = 0;

        // prepare the grid of images     
        repeat(100, function(count) {
            if (count % IMAGES_PR_ROW === 0) {
                left_offset = 0;
            } else {
                top_offset -= ROW_HEIGHT;
            }

            $container.clone().appendTo("#images").css({
                'top' : top_offset,
                'left' : left_offset
            });

            left_offset += IMAGE_WIDTH; 
        });

        // don't need the empty container anymore. 
        $container.remove();

        // resize #images so it displays all the images possible w/o giving a scrollbar 
        resize();
        $(window).bind('resize',function() {
           resize(); 
        });
        
        // add the images
        $.each($.map(data, function(item,index) {
           return create_image(item.image_url, item.link);
        }),function(index, image) {
            $('#images .empty:first').append(image).removeClass("empty");
        });

        setTimeout(function() {flip();}, 500);
        
        // adding event handlers 
        $('.opaque').hover(function() { 
            $(this).animate({'opacity':0},300);
        },
        function() {
            $(this).animate({'opacity':0.5},300);
        });
        
        $('.opaque').live('click',function() {
           $(this).parent().click();
        });

        
        var previous_size = $('#top .wrapper:first').css('height');
        
        $('#full').bind('click',function() {    
            if ($(this).hasClass('off')) {
                $('#top .wrapper:first').animate({'height':0},500,function() {
                    resize();
                });
                $(this).removeClass('off');
            } else {
                $('#top .wrapper:first').animate({'height':previous_size},500,function() {
                    resize();
                });
                $(this).addClass('off');
            }    
            return false; 
        });

        var close = function(){
            $("#overlay").fadeOut(250);
            $('#mail_box').animate({
                'top' : "-115px"
            }, 250);
        };
        
        $('#mail').bind('click',function() {
            $('#overlay').fadeIn(250);
            $('#mail_box').animate({
                'top' : 50
            },250);
            $('#email').focus();
        });
        
        $('#overlay').bind('click',function() { close(); });
        $('#close').bind('click',function() { close(); });
        
        // form submission 
        $('#submit').bind('click',function() {
            
            var validate_email_input = function(text){
                var filter = /[a-zA-Z0-9._\-]+@[a-zA-Z0-9]+.[a-z]+(.[a-z]+)?/;

                if (!filter.test(text)) {
                    return false;
                }
                return true;
            };
            
            var email_value = $('#email').val(),
                url = window.location.href + "submit.php?" + "email=" + email_value + "&name=" + email_value;   
            if (validate_email_input(email_value)) {
                jQuery.post(url);
                $('form li').slice(1,3).hide();
                $('form ul').append("<li class='thanks'>Thanks! We’ll keep you updated!</li>");
            } else {
                alert("Invalid email");
            }
            return false; 
          });

    });
};
