﻿// bind parameters
function curry(fn) {
	var args = [];
	for (var i = 1, len = arguments.length; i < len; ++i) {
		args.push(arguments[i]);
	};
	return function() {
		fn.apply(window, args);
	};
}



jQuery.fn.fancyZoom = function(options){
/* Fancy Zoom script by Steve Smith of Ordered List, modified to support ajax :) */

  var options   = options || {};
  var directory = options && options.directory ? options.directory : '/img/fancyzoom';
  var zooming   = false;

  if ($('#zoom').length == 0) {
	var ext = $.browser.msie ? 'gif' : 'png';
	var html = '<div id="zoom" style="display:none; z-index:150;"> \
				  <table id="zoom_table" style="border-collapse:collapse; width:100%; height:100%;"> \
					<tbody> \
					  <tr> \
						<td class="tl" style="background:url(' + directory + '/tl.' + ext + ') 0 0 no-repeat; width:20px; height:20px; overflow:hidden;">&#160;</td> \
						<td class="tm" style="background:url(' + directory + '/tm.' + ext + ') 0 0 repeat-x; height:20px; overflow:hidden;">&#160;</td> \
						<td class="tr" style="background:url(' + directory + '/tr.' + ext + ') 100% 0 no-repeat; width:20px; height:20px; overflow:hidden;">&#160;</td> \
					  </tr> \
					  <tr> \
						<td class="ml" style="background:url(' + directory + '/ml.' + ext + ') 0 0 repeat-y; width:20px; overflow:hidden;">&#160;</td> \
						<td class="mm" style="background:#fff; vertical-align:top; padding:6px;"> \
						  <div id="zoom_content"></div> \
						</td> \
						<td class="mr" style="background:url(' + directory + '/mr.' + ext + ') 100% 0 repeat-y; width:20px; overflow:hidden;">&#160;</td> \
					  </tr> \
					  <tr> \
						<td class="bl" style="background:url(' + directory + '/bl.' + ext + ') 0 100% no-repeat; width:20px; height:20px; overflow:hidden;">&#160;</td> \
						<td class="bm" style="background:url(' + directory + '/bm.' + ext + ') 0 100% repeat-x; height:20px; overflow:hidden;">&#160;</td> \
						<td class="br" style="background:url(' + directory + '/br.' + ext + ') 100% 100% no-repeat; width:20px; height:20px; overflow:hidden;">&#160;</td> \
					  </tr> \
					</tbody> \
				  </table> \
				  <a href="#" title="Close" id="zoom_close" style="position:absolute; top:0; left:0;z-index:200;background:transparent;"><img src="' + directory + '/closebox.' + ext + '" alt="Close" style="border:none;display:block;" /></a> \
				</div>';

	$('body').append(html);

	$('html').click(function(e){if($(e.target).parents('#zoom:visible').length == 0) hide();});
	$(document).keyup(function(event){
		if (event.keyCode == 27 && $('#zoom:visible').length > 0) hide();
	});

	$('#zoom_close').click(hide);
  }

  var zoom          = $('#zoom');
  var zoom_table    = $('#zoom_table');
  var zoom_close    = $('#zoom_close');
  var zoom_content  = $('#zoom_content');

  this.each(function(i) {
	$($(this).attr('href')).hide();
	$(this).click(show);
  });

  return this;

  function show(e) {
	if (zooming) return false;
		zooming         = true;
		var href = $(this).attr('href');
		var content_div = $(href);
	var zoom_width  = options.width;
		var zoom_height = options.height;

		var width       = window.innerWidth || (window.document.documentElement.clientWidth || window.document.body.clientWidth);
	var height      = window.innerHeight || (window.document.documentElement.clientHeight || window.document.body.clientHeight);
	var x           = window.pageXOffset || (window.document.documentElement.scrollLeft || window.document.body.scrollLeft);
	var y           = window.pageYOffset || (window.document.documentElement.scrollTop || window.document.body.scrollTop);
	var window_size = {'width':width, 'height':height, 'x':x, 'y':y}

		var width              = (zoom_width || content_div.width()) + 52;
		var height             = (zoom_height || content_div.height()) + 52;
		var d                  = window_size;

		// ensure that newTop is at least 0 so it doesn't hide close button
		var newTop             = Math.max((d.height/2) - (height/2) + y, 0);
		var newLeft            = (d.width/2) - (width/2);
		var curTop             = e.pageY;
		var curLeft            = e.pageX;

		zoom_close.attr('curTop', curTop);
		zoom_close.attr('curLeft', curLeft);
		//zoom_close.attr('scaleImg', options.scaleImg ? 'true' : 'false');

	$('#zoom').hide().css({
			position	: 'absolute',
			top				: curTop + 'px',
			left			: curLeft + 'px',
			width     : '1px',
			height    : '1px'
		});

	fixBackgroundsForIE();
	zoom_close.hide();

	if (options.closeOnClick) {
	  $('#zoom').click(hide);
	}

	zoom_content.html('');
	

	if(href.indexOf('http') != -1) {

	  var ajaxcall = true, ajaxdata;

		var onDataLoad = function(data) {
				if(zooming) 
					ajaxdata = data;
				else
					zoom_content.html(data).removeClass('ajaxload');
		};
		if(href.search(/(.*).(jpg|jpeg|gif|png)$/gi) != -1) {
		  var imgload = new Image();
		  $(imgload).load(curry(onDataLoad, imgload)).attr('src', href);
		} else {
		  $.get(href, onDataLoad);
		}
	}

	$('#zoom').animate({
	  top     : newTop + 'px',
	  left    : newLeft + 'px',
	  opacity : "show",
	  width   : width,
	  height  : height
	}, 450, null, function() {
	  //if (options.scaleImg != true) {
		if(ajaxcall == true) {
		  zoom_content.css({width:zoom_width,height:zoom_height});
		  if(ajaxdata) zoom_content.html(ajaxdata);
		  else zoom_content.addClass('ajaxload');
		} else
			zoom_content.html(content_div.html());
		//}
			unfixBackgroundsForIE();
			zoom_close.show();
			zooming = false;
	})
	
	if (options.overlay) {
	  $('body').append('<div id="fancy-overlay" style="background:#000; display:none; filter:alpha(opacity=40); -moz-opacity: 0.4; opacity:0.4; position: absolute; margin: auto; top: 0;left: 0; z-index: 100; width: 100%; height: 100%;"></div>');
	  $('#fancy-overlay').fadeIn(125);
	}
	return false;
  }

  function hide() {
	if (zooming) return false;
		zooming         = true;
	if (options.overlay) {
	  $('#fancy-overlay').fadeOut(125,function() { $(this).remove(); });
	}
	  $('#zoom').unbind('click');
		fixBackgroundsForIE();
		//if (zoom_close.attr('scaleImg') != 'true') {
		zoom_content.html('').removeClass();
		//}
		zoom_close.hide();
		$('#zoom').animate({
	  top     : zoom_close.attr('curTop') + 'px',
	  left    : zoom_close.attr('curLeft') + 'px',
	  opacity : "hide",
	  width   : '1px',
	  height  : '1px'
	}, 500, null, function() {
	  /*if (zoom_close.attr('scaleImg') == 'true') {
			zoom_content.html('');
		}*/
	  unfixBackgroundsForIE();
			zooming = false;
	});
	return false;
  }

  function switchBackgroundImagesTo(to) {
	$('#zoom_table td').each(function(i) {
	  var bg = $(this).css('background-image').replace(/\.(png|gif|none)\"\)$/, '.' + to + '")');
	  $(this).css('background-image', bg);
	});
	var close_img = zoom_close.children('img');
	var new_img = close_img.attr('src').replace(/\.(png|gif|none)$/, '.' + to);
	close_img.attr('src', new_img);
  }

  function fixBackgroundsForIE() {
	if ($.browser.msie && parseFloat($.browser.version) >= 7) switchBackgroundImagesTo('gif');
  }
  function unfixBackgroundsForIE() {
	if ($.browser.msie && $.browser.version >= 7) switchBackgroundImagesTo('png');
  }
}

jQuery.fn.linkify = function(options) {
	var defaults = {
		extraclass: false,
		onclick: false
	};
	var options = $.extend(defaults,options); 
	return this.each(function(){
		var obj = $(this);
		var inp = obj.parent();
		inp.addClass('options');
		if(options.extraclass) inp.parent().addClass(options.extraclass);
		var html = '<ul class="list">';
		$('option',obj).each(function(i){
			html += '<li '+(i==0 ? ' class="first"' : '')+'><a href="#' + $(this).val() + '"' + ($(this).attr('selected') ? ' class="selected"' : '') + '>' + $(this).text() + '</a></li>';
		});
		html += '</ul>';
		$(inp).prepend(html);
		var lnk = $(inp).find('> ul a');
		lnk.each(function() {
			$(this).click(function() {
				lnk.removeClass();
				$(this).addClass('selected');
				$(inp).find('option:selected').removeAttr('selected');
				var ahref = $(this).attr('href').split('#')[1];
				$(inp).find('option[value='+ ahref + ']').attr('selected',true);
				if(options.onclick) options.onclick(ahref);
				return false;
			});
		});
	});
}
function SelectText(element) {
	var text = element[0];
	if ($.browser.mozilla || $.browser.opera) {
		var range = document.createRange();
		range.selectNodeContents(text);
		var selection = window.getSelection();
		selection.removeAllRanges();
		selection.addRange(range);
	} else if ($.browser.msie) {
		var range = document.body.createTextRange();
		range.moveToElementText(text);
		range.select();
	} else if ($.browser.safari) {
		var selection = window.getSelection();
		selection.setBaseAndExtent(text, 0, text, 1);
	}
}
function twitterCallback2(twitters) {
  var statusHTML = '';
  for (var i=0; i<twitters.length; i++){
	var username = twitters[i].user.screen_name;
	var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
	  return '<a href="'+url+'">'+url+'</a>';
	}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
	  return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
	});
	statusHTML += '<li>'+status+' &ndash; <small>'+relative_time(twitters[i].created_at)+'</small></li>';
  }

  $('.loading').fadeOut(500, function() {
		$('#news div').prepend($('<ul>'+statusHTML+'</ul>').hide().fadeIn(750));
		$(this).remove();
  });
}
function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);
  
  if (delta < 60) {
	return 'less than a minute ago';
  } else if(delta < 120) {
	return 'about a minute ago';
  } else if(delta < (60*60)) {
	return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
	return 'about an hour ago';
  } else if(delta < (24*60*60)) {
	return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
	return '1 day ago';
  } else {
	return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}
jQuery.fn.fadeSlide = function(opacity,height,speed,callback) {
return this.animate({
	opacity: opacity,
	height: height
}, speed, callback);
}
jQuery.fn.tipsy = function(options) {
	var defaults = {
			gravity: 'n',
			html: false,
			sprite: false,
			fade: true,
			title: 'title',
			fallback: ''
	};
	options = $.extend(defaults, options || {});
	return this.each(function() {
		if ($(this).attr('title') || typeof($(this).attr('original-title')) != 'string') {
			$(this).attr('original-title', $(this).attr('title') || '').removeAttr('title');
		}
		$(this).hover(function() {
			$.data(this, 'cancel.tipsy', true);
			var tip = $.data(this, 'active.tipsy');
			if (!tip) {
				tip = $('<div class="tipsy"><div class="tipsy-inner"/><div class="arrow"/></div>');
				tip.css({position: 'absolute', zIndex: 100000});
				$.data(this, 'active.tipsy', tip);
			}
			var title;
			if (typeof options.title == 'string') {
				title = $(this).attr(options.title == 'title' ? 'original-title' : options.title);
			} else if (typeof options.title == 'function') {
				title = options.title.call(this);
			}
			var tipsyinner = tip.find('.tipsy-inner');
			tipsyinner[options.html ? 'html' : 'text'](title || options.fallback);
			if(options.sprite) tipsyinner.wrapInner('<div id="'+title+'sprite" class="tipsy-sprite" />');
			var arr = tip.find('.arrow');
			var pos = $.extend({}, $(this).offset(), {width: this.offsetWidth, height: this.offsetHeight});
			arr.get(0).className = 'arrow'; //reset
			tip.remove().css({top: 0, left: 0, visibility: 'hidden', display: 'block'}).appendTo(document.body);
			var actualWidth = tip[0].offsetWidth, actualHeight = tip[0].offsetHeight;
			var gravity = (typeof options.gravity == 'function') ? options.gravity.call(this) : options.gravity;
			switch(gravity.charAt(0)) {
				case 'n':
					tip.css({top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2});
					arr.addClass('arrow-north');
					break;
				case 's':
					tip.css({top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2});
					arr.addClass('arrow-south');
					break;
				case 'e':
					tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth});
					arr.addClass('arrow-east');
					break;
				case 'w':
					tip.css({top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width});
					arr.addClass('arrow-west');
					break;
			}
			if (options.fade) {
				tip.stop().css({opacity: 0, display: 'block', visibility: 'visible'}).animate({opacity: 1});
			} else {
				tip.css({visibility: 'visible'});
			}
		}, function() {
			$.data(this, 'cancel.tipsy', false);
			var self = this;
			setTimeout(function() {
				if ($.data(this, 'cancel.tipsy')) return;
				var tip = $.data(self, 'active.tipsy');
				if (options.fade) {
					tip.stop().fadeOut(function() { $(this).remove(); });
				} else if(tip) {
					tip.remove();
				}
			}, 150);
		});
	});
}
function autoSN() {
	return $(this).offset().top < ($(document).scrollTop() + $('.tipsy').outerHeight()) ? 'n' : 's'; 
}
$(function(){
	var switchlab = $('#switch label');
	switchlab.click(function() {
		switchlab.removeClass('selected');
		$(this).addClass('selected');
	}).tipsy({delayIn:50,gravity:autoSN,title:'for',sprite:true});
	$('#pp button').tipsy({gravity:'w'});
	$('#share a').tipsy();
	$('#sc').fancyZoom({overlay:true,width:640,height:480});
	$('#pp-zoom').fancyZoom({width:731,height:145,closeOnClick:true});
	$('a[rel="external"],#share a').click(function() {
		window.open($(this).attr('href'));
		return false;
	});
	var info = $('#info');
	info.hide();
	var trswitch = $('#switch');
	trswitch.hide();
	$('#t').linkify({extraclass:'nopad'});
	$('#type').linkify({onclick:function(caption) {
	var trsize = $('#size');
	var frmset = $('#frm fieldset');
		if(caption == 'auto') {
			info.fadeSlide(1,'show',600);
			frmset.addClass('padfix');
			trsize.hide();
			trswitch.show();
		} else {
			if(info.is(':hidden')) {
				frmset.removeClass();
				trsize.show();
			} else {
				info.fadeSlide(0,'hide',300,function() {
					if(info.is(':hidden')) { // make sure size field is always hidden when 'auto' selected
						frmset.removeClass();
						trsize.show();
					}
				});
			}
			trswitch.hide();
		}
	}});
	$('#c').linkify();
	$('#share a').click(function() {
		window.open($(this).attr('href'));
		return false;
	});
	var close = $('<a href="#" class="close" title="close">[x]</a>');
	info.find('p:first').prepend(close);
	close.click(function() {
	//$(this).parent().parent().remove();
		info.fadeSlide(0,'hide',300);
		return false;
	});
	$('#s,#i').each(function() {
	$(this).attr('title', $(this).attr('value'));
	var txt = $(this).attr('title');
	$(this).focus(function() {
		if($(this).attr('value') == txt) $(this).attr('value','');
	}).blur(function() {
		if($(this).attr('value') == '') $(this).attr('value',txt);
	});
	});
	var gen = $('#gen');
	gen.hide(); //gen.text('please type in username first');
	var imgpre = new Image();
	var img=$('<em></em>').append($(imgpre).attr('src', '/img/frontend/load.gif'));
	var time = null;
	var frmbutton = $('#frm button');
	frmbutton.removeAttr('disabled'); //make sure button is clickable after any errors
	var uinput = $('#u');
	uinput.keydown(function(){
		if(!$(this).hasClass('disabled')) {
			if(time) clearTimeout(time);
			var $$ = $(this);
			time = setTimeout(function() {
				$('h1').append(img);
				$.ajax({
					url: 'ucheck.php',
					type: 'get',
					data: $$.attr('name')+'='+$$.val(),
					success:function(r){
						$('h1').find('em').fadeOut(function() { $(this).remove().show(); });
						$$.parent().children('em').remove();
						$$.after(r);
					},
					error:function() {
						alert("ajax error");
					}
				});
			},300);
		}
	});
	$('#frm').submit(function() {
		$('h1').append(img);
		gen.show().html('<p class="load">generating images... this may take a moment (depending how many items).</p>');
		frmbutton.attr('disabled',true).addClass('disabled');
		uinput.attr('readonly',true).addClass('disabled');
		$.ajax({
			url: 'ajax'+$(this).attr('action'),
			type: $(this).attr('method'),
			data: $(this).serialize(),
			success:function(r){
				$('h1').find('em').fadeOut(function() { $(this).remove().show(); });
				gen.hide().html(r);
				var codebox = $('#codebox');
				codebox.append('<div id="overlay"><span>click here to select top albums code, then copy it and paste in \'about me\' section of your last.fm profile</span></div>');
				var overlay = $('#overlay');
				overlay.css({display: 'none', height: 0});
				var overspan = overlay.find('span');
				overspan.css({display: 'none', opacity: 0});
				gen.fadeIn(function() {
					codebox.css('position', 'relative'); // ie
					overlay.show().animate({height: '52px', paddingTop: '28px'}, 250, function() {
						overspan.show().animate({opacity: 1}, 400, function() {
							if($.browser.msie) this.style.removeAttribute('filter');
						});
					});
				});
				overlay.bind('click',function() {
					$(this).remove();
					SelectText(codebox.find('code'));
				});
			},
			error:function() { alert("ajax error"); },
			complete:function() {
				frmbutton.removeAttr('disabled').removeClass();
				uinput.removeAttr('readonly').removeClass('disabled');
			}
		});
		return false;
	});
	$.getScript('http://twitter.com/statuses/user_timeline/coversdev.json?callback=twitterCallback2&count=3');
});