var activity_data         = null;
var activity_current      = 0;
var activity_update_time  = 5000;
var activity_timer        = null;

$(document).ready(function() {
  startFooSlider();
  $('div.logo-rotating').scrollable().navigator();
  $('a[rel="_blank"]').click(function() {
    window.open($(this).attr('href'));
    return false;
  });
  $('a.bookmark').click(function() {
    var el = $($(this).attr('href'));
    $.scrollTo(el, 950, { onAfter: function() { window.location.hash = el.attr('id') }});
    return false;
  });
  initBaloons();
  initInputs();
  $('.live_site_count').load('stats.php?type=live_site_count');
  $('.live_partner_count').load('stats.php?type=live_partner_count');
  loadActivityFeed(5);
  initCarousel();
  initFancy();
});

function initFancy() {
  $(".fancy").fancybox({
    'titleShow' : false,
    'width' : 700,
    'height' : 400,
    'padding' : 5,
    'transitionIn' : 'none',
    'transitionOut' : 'none',
    'overlayColor' : '#144B6C',
    'overlayOpacity' : 0.8
  });
}

function startFooSlider() {
	$('#content .jobs .slider').tabs('#content .jobs .slider > div.slide', {
		effect: 'fade', 
		rotate: true
	}).slideshow({
		autoplay: true
	});
}

function initBaloons() {
	$.baloon = $('.baloon');
	
	$.baloon.appendTo('body');
	
	$.baloon.on = function(text, e) {
		$.baloon.css({ top: ($(e).offset().top - 80), left: ($(e).offset().left + 50) });
		
		text = text.split(',');
		$.baloon.find('h3').text(text[0]);
		$.baloon.find('span').text(text[1]);
		
		$.baloon.show();
	}
	
	$.baloon.off = function() { $.baloon.hide(); }
	
	$('#hint-area a').each(function(i, el) {
		$(el).mouseenter(function( event ) {
			$.baloon.on($(el).attr('title'), el);
		});

		$(el).mouseleave(function( event ) { $.baloon.off(); });
	});
}

function initInputs() {
	 $('.auto-hint').each(function(){
        if($(this).attr('title') == ''){ $(this).attr('title', $(this).val()); }
        
        if($(this).val() == ''){ $(this).val($(this).attr('title')); }
        $(this).focus(function(){
            if($(this).val() == $(this).attr('title')){ 
                $(this).val('');
                $(this).removeClass('auto-hint');
            }
        });
        $(this).blur(function(){
        	if($(this).val() == ''){ 
        	   $(this).val($(this).attr('title'));
        	   $(this).addClass('auto-hint');
        	}
        });
    });
}

function getTweets( accounts, limit, element, options) {
	$.getJSON('twitter.php', { 'accounts' : accounts }, function(data) { outputTweets(data, limit, element, options); });
}
function getTweetLists( accounts, limit, element, options) {
	$.getJSON('twitter.php', { 'accounts' : accounts, 'type' : 'list' }, function(data) { outputTweets(data, limit, element, options); });
}
function outputTweets(tweets, limit, element, options) {
  $('.load', element).remove();
  var ls = $('<ul>');
  $(tweets).each(function(i, tweet) { if(i < limit) { ls.append(constructTweetLayout(tweet, options)); } });
  $(element).append(ls);
}

function constructTweetLayout(tweet, options) {
  var config = {
    'show_avatar' : true,
    'format_content' : true,
    'show_timestamp' : true
  };
  config = jQuery.extend(config, options);
  // returning object
  var li = $('<li>');
  // avatar
  if(config.show_avatar) {
    var avatar_lnk = $('<a>').attr({ 'href' : 'http://twitter.com/' + tweet.user.screen_name, 'target' : '_blank' }).addClass('avatar');
    var avatar_img = $('<img>').attr({ 'src' : tweet.user.profile_image_url, 'alt' : tweet.user.name}).appendTo(avatar_lnk);
    avatar_lnk.appendTo(li);
  }
  // tweet content
  var tweet_content = $('<div>');
  var content_str = tweet.text;
  if(config.format_content) {
    content_str = twitterUrlRewrites(content_str);
    content_str = twitterAtRewrites(content_str);
    content_str = twitterHashRewrites(content_str);
  }
  tweet_content.html(content_str);
  if(config.show_timestamp) {
    var lnk = $("<a>").attr({ 'href' : 'http://twitter.com/' + tweet.user.screen_name + "/status/" + tweet.id, 'target' : '_blank' }).addClass('datetime');
    $('<span>').html(twitterTimeRewrite(tweet.created_at) + ' via ' + tweet.source).appendTo(lnk);
    lnk.appendTo(tweet_content);
  }
  tweet_content.appendTo(li);
  return li;
}
function twitterTimeRewrite(timestamp) {
  var today = new Date();
  var post_date = new Date(timestamp);
  var milli_diff = today.valueOf() - post_date.valueOf();
  var milli_day = 86400000;
  if(milli_diff < milli_day) {
    var sec_diff = milli_diff/1000;
    var res = "";
    if(sec_diff < 60) 
      res = sec_diff + " seconds ago";
    else if(sec_diff < 3500) 
      res = "about " + Math.round(sec_diff/60) + " minutes ago";
    else 
      res = "about " + Math.round(sec_diff/3600) + " hours ago";
    return res;
  } else {
    return post_date.toUTCString();
  }
}
function twitterUrlRewrites(str) {
  // url re-writes...
  var regex = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/g;
  matches = str.match(regex);
  $(matches).each(function(i, match) {
    var ur = "<a href='"+match+"' target='_blank'>"+match+"</a>";
    str = replaceContentString(str, match, ur);
  });
  return str;
}
function twitterAtRewrites(str) {
  // @ re-writes...
  var regex = /@{1}(\w+)/g;
  matches = str.match(regex);
  $(matches).each(function(i, match) {
    var at = "<a href='http://twitter.com/"+match.replace('@', '')+"' target='_blank'>"+match+"</a>";
    str = replaceContentString(str, match, at);
  });
  return str;
}
function twitterHashRewrites(str) {
  // @ re-writes...
  var regex = /#{1}(\w+)/g;
  matches = str.match(regex);
  $(matches).each(function(i, match) {
    var at = "<a href='http://twitter.com/search?q="+encodeURI(match.replace('#', ''))+"' target='_blank'>"+match+"</a>";
    str = replaceContentString(str, match, at);
  });
  return str;
}
function replaceContentString(str, match, replacement) {
  return str.replace(match, replacement);
}

/*
 * With many thanks to Jan Sorgalla - http://sorgalla.com/projects/jcarousel/
*/
function initCarousel() {
  var carou = $('#logocarousel');
  if(carou.size() > 0) {
    carou.jcarousel({
      auto: 4,
      scroll: 1,
      animation: 1500,
      wrap: 'circular',
      initCallback: mycarousel_initCallback
    });
  }
  var wwdcar = $('#wwdcaro');
  if(wwdcar.size() > 0) {
    wwdcar.jcarousel({
      auto: 0,
      scroll: 1,
      animation: 1000,
      initCallback: mycarousel_initCallback
    });
  }
}

function mycarousel_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.
    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });
    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

/*
 * Activity Feed...
*/
function loadActivityFeed(number_to_show) {
  var af = $.getJSON('activity.php', { 'type' : 'latest_member_activity' }, function(data) {
    activity_data = $(data);
    activity_current = (activity_data.size() - 1);
    for(i=0; i < number_to_show; i++) { addActivityItem({compact : false, animate : false}); }
    setActivityUpdate();
  });
}

function setActivityUpdate() {
  activity_timer = setInterval('addActivityItem({compact : true, animate : true})', activity_update_time);
}

function clearActivityUpdate() {
  clearInterval(activity_timer);
  activity_data = null;
  acitity_current = 0;
}

function addActivityItem(options) {
  options = jQuery.extend({animate : true, collapse : true}, options);
  if(activity_data == null) return false;
  data = activity_data[activity_current];
  if(activity_current == -1 || data == null) {
    clearActivityUpdate();
    return false;
  } else {
    var af_holder = $('#latest_activity_feed');
    var af_item = $('<li>').css({'display' : 'none'});
    // build the image...
    var af_img = $('<img>').attr({'src': data['member_photo'], 'alt' : data['member_name']});
    var af_img_src = $('<a>').attr({'href': data['site_url'], 'target' : '_blank'}).addClass('avatar').html(af_img).appendTo(af_item);
    // build the div below...
    var af_hl = $('<div>');
    var content_copy = "";
    content_copy += data['member_name']+", "+Number(data['member_age'])+" from "+data['member_region'];
    // switch content...
    content_copy += " "+activityTypeToText(Number(data['type_id']));
    content_copy += " on <a href='"+data['site_url']+"'>"+data['site_name']+"</a> ";
    $('<strong>').html(content_copy).appendTo(af_hl);
    af_hl.appendTo(af_item);
    
    // insert into view...
    af_holder.prepend(af_item);
    if(options['compact']) { $(af_holder).children('li:last-child').slideUp('slow', function() { $(this).remove(); $(af_holder).children('li:last-child').addClass('no-border'); }); }
    (options['animate']) ? af_item.slideDown('slow') : af_item.css({'display' : 'block'});
    activity_current--;
    return true;
  }
}

function activityTypeToText(type_id) {
  var map = {
		1  : "became a new full member",
		2  : "updated their profile",
		3  : "uploaded a new photo",
		4  : "posted a new diary entry",
		5  : "uploaded a new video",
		8  : "updated their status",
		10 : "sent a new private message",
		12 : "sent a gift",
		14 : "winked at another member",
		15 : "added a new favourite"
	}
	return map[type_id];
}
