var currentPage = -1;
var moved = false;
var pages = new Array();

//fix for mobile devices
//if(navigator.userAgent.toLowerCase().match(/(iphone|ipod|ipad)/) != null){
// $('body').css({
//    width: $(window).width()+'px',
//    overflow: 'hidden'
//  });
//}


$('document').ready(function(){
  $('#contact_button').click(function(){
    $('#contact_form').animate({width: 'toggle'});
  });

  $( "#slidable_menu" ).draggable({
    axis: 'x',
    // grid: [238, 0],
    start: menuDragStart,
    stop: menuDragStop,
    scroll: true
  });

  $('#slidable_menu li').click(function(evt){
    if(!moved){
      moved = true;
      loadPage($(evt.currentTarget).index());
    }
    moved = false;
  });
  $('#slidable_menu').css({
    left: '150px'
  });
  if(window.location.hash.split('/')[0].replace('#', '') != ''){
    loadPage(window.location.hash.split('/')[0].replace('#', ''));
  }else{
    loadPage(1);
  }
});

function getCurrentMenuPosition(){
  return Math.round((($('#slidable_menu').position().left-428)*-1)/238);
}

function menuDragStart(){
  moved = true;
  showSelector();
}

function menuDragStop(){
  loadPage(getCurrentMenuPosition());
}

function showSelector(){
  $('#menu_selector').css('filter', 'alpha(opacity=20)');
  $('#menu_selector').fadeIn();
}

function hideSelector(){
  $('#menu_selector').fadeOut();
}

function animateBarToPosition(index){
  var move = 150 - ((index-1) * 238);
  showSelector();
  $('#slidable_menu').animate({
    left: move+'px'
  }, 500, function(){
    window.setTimeout(hideSelector, 1500);
    moved = false;
  });
}

var animmationInProgress = false;
function loadPage(index){
  if(index >= $("#slidable_menu li" ).length){
    index = $("#slidable_menu li" ).length -1;
  }else if(index < 0){
    index = 0;
  }
  animateBarToPosition(index);
  if(currentPage == index) return;
  if(index < 0) index = 0;
  
  var url = $($( "#slidable_menu li" ).get(index)).attr('ref');
  window.location = '#'+index+'/' + url;
  pages[currentPage] = $('#main_container').html();

  if((index > currentPage)){
    annimateRight(index);
  }else{
    annimateLeft(index);
  }
  currentPage = index;
}

function createTempOverlay(){
  var overlay = $('<div id="tempSlider" class="main_container"></div>');
  overlay.html($('#main_container').html());
  overlay.css({
    top: ($('#main_container').offset().top) + 'px',
    left: $('#main_container').offset().left+ 'px',
    position: 'absolute'
  });
  $('body').append(overlay);
  return overlay;
}

function annimateRight(index){
  if(!animmationInProgress){
    var overlay = createTempOverlay();
  }

  $('#main_container').html('<center><h1 style="padding-top:20px;">Loading...</h1></center>');
  if(pages[index] == undefined){
    $('#main_container').load($($( "#slidable_menu li" ).get(index)).attr('ref'));
  }else{
    $('#main_container').html(pages[index]);
  }

  if(animmationInProgress) return;
  animmationInProgress = true;
  var width = ($(window).width()/2)+1500;
  overlay.animate({
    left: '-'+width+'px'
  },2000, function(){
    $('#tempSlider').remove();
  });
  $('#main_container').animate({
    left: width+'px'
  }, 0).animate({
    left: '0px'
  }, 1000, function(){
    animmationInProgress = false;
  });
}

function annimateLeft(index){
  if(!animmationInProgress){
    var overlay = createTempOverlay();
  }
  $('#main_container').html('<center><h1 style="padding-top:20px;">Loading...</h1></center>');
  if(pages[index] == undefined){
    $('#main_container').load($($( "#slidable_menu li" ).get(index)).attr('ref'));
  }else{
    $('#main_container').html(pages[index]);
  }
  if(animmationInProgress) return;
  animmationInProgress = true;
  var width = ($(window).width()/2)+1500;
  overlay.animate({
    left: width+'px'
  },2000, function(){
    $('#tempSlider').remove();
  });
  $('#main_container').animate({
    left: '-'+width+'px'
  }, 0).animate({
    left: '0px'
  }, 1000, function(){
    animmationInProgress = false;
  });
}

var tweets  = new Array();
var currentTweet = 0;
function getTweets(){
  $.ajax({
    url: 'https://twitter.com/statuses/user_timeline/benjaminnimmo.json',
    dataType: 'jsonp',
    success: function(data){
      tweets = data;
      $('#tweets_inner').html('');
      currentTweet = 0;
      showTweet(false);
    },
    error: function(jqXHR, textStatus, errorThrown){
      $('#tweets_inner').html('Error gettting information from twitter');
    }
  })
}

function showTweet(even){
  var oddEven = even ? 'even' : 'odd';
  var tweet = tweets[currentTweet];
  var text = tweet.text.replace(/(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/, '<a target="blank" href="$&">$&</a>');
  var tweetDiv = $('<div class="tweet '+oddEven+'" style="display:none;"><img src="'+tweet.user.profile_image_url+'" />'+text+'</div>');
  $('#tweets_inner').append(tweetDiv);
  tweetDiv.fadeIn(1000);
  if(currentTweet+1 < tweets.length){
    currentTweet++;
    setTimeout(function(){showTweet(!even)}, 500);
  }
}

function getFriends(){
  $.ajax({
    url: 'http://api.twitter.com/1/friends/ids.json?screen_name=benjaminnimmo',
    dataType: 'jsonp',
    success: function(friends){
      $('#friendsList').html('');
      for(var i in friends){
        var friend = friends[i];
        $('#friendsList').append('<a href="twitter/twitterRedirect.php?id='+friend+'" target="_blank"><img src="http://api.twitter.com/1/users/profile_image/'+friend+'.json" alt="twitter friend"/><a/>');
      }
    },
    error: function(jqXHR, textStatus, errorThrown){
      $('#followersList').html('Error gettting information from twitter');
    }
  });
}

function getFollowers(){
  $.ajax({
    url: 'http://api.twitter.com/1/followers/ids.json?screen_name=benjaminnimmo',
    dataType: 'jsonp',
    success: function(followers){
      
      $('#followersList').html('');
      for(var i in followers){
        var follower = followers[i];
        $('#followersList').append('<a href="twitter/twitterRedirect.php?id='+follower+'" target="_blank"><img src="http://api.twitter.com/1/users/profile_image/'+follower+'.json" alt="twitter follwer"/></a>');
      }
    },
    error: function(jqXHR, textStatus, errorThrown){
      console.log('here');
      $('#followersList').html('Error gettting information from twitter');
    }
  });
}

var on = false;
contact_box_width = 440;
function toggleContact(){
  if(on == true){
    $('#contact_form').animate({
      left:'-='+contact_box_width
    },2000);
    on = !on;
  }else{
    $('#contact_form').animate({
      left:'+='+contact_box_width
    },2000);
    on = !on;
  }
}

function contactFormSubmit(){
  var name = $('#contact_name').val();
  var email = $('#contact_email').val();
  var message = $('#contact_message').val();

  $('#contact_form_containter').html("<h2>Please wait for a couple of moments while we send your message</h2>");
  var dataString = 'name='+ name + '&email=' + email + '&message=' + message;
  $.ajax({
    type: "POST",
    url: "email.php",
    data: dataString,
    success: function() {
      $('#contact_form_containter').html("<h2>Thank you for you message we will get back to you as soon as we can.</h2>");
      window.setTimeout(toggleContact, 5000);
    },
    error: function( objAJAXRequest, strError ){
      $('#contact_form_containter').html("<h2>Oops it seems something has gone wrong!<br/>Please try emailing us at ben@nimmonet.co.uk</h2>");
    }
  });
}

var contactShown = false;
function toggleContactInfo(){
  if(contactShown){
    $('#top_menu').animate({
      top:'-='+50
    },1000);
  }else{
    $('#top_menu').animate({
      top:'+='+50
    },1000);
  }
  contactShown = !contactShown;
}
