$(document).ready(function(){
    content_position();
// Animate the Timeline Bar to move left and right on previous and next
	var total_projects = $(".tl_link").length;
    var width = parseInt($('.tl_link').outerWidth()) + 1;
    var total_length = total_projects * width
	var initial_viewable_projects=28;
    var hidden_length = total_length - $("#timeline_housing").css('width', initial_viewable_projects * width).width()
    
/*    if($('section.page[id^=content]').length > 0){
        $('a#link-project-'+current_project).addClass('current_project')
        
            var gap = Math.round(($('.current_project').position().left - $('#timeline_housing').width() * .5)/width)*width
            console.log(gap)
            $('#timeline').animate({ left:"-="+gap+"px"}, 400)
        }
	}*/

    var disable_forward = function() {
		$(".forward img").fadeOut(200);
	}
	var disable_back = function() {
		$(".back img").fadeOut(200);
	}

    $('.back img').hide()

    $('.back img').click(function() {
        left = Math.round(parseInt($('#timeline').css('left'))/width)*width + width * 4
        var shift = width * 4
        $('#timeline').animate({ left:"+="+shift+"px"}, 400, function(){
            $(".forward img").fadeIn(400, function(){ $(this).removeAttr('filter') });
            if(parseInt($('#timeline').css('left')) * -1 <= 0){
                disable_back()
                $(this).animate({'left':0}, 200)
            }
        });
    });
    
    $('.forward img').click(function() {
        left = Math.round(parseInt($('#timeline').css('left'))/width)*width - width * 4
        var shift = width * 4
        if(Math.abs(left)> hidden_length){
            shift = hidden_length + left
            shift = -1 * shift
        }

        $('#timeline').animate({ left:"-="+shift+"px"}, 400, function(){
            $('.back img').fadeIn(400, function(){ $(this).removeAttr('filter') })
            if(parseInt($('#timeline').css('left')) * -1 >= hidden_length){
                disable_forward()
                $(this).animate({'left':hidden_length * -1 + 'px'}, 200)
            }
        });
    }); 
        
//Scroll To. Eases the scroll.   
    $('#more_button').click(function(){
        //  $("#project").offset().top
        $('html, body').animate({scrollTop: $("#project").offset().top + "px"}, 500);
        return false
    });
    //Scrolls back to top of page
    $('#back_to_top').tipTip({edgeOffset:22, delay:100});
    $('#back_to_top').click(function(){
        $('html, body').animate({scrollTop: 0}, 500);
        return false
    });

// Hides the tour form when hide button is clicked
    $('#collapse_tour_form').click(function(){
        $('#tour_form form').slideToggle(500);
        return false
    });



// Select all textboxes and assign them to an array


    var sweet_forms = function(form){
        var textboxes = form.find('.input-text')
        textboxes.each(function(){
            var input = $(this)
            var label = input.prev()
            // TimedObserver to check for autocomplete	
            if(input.val()){
                label.addClass('has_text')
            }
            input.focus(function(){
                label.addClass('focus')

            })
            input.blur(function(){
                label.removeClass('focus')
                if(!$(this).val()){
                    label.removeClass('has_text') 
                }
            })
            input.keydown(function(){
                label.addClass('has_text') 
            })
        })
        var selections = $('#membership_selection fieldset')
        selections.change(function(){
            $('ul#benefits li').removeClass('selected')
            var checked = $(this).find('input:checked') 
            for (var i in selections.children().length){
                if(checked.is("[value='"+i+"']")){
                    $('ul#benefits li').addClass('selected')
                }
            }
        });


        $('input.next').click(function(){
            $('section.membership').animate(
                {'margin-left': "-970px"},
                {
                    duration: 700,    
                    specialEasing: "easeInQuart",
                    complete:function(){
                        $(this).fadeOut('fast',function(){
                            $(this).remove()
                        })
                }}
            )
            $("#payment").delay(100).fadeIn('fast', function(){ $(this).removeAttr('filter') })
            return false
        })
        $('input.verify').click(function(){
            $('#payment').animate(
                {'margin-left': "-970px"},
                {
                    duration: 700,     
                    specialEasing: "easeInQuart",
                    complete:function(){
                        $(this).fadeOut('fast',function(){
                            $(this).remove()
                        })
                    }
                }
            )
            $("#welcome").delay(200).fadeIn()
            return false
        })

    }
    if($(".fancy_form").length > 0){
        sweet_forms($(".fancy_form"))
    }

//makes Elipses into links
        $('.body_text').each(function(){
            var project_link = $(this).find('.view').attr('href');
            var new_text = $(this).html().replace('...', '<a href="'+project_link+'">…</a>');
            $(this).html(new_text);
        });

//Uses TipTip
        $('#social-links li a').tipTip({edgeOffset:22, delay:100});
        $('a.project_list_link').tipTip({edgeOffset:22, delay:100});
        
//Toggles events in ProjectList         Decided to delete this feature
/*        $('#toggle-events').click(function(){
            $('#body_projects.list section li.timeline_event').slideToggle(1500, 'easeInQuart');
            return false
        })
*/
//Positions content relative to bottom of window
    function content_position(){
            var win_height = $(window).height()
            switch($('body').attr('id')){
                case 'body_home':
                    win_height = (win_height*.52)
                    break
                case 'body_events':
                    win_height = win_height * .10
                    break
                case 'body_contact':
                    win_height = (win_height*.10)
                    break;
                case 'body_tours':
                    win_height = (win_height*.10)
                    break
                case 'body_membership':
                    win_height = (win_height*.10)
                    break
                case 'body_':
                    win_height = win_height * .10
                    break
                default:
                    win_height = (win_height*.40)
            }
            $('.detail div#content').css({
                'margin-top':win_height
            });
        };

    $(window).resize(content_position)   

// PROJECTS_LIST page slideshows
/*function slideshow(){
    $('figure .view').hide();
    $('figure .count-1').show();
}
function ss-next(){
    
}
function ss-prev(){
    
}
slideshow();
*/



function generateNoise(opacity) {
   if ( !!!document.createElement('canvas').getContext ) {
      return false;
   }

   var canvas = document.createElement("canvas"),
   ctx = canvas.getContext('2d'),
   x, y,
   r, g, b,
   opacity = opacity || .2;

   canvas.width = 100;
   canvas.height = 100;

   for ( x = 0; x < canvas.width; x++ ) {
      for ( y = 0; y < canvas.height; y++ ) {
         r = g = b = Math.floor( Math.random() * 75 );

         ctx.fillStyle = "rgba(" + r + "," + g + "," + b + "," + opacity + ")";
         ctx.fillRect(x, y, 1, 1);
      }
   }
    $('body:not(#body_home)').css({
        'background-color': "rgba(0,0,0, .93)",
        'background-image': "url(" + canvas.toDataURL("image/png")+ ")",
        'background-size': "initial",
        '-moz-background-size': "100px 100px",
        'background-repeat':"repeat"
    
    })
}

if($('body').css('background-image') == 'none'){
    generateNoise(.08); // default opacity is .2
}

//
//Contact Form
//
if(("#body_contact").length>0){    
    $('.fancy_form').submit(function(){
        //if(validateEmail($(this).find('[name="email"]').val()) || $('textarea').val()!=''){
            $('.fancy_button').addClass('submitting').attr('disabled', true);
            $.ajax({
                type: 'POST',
                url: $(this).attr('action'),
                data: $(this).serialize(),
                success: function(data){
                    $('.fancy_button').removeClass('submitting').removeAttr('disabled');
                    $('.fancy_form').fadeOut(400, function(){
                        $(this).remove();
                        $('section.column.colx8').append('<h4 id="thankyou">Thank you for contacting us. <br/> We will reply to you later.</h4>')
                        $("#thankyou").delay(500).animate({
                                'margin-top': '120px',
                                'opacity':1,
                            }, 2000);
                    
                    });
                },
                error: function(data){
                    $('.fancy_button').removeClass('submitting').removeAttr('disabled');
                    var error_array = $.parseJSON(data.responseText).errors
                    for(var i = 0; i<error_array.length; i++){
                        $('label[for='+error_array[i][0]+']').removeClass('has_text').addClass('not_valid');
                        $('[name='+error_array[i][0]+']').val('')
                    }
                }
                });
        //}else{
            //$("label[for=email] span").css({'color': 'rgba(255, 0, 0, .3)'}).text("Please fill out valid email address.");
            
        //}
        return false;
    })
}
//MEMBERBENIFITS

$('.level1').mouseenter(function(){
    $('#level1').addClass('selected');
    }).mouseleave(function(){
    $('#level1').removeClass('selected');
    });

$('.level2').mouseenter(function(){
    $('#level1,#level2').addClass('selected');
    }).mouseleave(function(){
    $('#level1,#level2,#level3').removeClass('selected');
    });

$('.level3').mouseenter(function(){
    $('#level1,#level2,#level3').addClass('selected');
    }).mouseleave(function(){
    $('#level1,#level2,#level3').removeClass('selected');
    });
    
$('.level4').mouseenter(function(){
    $('#level1,#level2,#level3,#level4').addClass('selected');
    }).mouseleave(function(){
    $('#level1,#level2,#level3,#level4').removeClass('selected');
    });
    
//MAILINGLIST

function say_thankyou(){
$('#subForm input, #subForm span').hide();
$('#subForm').prepend('<h2 id="thankyou"><strong>Thank you</strong><br/>for subscribing!</h2>');
}

var is_subscribed = window.location.href.match(/subscribe/)
if(is_subscribed){
say_thankyou();
console.log('stf')
}

function click_membership(){
    $('fieldset label').click(function(){
        $('.fancy_button').trigger('click');
    });   
}

if($('#body_membership').length > 0){
    click_membership();
}

//If project is only one year.. it doesn't show second year.
//Not working yet... hm... put on backburner


function check_duplicates(){
    $('.dates').each(function(){
    var start = $(this+' .start-year').text().replace(/[\s\-]*/g,'');
    console.log('start'+start);
    var end = $(this+' .end-year').text().replace(/[\s\-]*/g,'');
    console.log('end'+end)
    if(start == end){
        $(this+'.end-year').css({
            'display' : 0
        });
        };
    });
};

check_duplicates();

$('.follow_us').click(function(){
      $('.social_nav').css({
        'opacity' : 1,
        'display' : 'inherit'
        });
    return false    
});

$('.social_nav').mouseleave(function(){
        $('.social_nav').css({
            'opacity':0,
            'display':'none'
        });
});

//Pulls JSON of TUMBLR FEED
if($("#body_home").length){
  $.getJSON("http://blog.miessociety.org/api/read/json?callback=?", 
    function(data) {
        var length = 3,
            count = 0,
            list = $('#body_home #blog h3').after('<ul class="blog-posts" />').parent().find('ul');
        $.each(data.posts, function(i,post){ 
          if(count < length){
            if( post['type'] == 'regular'){
                list.append('<li><a href="'+post["url-with-slug"]+'" title="posted on '+post['date']+'">'+post['regular-title']+'</a></li>');
                count++;
            }
          }
      });
    }); 
}

$.get('/?footer=links', function(dom){
  if(dom != 'nope'){
    $("#otherLinks").find('ul').empty().append(dom);
  }
});




}); // ends jQuery ready function




