/******************/
/* Know Your Meme */
/******************/
function fbs_click(u, t) {window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');return false;}

function parse_domain(str) {return str.replace(/^(http|https)(\:\/\/)([A-Z0-9\@\:\.\-\_]*)(.*)/i, '$1$2$3');}
function parse_path(str) {return str.replace(/^(http|https)(\:\/\/)([A-Z0-9\@\:\.\-\_]*)(.*)/i, '$4');}

function gaTrackPage(url) {if (!url || url == '') return; alert(parse_path(url)); try {pageTracker._trackPageview(parse_path(url));} catch (err) {}}
function gaTrackEvent(cat, action, opt_label, opt_val) {if (!cat || cat == '') return; try {if (!action || action == '') action = '-n/a-'; pageTracker._trackEvent(cat, action, opt_label, opt_val);} catch(err) {}}


var SLIDE_SPEED = 500;
function jeval(str){ return eval('(' +  str + ');'); }
function debug(m){/* if (typeof console != 'undefined'){console.log(m);} */}
function puts(m){ debug(m); }


/* initialize */
$(function(){

  /* AJAX activity indicators */
  $("#waiter").ajaxStart(function(){
    $(this).show();
  }).ajaxStop(function(){
    $(this).hide();
  }).ajaxError(function(){
    $(this).hide();
  });

  /*Truncate long fields
  $('.jstruncate').truncate({max_length: 50}); */
	
	/* Search box selecting/highlighting */
	$('#search_q').focus(function(){
	  if ($(this).attr('value') == 'Search...' || $(this).attr('value') == 'Search users...') $(this).removeClass('soft').attr('value', '');
    // else $(this).select();
	  });
	$('#search_q').blur(function(){if ($(this).attr('value') == '') $(this).addClass('soft').attr('value', ($(this).hasClass('admin') ? 'Search users...' : 'Search...'));});

	$('.e_obf').each(function() {
		var c = $(this).text().replace(/&nbsp;|\s/g, '').replace(/\(at\)/ig, '@').replace(/\(dot\)/ig, '.');
		var s = $(this).attr('rel');
		$(this).before('<a href="http://www.knowyourmeme.com/contact" onclick="location.href=\'mailto:'+ c + (s ? '?subject='+ s : '') +'\'; return false;">'+ c +'</a>').remove();
	});


  // a.remote auto-ajax magic
	make_remote_links();

  // additional document.ready wrapper needed...?
  $(document).ready(function() {
    $('.timeago').timeago();
    User.Init();
    gallery_facebox('.fbox');
    
    // facebox-ify
    $('a[rel*=facebox]').facebox();
    
  });
  
});




/* .remote turns links into ajax like magic
   doesn't let you do anything with response, callbacks still todo
   for now just pair with an onclick & fake it
   use .delete, .put or .post as well for those HTTP verbs */
function make_remote_links() {
  $('a.remote').unbind('click').click(function(){
		var elm = $(this);
    if (elm.hasClass('confirm')) {
      if (!confirm('Are you sure want to do this?')) return false;
    }

    var data = {};
    var method = 'GET';
    if (elm.hasClass('delete')) method = 'DELETE';
    /*if (elm.hasClass('delete')) {
      method = 'POST';
      data['_method'] = 'delete';
    }*/
    if (elm.hasClass('put')) method = 'PUT';
    if (elm.hasClass('post')) method = 'POST';
    
		var success = function(response) {flash(response);};
		var failure = function(response) {flash(response.responseText);};

    /* console.log("OK, will make the request now! method = "+method); */
    /* RESTController will try to redirect you w/o format... honestly we should get JSON, or HTML :| */    
    var data = {format: 'html'}; // was XML but we rarely respond to that...
    // var data = {};

    /* TODO: move these custom callbacks onto their actual pages, or into its own file (?) */
		if (elm.hasClass('favorite')) {
		  if (!User.LoggedIn) {
		    location.href = '/signup';
		    return false;
		  } else {
  			var success = function() {
  			  var i = parseInt(elm.text()), id = Favorites.GetId(elm.attr('class')), kind = Favorites.GetKind(elm.attr('class'));
  			  if (elm.hasClass('on')) {
  			    if (id && kind) Favorites.Remove(id, kind); elm.text(i > 0 ? (i-1) : 0); elm.removeClass('on');
  			    gaTrackEvent('Favorites', 'Remove'+(kind != 'entry' ? ' '+ kind.toUpperCase() : ''), id);
  			  } else {
  			    if (id && kind) Favorites.Add(id, kind); elm.text(i+1); elm.addClass('on');
  			    gaTrackEvent('Favorites', 'Add'+(kind != 'entry' ? ' '+ kind.toUpperCase() : ''), id);
  			  }
  			}, failure = function(response) {};
  		}
		} else if (elm.hasClass('friend')) {
			var success = function(responseText) {elm.parent().before(responseText).remove(); make_remote_links();}, failure = function(response) {};
		} else if ((elm.hasClass('delete') && elm.hasClass('feed')) || elm.hasClass('admin_user')) {
			elm.parent().parent().animate({'height' : 'toggle'}, 500, false, function() {$(this).remove();});
			var success = function(response) {}, failure = function(response) {};
		} else if (elm.hasClass('delete') && (elm.hasClass('comment') || elm.hasClass('photo'))) {
			elm.parent().animate({'height' : 'toggle'}, 500, false, function() {$(this).remove();});
			var success = function(response) {}, failure = function(response) {};
		} else if ((elm.hasClass('delete') && (elm.hasClass('forum_post') || elm.hasClass('forum_topic')))) {
			elm.parent().parent().animate({'height' : 'toggle'}, 500, false, function() {$(this).remove();});
			var success = function(response) {}, failure = function(response) {};
		} else if (elm.hasClass('redirect')) {
		  var success = function() {location.href = '/';}, failure = function(response) {};
		}

    var what = {type: method, url: elm.attr('href'), data: data, success : success, failure : failure};
    /* if(elm.hasClass('delete')) what['dataType'] = 'script'; */
    $.ajax(what);
    /* console.log('returnin false...'); */
    return false;
  });
}


/* flash shortcut */
function flash(msg, kind) {
  var kind = (kind == null) ? "notice" : kind; /* seriously, what kind of language doesn't have default args? */

  /* console.log("flash("+kind+"): "+msg); */
  if (msg == "" || msg == undefined) return false;

  if (kind == 'error'){
    $('#flash').removeClass('notice').addClass('error');
  } else { /*anything else is a notice*/
    $('#flash').removeClass('error').addClass('notice');
  }

  $('#flash').html(msg).slideToggle(); 
  setInterval(function(){ $('#flash').fadeOut('fast'); }, 3000);
}
function notice(msg) {flash(msg, 'notice');}
function error(msg) {flash(msg, 'error');}




function tog(clicker, toggler, callback, speed){
  if (speed == undefined) speed = SLIDE_SPEED;
  if (callback) {
    $(clicker).click(function(){$(toggler).slideToggle(speed, callback); return false;});
  } else {
    $(clicker).click(function(){$(toggler).slideToggle(speed); return false;});
  }
}
function togger(j, callback, speed){
  if (speed == undefined) speed = SLIDE_SPEED;
  if(callback) {
    $(j).slideToggle(speed, callback); 
  } else {
    $(j).slideToggle(speed);
  }
}



function async_message(m, d){message(m, d);}
function messages(m, d){message(m, d);}
function message(message, duration){
    if (duration == undefined) duration = 3000;
    if ($.browser.msie) { $("#message").css({position: 'absolute'}); }
    $("#message").text(message).fadeIn(1000);
    setTimeout('$("#message").fadeOut(2000)',duration);
    return false;
}


function thickbox(id, title, height, width){
/*    location.href = '/photos/' + id;
      return; */
    if (height == undefined){ height = 300; }
    if (width == undefined){ width = 300; }
    tb_show(title, '#TB_inline?height='+ height +'&amp;width='+ width +'&amp;inlineId='+ id +'', false);
    return false;
}

function truncate(str, len){
  if (len == undefined){ len = 9; }
  if (str.length <= len+3){ return str; }
  return str.substring(0, len) + '...';
}

function tog_login_element() {
  $('.login_element, .checkout_element').toggle();
}

function toggleComments(comment_id) {
	$('#comment_'+comment_id+'_short, #comment_'+comment_id+'_complete').toggleClass('hidden');
  
	$('#comment_'+comment_id+'_toggle_link').html(
    	$('#comment_'+comment_id+'_toggle_link').html() == "(more)" ? "(less)" : "(more)"
	); 
}

var Vimeo = {
	GetId : function(id) {
		return (/vimeo/.test(id)) ? (/clip_id/.test(id) ? id.replace(/^(.*)(clip_id\=)(\d+)(.*)$/, '$3') : id.replace(/^(.*)\/(\d*)$/, '$2')) : id;
	},
	GetThumbnail : function(id, callback) {
		id = this.GetId(id);
		var js = document.createElement('script');
		var url = 'http://vimeo.com/api/clip/'+id+'.json?callback='+ (callback && callback != '' ? callback : 'Vimeo.ShowThumbnail');
		js.setAttribute('type', 'text/javascript');
		js.setAttribute('src', url);
		document.getElementsByTagName('head').item(0).appendChild(js);
	},
	ShowThumbnail : function(json) {
		var src = (this.Use == 'small' ? json[0].thumbnail_small : json[0].thumbnail_large.replace(/\_160/, '_640'));
		$('img.vimeo_'+ json[0].clip_id).attr('src', src).parent().parent().removeClass("hidden");
	}
};

var YouTube = {GetId : function(id) {return id.replace(/^(.*)(youtube\.com\/)(v\/|watch\?v\=)([a-z0-9\-\_]{5,12})(.*)$/i, '$4');}, GetThumbnail : function(id) {return 'http://i4.ytimg.com/vi/'+ (/youtube/.test(id) ? this.GetId(id) : id) +'/'+ (this.Use == 'small' ? '1' : '0') +'.jpg';}};

$.fn.clickToPlay = function(skipFirst, facebox) {
	var ids = new Array();
	return this.each(function(i) {
		var e = $(this).find('embed').each(function() {
			var j = ids.length, embed, element, url, width, height, klass = '', klass2 = '';
			if (this.src.match(/youtube.com/)) {
				ids[j] = YouTube.GetId(this.src);
				klass = 'youtube_'+ids[j];
				var img = YouTube.GetThumbnail(ids[j]);
				embed = $(this).parent().parent().html().replace(/\n/ig, '').replace(/^(.*)(\<object)(.*)(\<\/object\>)(.*)$/ig, '$2$3$4').replace(new RegExp(ids[j], 'g'), ids[j]+'&amp;autoplay=1');
				url = 'http://www.youtube.com/watch?v='+ ids[j]; width = 320; height = 240;
				element = 'vid_click_'+ ids[j] +'_'+ i;
			} else if (this.src.match(/vimeo.com/)) {
				ids[j] = Vimeo.GetId(this.src);
				klass = 'vimeo_'+ids[j]; klass2 = 'hidden'; img = 'images/blank.png';
				embed = $(this).parent().parent().html().replace(/\n/ig, '').replace(/^(.*)(\<object)(.*)(\<\/object\>)(.*)$/ig, '$2$3$4').replace(new RegExp(ids[j], 'g'), ids[j]+'&amp;autoplay=1');
				url = 'http://www.vimeo.com/'+ ids[j]; width = 320; height = 180;
				element = 'vid_click_'+ ids[j] +'_'+ i;
				Vimeo.GetThumbnail(ids[j]);
			}
			if (((skipFirst && ids.length > 1) || !skipFirst) && embed && element) {
				/*$(this).parent().before('<div class="vid_click '+ klass2 +'" id="'+ element +'"><a href="'+ url +'"><img class="play" src="/images/blank.png" style="top: '+ Math.round((height-50)/2) +'px; left: '+ Math.round((width-50)/2) +'px;" border="0" title="Click to play this video." /><img src="'+ img +'" width="'+ width +'" height="'+ height +'" border="0" title="Click to play this video." class="'+klass+'" /></a></div>'); */
				$(this).parent().before('<div class="vid_click '+ klass2 +'" id="'+ element +'"><a href="'+ url +'"><img class="play" src="/images/blank.png" border="0" title="Click to play this video." /><img src="'+ img +'" width="'+ width +'" height="'+ height +'" border="0" title="Click to play this video." class="'+klass+'" /></a></div>');
        if (facebox) {
  				$('#'+ element +' a').click(function() {$.facebox(embed); return false;});
        } else {
  				$('#'+ element +' a').click(function() {$(this).parent().after(embed); $(this).remove(); return false;});
  			}
  			gaTrackEvent('Click2Play', 'Video '+ ids[j], url);
				$(this).parent().remove();
			}
		});
	});
};

function gallery_facebox(elm) {
	var fbimgs = [], fbtitles = [];
	$(elm).each(function() {
		if ($(this).attr('rel') != '') {
			fbimgs.push($(this).attr('rel'));
			if ($(this).attr('rel') != this.href) {
				var etc = (this.href.indexOf($(this).attr('rel')) == -1 ? '<br /><br /><small><a href="'+ $(this).attr('href') +'#comments" class="button ghost small"><span>View Comments</span></a> <a href="'+ $(this).attr('href') +'" class="button ghost small"><span>More Info&hellip;</span></a></small>' : '');
				fbtitles.push($(this).attr('title') + etc );
			}
		}
	});
	if (fbimgs.length > 0) $(elm).click(function() {$.facebox({images:fbimgs,titles:fbtitles,initial:$(this).attr('rel')}, 'gallery');return false;});
}

var Favorites = {
  Ids : {Entries:[], Images:[], Supplements:[]},
  Init : function() {
    $('.favorite').each(function() {
      var id = parseInt(Favorites.GetId(this.className)), kind = Favorites.GetKind(this.className);
      if (id && ((kind == 'entry' && $.inArray(id, Favorites.Ids.Entries) != -1) || (kind == 'photo' && $.inArray(id, Favorites.Ids.Photos) != -1) || (kind == 'supplement' && $.inArray(id, Favorites.Ids.Supplements) != -1))) $(this).addClass('on');
    });
    
    if (Favorites.Ids.Entries.length > 0) {
      var s = '.entry_row.entry_'+ Favorites.Ids.Entries.join(' .entry_image, .entry_row.entry_') +' .entry_image';
      $(s).append('<span class="fave"><span class="favorite on"></span></span>');
    }

    if (Favorites.Ids.Images.length > 0) {
      var s = '.image.image_'+ Favorites.Ids.Images.join(' a.img, .image.image_') +' a.img';
      $(s).append('<span class="fave"><span class="favorite on"></span></span>');
    }

    if (Favorites.Ids.Supplements.length > 0) {
      var s = '.entry_row.supplement_'+ Favorites.Ids.Supplements.join(' .entry_image, .entry_row.supplement_') +' .entry_image';
      $(s).append('<span class="fave"><span class="favorite on"></span></span>');
    }
  },
  GetId : function(klass) {return (/entry|image|photo|supplement/.test(klass)) ? klass.replace(/(.*)(entry|image|photo|supplement)(_)([\d]+)(.*)/, '$4') : false;},
  GetKind : function(klass) {return (/entry|image|photo|supplement/.test(klass)) ? klass.replace(/(.*)(entry|image|photo|supplement)(_)([\d]+)(.*)/, '$2') : false;},
  Add : function(id, kind) {var a = this.GetArray(kind); a.push(id);},
  Remove : function(id, kind) {var a = this.GetArray(kind), k = $.inArray(id, a); if (k >= 0) a.splice(k,1);},
  GetArray : function(kind) {
    if (kind == 'entry') {
      return Favorites.Ids.Entries;
    } else if (kind == 'photo') {
      return Favorites.Ids.Photos;
    } else if (kind == 'supplement') {
      return Favorites.Ids.Supplements;
    } else {
      return [];
    }
  }
};

var User = {
  LoggedIn : false,
  Favorites : [],

  Init : function() {
    if (!this.LoggedIn) return;
    Favorites.Init();
  }
};