// SEND EMAIL WHEN REVIEW IS POSTED
FB.Event.subscribe('comment.create', function(response) {
 var posted = '';
 if( response.parentCommentID ){
  var url    = 'https://graph.facebook.com/' + response.parentCommentID + '/comments?access_token=213019372053164|2OSdvbSXNXd9NdixCZMPq5tiC0o&callback=?';
  $.getJSON(url,function(json){
   total     = json.data.length - 1;
   posted    = json.data[total].message;
   $.ajax({
    type: "POST",
    url: '/comment/' + schoolid + '.html',
    data: 'reply=' + posted
   });
  });
 } else {
  var url    = 'https://graph.facebook.com/' + response.parentCommentID + '/comments?access_token=213019372053164|2OSdvbSXNXd9NdixCZMPq5tiC0o&callback=?';
  $.getJSON(url,function(json){
   FB.api({
    method: 'fql.query', query: "SELECT object_id, fromid, text, post_fbid from comment WHERE object_id in (select comments_fbid from link_stat where url ='" + response.href  + "') order by time desc limit 1"
   }, function(response) {
    $.ajax({
     type: "POST",
     url: '/comment/' + schoolid + '.html',
     data: 'object_id=' + response[0].object_id + '&fromid=' + response[0].fromid + '&text=' + response[0].text + '&post_fbid=' + response[0].post_fbid
    });
   });
  });
 }
}); 



function fbWall(fb){
 var url = "https://graph.facebook.com/" + fb + "/feed?access_token=213019372053164|2OSdvbSXNXd9NdixCZMPq5tiC0o&limit=5&callback=?";
 $.getJSON(url,function(json){
 var html = '';

 $.each(json.data,function(i,fb){
// alert(json.data.toSource());
// alert(fb.type);
  html += '<div class="wall">';
  html += ' <img src="https://graph.facebook.com/' + fb.from.id + '/picture?type=square" align="left"/>';
  html += ' <div>';
  if (fb.type === 'photo') {
   html += ' <div class="photo"><a href="' + fb.link + '" title="' + fb.name + '" target="_blank"><div style="background-image:url(' + fb.picture + ');"></div></a></div>';
   if ( fb.caption ){
    html += ' <a href="http://www.facebook.com/profile.php?id=' + fb.from.id + '" target="_blank">' + fb.from.name + '</a> added ' + formatString(fb.caption) + ' to the album:<br/><a href="' + fb.link + '" target="_blank">' + formatString(fb.name) + '</a>';
   } else {
    html += ' <a href="http://www.facebook.com/profile.php?id=' + fb.from.id + '" target="_blank">' + fb.from.name + '</a> added a photo:<br/>' + formatString(fb.message);
   }
  } else if (fb.message) {
   html += '  <a href="http://www.facebook.com/profile.php?id=' + fb.from.id + '" target="_blank">' + fb.from.name + '</a> ' + formatString(fb.message);
  } else {
   html += '  <a href="http://www.facebook.com/profile.php?id=' + fb.from.id + '" target="_blank">' + fb.from.name + '</a> posted a ' + fb.type + ':<br/>';
   html += '  <a href="' + fb.link + '" target="_blank">' + formatString(fb.name) + '</a><br/>';
   if (fb.caption != '') { html += '<em>' + formatString(fb.caption) + '</em><br/>'; }
   if (fb.description != '') { html +=   formatString(fb.description); }
  }
  html += ' </div>';
  html += ' <div class="date"><em>' + fuzzyFacebookTime(fb.created_time.replace(/-/g,'/')) + '</em></div>';
  html += '</div>';

  if (fb.comments.data) {
   // alert(fb.comments.toSource());
   $.each(fb.comments.data,function(i,fb){
    html += '<div class="wallcomment">';
    html += ' <img src="https://graph.facebook.com/' + fb.from.id + '/picture?type=square" align="left"/>';
    html += ' <div>'
    html += '  <a href="http://www.facebook.com/profile.php?id=' + fb.from.id + '" target="_blank">' + fb.from.name + '</a> ' + formatString(fb.message);
    html += ' </div>';
    html += ' <div class="date"><em>' + fuzzyFacebookTime(fb.created_time.replace(/-/g,'/')) + '</em></div>';
    html += '</div>';
   });
  }
 });
 $('#facebookwall').animate({opacity:0}, 500, function(){
  $('#facebookwall').html(html);
 });
  $('#facebookwall').animate({opacity:1}, 500);
 });
};

function fbAlbum(fb){
 var url = "https://graph.facebook.com/" + fb + "/albums?access_token=213019372053164|2OSdvbSXNXd9NdixCZMPq5tiC0o&limit=3&callback=?";
 $.getJSON(url,function(json){
  var html = '';
  if (json.error) {
   // alert(document.location.href);
   html += 'There are currently no photos available';
  } else if (json.data != '') {
   var count = 0;
   $.each(json.data,function(i,fb){
    if( fb.name != 'Profile Pictures' ){
     html += '<div class="album">';
     html += ' <a href="' + fb.link + '" target="_blank">' + fb.name + '</a>';
     html += ' <div class="photos" id="' + fb.id + '"></div>';
     html += '</div>';
     count++;
    }
   });
   if (count == 0) {
    html += 'There are currently no photos available';
   }
  } else {
   html += 'There are currently no photos available';
  }
  $('#photos').animate({opacity:0}, 500, function(){
   $('#photos').html(html);
  });
  $('#photos').animate({opacity:1}, 500, function(){
   $('.photos').html( function(){ 
    fbPhotos($(this).attr('id'));
   });

   $(".lightbox").live("click", function(event){
    $("#overlay").css("z-index","149999");
    $("#lightbox").html('<div class="closePhoto">' + $(this).attr('title') + '</div><img src="' + $(this).attr('href') + '"/>');
    $("#lightbox").show();
    setTimeout(function(){
     $(".closePhoto").css("top", (($(window).height() - $("img", "#lightbox").height()) / 2 ) - 13 );
     $(".closePhoto").css("left", ($(window).width() - $("img", "#lightbox").width()) / 2 );
     $(".closePhoto").css("width", $("img", "#lightbox").width() - 2 );
    }, 1200);
    return false;
   });

   $("#lightbox").live("click", function(event){
    $("#overlay").css("z-index","5000");
    $("#lightbox").hide();
    $("#lightbox").html('')
    return false;
   });

  });
 });
};

function fbPhotos(id){
 var url = "https://graph.facebook.com/" + id + "/photos?access_token=213019372053164|2OSdvbSXNXd9NdixCZMPq5tiC0o&limit=4&callback=?";
 $.getJSON(url,function(json){
  var html = '';
  $.each(json.data,function(i,fb){
   var title = fb.name;
   if (title == undefined){ title = 'Photo'; }
   var photoclass = 'photo';
   if (i == 3){ photoclass = 'photo last'; }
   if( fb.images[3].width > 100 ) {
    html += ' <div class="' + photoclass + '"><a href="' + fb.source + '" title="' + title + '" class="lightbox"><div style="background-image:url(' + fb.images[3].source + ');"></div></a></div>';
   } else {
    html += ' <div class="' + photoclass + '"><a href="' + fb.source + '" title="' + title + '" class="lightbox"><div style="background-image:url(' + fb.images[2].source + ');"></div></a></div>';
   }
  });
  $('#' + id).animate({opacity:0}, 500, function(){
   $('#' + id).html(html);
  });
  $('#' + id).animate({opacity:1}, 500);
 });
};



function showTweets(twitter) {
 var count = 0;
 var html = '';
 $(twitter).each(function(el){
  html += '<div class="tweet">' + formatString(this.text) + '<em class="date"> - ' + quickDate(this.created_at) + '</em></div>';
  count++;
  if ( count === 5 ) { return false; } 
 });
 $('#tweets').animate({opacity:0}, 500, function(){
  $('#tweets').html(html);
 });
 $('#tweets').animate({opacity:1}, 500);
}

function formatString(str) {
 str=' '+str;
 str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
 str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
 str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
 return str;
}

function relativeTime(pastTime) {	
 var origStamp = Date.parse(pastTime);
 var curDate = new Date();
 var currentStamp = curDate.getTime();
 var difference = parseInt((currentStamp - origStamp)/1000);
 if(difference < 0) return false;
 if(difference <= 60)		return "less than a minute ago";
 if(difference < 3600)		return parseInt(difference/60)+" minutes ago";
 if(difference <= 1.5*3600) 	return "about an hour ago";
 if(difference < 23.5*3600)	return Math.round(difference/3600)+" hours ago";
 var dateArr = pastTime.split(' ');
 var time    = dateArr[4].replace(/\:\d+$/,'')
 var timeArr = time.split(':');
 var hours   = timeArr[0];
 var ampm  = 'am';
 if (timeArr[0] > 12) {
  hours = hours - 12;
  ampm  = 'pm';
 } else if (hours == 12) {
  ampm  = 'pm';
 }
 if(difference < 1.5*24*3600)
  return "Yesterday" + ' at ' + hours + ':' + timeArr[1] + ampm;
 return dateArr[2] + ' ' + dateArr[1] + (dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'') + ' at ' + hours + ':' + timeArr[1] + ampm;
}



function quickDate(str) {
 var v=str.split(' ');
 var time=v[3];
 var t=time.split(':');
 var hours = t[0];
 var ampm  = 'am';
 if (t[0] > 12) {
  hours = hours - 12;
  ampm  = 'pm';
 } else if (hours == 12) {
  ampm  = 'pm';
 }
 return v[1] + " " + v[2] + " at " + hours + ":" + t[1] + ampm;
}

function fix_flash() {
 var embeds = document.getElementsByTagName('embed');
 for (i = 0; i < embeds.length; i++) {
  embed = embeds[i];
  var new_embed;
  if (embed.outerHTML) {
   var html = embed.outerHTML;
   if (html.match(/wmode\s*=\s*('|")[a-zA-Z]+('|")/i))
    new_embed = html.replace(/wmode\s*=\s*('|")window('|")/i, "wmode='transparent'");
   else
    new_embed = html.replace(/<embed\s/i, "<embed wmode='transparent' ");
   embed.insertAdjacentHTML('beforeBegin', new_embed);
   embed.parentNode.removeChild(embed);
  } else {
   new_embed = embed.cloneNode(true);
   if (!new_embed.getAttribute('wmode') || new_embed.getAttribute('wmode').toLowerCase() == 'window')
   new_embed.setAttribute('wmode', 'transparent');
   embed.parentNode.replaceChild(new_embed, embed);
  }
 }
 var objects = document.getElementsByTagName('object');
 for (i = 0; i < objects.length; i++) {
  object = objects[i];
  var new_object;
  if (object.outerHTML) {
   var html = object.outerHTML;
   if (html.match(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")[a-zA-Z]+('|")\s*\/?\>/i))
    new_object = html.replace(/<param\s+name\s*=\s*('|")wmode('|")\s+value\s*=\s*('|")window('|")\s*\/?\>/i, "<param name='wmode' value='transparent' />");
   else
    new_object = html.replace(/<\/object\>/i, "<param name='wmode' value='transparent' />\n</object>");
   var children = object.childNodes;
   for (j = 0; j < children.length; j++) {
    try {
     if (children[j] != null) {
      var theName = children[j].getAttribute('name');
      if (theName != null && theName.match(/flashvars/i)) {
       new_object = new_object.replace(/<param\s+name\s*=\s*('|")flashvars('|")\s+value\s*=\s*('|")[^'"]*('|")\s*\/?\>/i, "<param name='flashvars' value='" + children[j].getAttribute('value') + "' />");
      }
     }
    }
    catch (err) {}
   }
   object.insertAdjacentHTML('beforeBegin', new_object);
   object.parentNode.removeChild(object);
  }
 }
}

function initializeSchool() {
 var myOptions = { zoom: 13, center: pointLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, scrollwheel: false };
 mapsmall = new google.maps.Map(document.getElementById("map_small"), myOptions);
 mapsmall = new google.maps.Marker({ position: pointLatLng, map: mapsmall, icon: iconHover });

 $("#infobis").hide();
 var newheight = ($(window).height() - 60) - ($(".schoolname").height() + 17);
 $(".contents").css("height", newheight + 'px' );
 $("iframe").each(function() {
  var url = $(this).attr("src")
  $(this).attr("src",url+"?wmode=transparent")
 });

 $(".shorturl").each(function() { 
  var href = $(this).html(); 
  var newhref = '';
  if( href.length > 70 ){
   var split = href.split('/');
   length = split.length;
   for( i=0; i < length; i++){
    if( i == 3 ){
     newhref += ".../";
    } else if( i > 3 && i < (length - 1) ){
     // do nothing
    } else {
     newhref += split[i];
     if( i != length - 1 ){
      newhref += "/";
     }
    }
   }
   if( newhref.length > 70 ){
    $(this).html(href.substring(0,70) + '...' );
   } else {
    $(this).html(newhref);
   }
  }
 }); 

 $('.news').click( function() {
  $.address.path('/news/' + $(this).attr('id') + '.html?ref=/school/' + schoolid + '.html');
  $("#infobis").load('/news/' + $(this).attr('id') + '.html', function() {
   $("#infobis").show();
  });
 });

 $('.campus a').click( function() {
  $.address.path( $(this).attr('href'));
  $("#info").load($(this).attr('href'));
  return false;
 });

 setTimeout( function() {
  document.title = schooltname;
  initBinding();
 }, 500);

 $('a.toggle').toggle(
  function() {
   $('#morenews').slideDown();
   $(this).html('Less news');
  }, function() {
   $('#morenews').slideUp();
   $(this).html('More news');
  }
 );

 $("#play").mouseover(function(){
  $(this).addClass("playhi");
 }).mouseout(function(){
  $(this).removeClass("playhi");
 });

 $('.program a').click( function() {
  $("#player").hide();
  $("#video").show();
  $("#overlayschool").show();
  $('.program-info').each(function(index) { $(this).hide(); });
  var program = $(this).attr('id');
  $("#progam_" + program).show();
  return false;
 });

 var windowwidth   = $(".contents").width();
 var programwidth  = windowwidth * 0.75;
 var programleft   = (windowwidth - programwidth) / 2;

 $('.program-info').each(function(index) {
  $(this).css("width", programwidth + 'px' );
  $(this).css("left", programleft + 'px' );
 });

 $(".closeProgram").mouseover(function(){
  $(this).addClass("closehi");
 }).mouseout(function(){
  $(this).removeClass("closehi");
 });

 $("#icons li div a").mouseover(function(){
  $(this).parents('div').addClass("hi");
 }).mouseout(function(){
  $(this).parents('div').removeClass("hi");
 });

 $("#programicons li div a").mouseover(function(){
  $(this).parents('div').addClass("hi");
 }).mouseout(function(){
  $(this).parents('div').removeClass("hi");
 });

 $(".closeProgram").click(function(){
  var player = $("#player").html();
  if( player != '' ){
   $("#player").show();
   $("#video").hide();
  }
  $("#overlayschool").hide();
  $('.program-info').each(function(index) { $(this).hide(); });
 });

 var contactleft   = (windowwidth - programwidth) / 2;
 $('#contact-info').css("left", (windowwidth - 580) / 2  + 'px' );

 $("#contact-link").click(function(){
  var href = $(this).attr('href');
  $("#overlayschool").show();
  $("#contact-info").html('<iframe src="' + href + '" width="582" height="180" frameborder="0" id="contact-link-frame"></iframe>');
  $("#contact-info").show();
  return false;
 });

 $(".contact-link-program").click(function(){
  var href = $(this).attr('href');
  $('#overlayschool').css('z-index','100002'); 
  $("#contact-info").html('<iframe src="' + href + '" width="582" height="180" frameborder="0" id="contact-link-program-frame"></iframe>');
  $("#contact-info").show();
  return false;
 });


 if ( $.address.parameter('action') === 'contact' ){
  var href = $("#contact-link").attr('href');
  $("#overlayschool").show();
  $("#contact-info").html('<iframe src="' + href + '" width="582" height="180" frameborder="0"></iframe>');
  $("#contact-info").show();
 }

 if ( $.address.parameter('action') === 'program' ){
  $("#player").hide();
  $("#video").show();
  $("#overlayschool").show();
  $('.program-info').each(function(index) { $(this).hide(); });
  var program = $.address.parameter('programid');
  $("#progam_" + program).show();
  return false;
 }

 $('.icon').bind('mouseover', menu_open)
 $('.icon').bind('mouseout',  menu_timer)

 fix_flash();
}

function fuzzyFacebookTime(timeValue) {
 defaultOptions={
  relativeTime : 48,
  monthNames   : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  amPm         : ['am', 'pm']
 }
 var options  = defaultOptions;
 var date     = parseDate(timeValue);
 var delta    = parseInt(((new Date()).getTime()-date.getTime())/1000);
 var relative = 48;
 var cutoff   = +relative===relative ? relative*60*60 : Infinity;

 if (relative===false || delta>cutoff) 
  return formatDate(date, options) + ' at ' + formatTime(date, options);
 if (delta<60)
  return 'less than a minute ago';

 var minutes=parseInt(delta/60 +0.5);
 if (minutes <= 1)
  return 'about a minute ago';

 var hours=parseInt(minutes/60 +0.5);
 if (hours<1)
  return minutes+' minutes ago';
 if (hours==1)
  return 'about an hour ago';

 var days=parseInt(hours/24 +0.5);
 if (days<1)
  return hours+' hours ago';
 if (days==1)
  return 'yesterday at ' + formatTime(date, options);

 var weeks=parseInt(days/7 +0.5);
 if (weeks<2)
  return formatDate(date, options) + ' at ' + formatTime(date, options);

 var months=parseInt(weeks/4.34812141 +0.5);
 if (months<2)
  return formatDate(date, options) + ' at ' + formatTime(date, options);

 var years=parseInt(months/12 +0.5);
 if (years<2)
  return formatDate(date, options) + ' at ' + formatTime(date, options);
}

function parseDate (str) {
 var v=str.replace(/[T\+]/g,' ').split(' ');
 return new Date(Date.parse(v[0] + " " + v[1] + " UTC"));
}

function formatTime (date, options) {
 var h=date.getHours(), m=''+date.getMinutes(), am=options.amPm;
 return (h>12 ? h-12 : h) + ':' + (m.length==1 ? '0' : '' ) + m + (h<12 ? am[0] : am[1]);
}

function formatDate (date, options) {
 var mon=options.monthNames[date.getMonth()],
 day = date.getDate(), year=date.getFullYear(), thisyear=(new Date()).getFullYear();
 return mon + ' ' + day + (thisyear != year ? ', ' + year : '');
}


