var siteRoot = null;
var urls = {};
var teachers = [];
var lastWasHidden = false;
var maxTeachersToShow = 6;
function NavigateTo(title)
{
 window.location= urls[title];
}

function pop(view)
{
 closePopup();
 var tmpContainer = $('<div></div>');
 $.ajax(
  {
   url: siteRoot + "/Home/ShowMore.rails",
   type: 'GET',
   data: {viewName: view},
   success: 
    function(data)
    {
      $('#container').after(data); 
    }
  });
}

function closePopup()
{
 $('.pop_over_bg').remove();
 $('.home_pop_up').remove();
}

function closeProfile()
{
 $('.pop_over_bg').remove();
 $('.pop_over_profile').remove();
}

function popProfile(id)
{
   var isfirst = id == teachers[0];
   $.ajax({
   url: siteRoot + "/Home/TeacherProfile.rails",
   type: 'GET',
   data: {teacher: id,isLast: isLastIntheList(id), isFirst : isfirst},
   success:
    function(data)
    {
       showProfile(data, getIndex(id));
    }
  });
}

function showProfile(data, currentIndex)
{
 closeProfile();
 var tmp = $('<div></div>').html(data);
 $(tmp).find('.current_index').val(currentIndex);
 $('#container').after($(tmp).html());
}

function getProfile(nextProfile)
{
  var index = parseInt($('.current_index').val()) + nextProfile;
  if(index < 0 || index > teachers.length) return;
  return popProfile( teachers[index]);
}

function getIndex(id)
{
 for(i = 0; i < teachers.length; i++)
 {
  if(teachers[i] != id) continue;
  return i;
 }
}

function isLastIntheList(id)
{
 return  id == teachers[teachers.length -1];
}

function teacherImageError(img, url) {
  img.src = url;
  $(img).parents("li").addClass("bad_image").hide();
  var teacherId = $(img).attr("data-teacher");
  var newLi = $(".temp_repo").find("li:not('.bad_image'):first")
  if (newLi) {
    var newTeacherId = parseInt($(newLi).find("img").attr("data-teacher"));
    $(img).parents("li").replaceWith(newLi);
    swapOldIdWithNewId(teacherId, newTeacherId);
  }
}
 
function swapOldIdWithNewId(oldId, newId) {
  $.each(teachers, function(index, id) {
    if (id == oldId) {
      teachers[index] = newId;
    }
  });
}
 
function appendTeachersWithPictures() {
  $(".temp_repo").show().hide();
  while(teachers.length < maxTeachersToShow) {
    var li = $(".temp_repo").find("li:not('bad_image'):first");
    var teacherId = parseInt($(li).find("img").attr("data-teacher"));
    var ul = $('.customer_srv_content ul');
    $(li).appendTo(ul);
    teachers.push(teacherId);
  }
 }
