// Underscore.js
// (c) 2010 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the terms of the MIT license.
// Portions of Underscore are inspired by or borrowed from Prototype.js,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function(){var n=this,A=n._,r=typeof StopIteration!=="undefined"?StopIteration:"__break__",j=Array.prototype,l=Object.prototype,o=j.slice,B=j.unshift,C=l.toString,p=l.hasOwnProperty,s=j.forEach,t=j.map,u=j.reduce,v=j.reduceRight,w=j.filter,x=j.every,y=j.some,m=j.indexOf,z=j.lastIndexOf;l=Array.isArray;var D=Object.keys,b=function(a){return new k(a)};if(typeof exports!=="undefined")exports._=b;n._=b;b.VERSION="1.0.4";var i=b.forEach=function(a,c,d){try{if(s&&a.forEach===s)a.forEach(c,d);else if(b.isNumber(a.length))for(var e=
0,f=a.length;e<f;e++)c.call(d,a[e],e,a);else for(e in a)p.call(a,e)&&c.call(d,a[e],e,a)}catch(g){if(g!=r)throw g;}return a};b.map=function(a,c,d){if(t&&a.map===t)return a.map(c,d);var e=[];i(a,function(f,g,h){e.push(c.call(d,f,g,h))});return e};b.reduce=function(a,c,d,e){if(u&&a.reduce===u)return a.reduce(b.bind(d,e),c);i(a,function(f,g,h){c=d.call(e,c,f,g,h)});return c};b.reduceRight=function(a,c,d,e){if(v&&a.reduceRight===v)return a.reduceRight(b.bind(d,e),c);a=b.clone(b.toArray(a)).reverse();return b.reduce(a,
c,d,e)};b.detect=function(a,c,d){var e;i(a,function(f,g,h){if(c.call(d,f,g,h)){e=f;b.breakLoop()}});return e};b.filter=function(a,c,d){if(w&&a.filter===w)return a.filter(c,d);var e=[];i(a,function(f,g,h){c.call(d,f,g,h)&&e.push(f)});return e};b.reject=function(a,c,d){var e=[];i(a,function(f,g,h){!c.call(d,f,g,h)&&e.push(f)});return e};b.every=function(a,c,d){c=c||b.identity;if(x&&a.every===x)return a.every(c,d);var e=true;i(a,function(f,g,h){(e=e&&c.call(d,f,g,h))||b.breakLoop()});return e};b.some=
function(a,c,d){c=c||b.identity;if(y&&a.some===y)return a.some(c,d);var e=false;i(a,function(f,g,h){if(e=c.call(d,f,g,h))b.breakLoop()});return e};b.include=function(a,c){if(m&&a.indexOf===m)return a.indexOf(c)!=-1;var d=false;i(a,function(e){if(d=e===c)b.breakLoop()});return d};b.invoke=function(a,c){var d=b.rest(arguments,2);return b.map(a,function(e){return(c?e[c]:e).apply(e,d)})};b.pluck=function(a,c){return b.map(a,function(d){return d[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,
a);var e={computed:-Infinity};i(a,function(f,g,h){g=c?c.call(d,f,g,h):f;g>=e.computed&&(e={value:f,computed:g})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);var e={computed:Infinity};i(a,function(f,g,h){g=c?c.call(d,f,g,h):f;g<e.computed&&(e={value:f,computed:g})});return e.value};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(e,f,g){return{value:e,criteria:c.call(d,e,f,g)}}).sort(function(e,f){var g=e.criteria,h=f.criteria;return g<h?-1:g>h?
1:0}),"value")};b.sortedIndex=function(a,c,d){d=d||b.identity;for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?(e=g+1):(f=g)}return e};b.toArray=function(a){if(!a)return[];if(a.toArray)return a.toArray();if(b.isArray(a))return a;if(b.isArguments(a))return o.call(a);return b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=function(a,c,d){return c&&!d?o.call(a,0,c):a[0]};b.rest=function(a,c,d){return o.call(a,b.isUndefined(c)||d?1:c)};b.last=function(a){return a[a.length-1]};
b.compact=function(a){return b.filter(a,function(c){return!!c})};b.flatten=function(a){return b.reduce(a,[],function(c,d){if(b.isArray(d))return c.concat(b.flatten(d));c.push(d);return c})};b.without=function(a){var c=b.rest(arguments);return b.filter(a,function(d){return!b.include(c,d)})};b.uniq=function(a,c){return b.reduce(a,[],function(d,e,f){if(0==f||(c===true?b.last(d)!=e:!b.include(d,e)))d.push(e);return d})};b.intersect=function(a){var c=b.rest(arguments);return b.filter(b.uniq(a),function(d){return b.every(c,
function(e){return b.indexOf(e,d)>=0})})};b.zip=function(){for(var a=b.toArray(arguments),c=b.max(b.pluck(a,"length")),d=new Array(c),e=0;e<c;e++)d[e]=b.pluck(a,String(e));return d};b.indexOf=function(a,c){if(m&&a.indexOf===m)return a.indexOf(c);for(var d=0,e=a.length;d<e;d++)if(a[d]===c)return d;return-1};b.lastIndexOf=function(a,c){if(z&&a.lastIndexOf===z)return a.lastIndexOf(c);for(var d=a.length;d--;)if(a[d]===c)return d;return-1};b.range=function(a,c,d){var e=b.toArray(arguments),f=e.length<=
1;a=f?0:e[0];c=f?e[0]:e[1];d=e[2]||1;e=Math.ceil((c-a)/d);if(e<=0)return[];e=new Array(e);f=a;for(var g=0;;f+=d){if((d>0?f-c:c-f)>=0)return e;e[g++]=f}};b.bind=function(a,c){var d=b.rest(arguments,2);return function(){return a.apply(c||{},d.concat(b.toArray(arguments)))}};b.bindAll=function(a){var c=b.rest(arguments);if(c.length==0)c=b.functions(a);i(c,function(d){a[d]=b.bind(a[d],a)});return a};b.memoize=function(a,c){var d={};c=c||b.identity;return function(){var e=c.apply(this,arguments);return e in
d?d[e]:(d[e]=a.apply(this,arguments))}};b.delay=function(a,c){var d=b.rest(arguments,2);return setTimeout(function(){return a.apply(a,d)},c)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(b.rest(arguments)))};b.wrap=function(a,c){return function(){var d=[a].concat(b.toArray(arguments));return c.apply(c,d)}};b.compose=function(){var a=b.toArray(arguments);return function(){for(var c=b.toArray(arguments),d=a.length-1;d>=0;d--)c=[a[d].apply(this,c)];return c[0]}};b.keys=D||function(a){if(b.isArray(a))return b.range(0,
a.length);var c=[];for(var d in a)p.call(a,d)&&c.push(d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=function(a){return b.filter(b.keys(a),function(c){return b.isFunction(a[c])}).sort()};b.extend=function(a){i(b.rest(arguments),function(c){for(var d in c)a[d]=c[d]});return a};b.clone=function(a){if(b.isArray(a))return a.slice(0);return b.extend({},a)};b.tap=function(a,c){c(a);return a};b.isEqual=function(a,c){if(a===c)return true;var d=typeof a;if(d!=typeof c)return false;
if(a==c)return true;if(!a&&c||a&&!c)return false;if(a.isEqual)return a.isEqual(c);if(b.isDate(a)&&b.isDate(c))return a.getTime()===c.getTime();if(b.isNaN(a)&&b.isNaN(c))return false;if(b.isRegExp(a)&&b.isRegExp(c))return a.source===c.source&&a.global===c.global&&a.ignoreCase===c.ignoreCase&&a.multiline===c.multiline;if(d!=="object")return false;if(a.length&&a.length!==c.length)return false;d=b.keys(a);var e=b.keys(c);if(d.length!=e.length)return false;for(var f in a)if(!(f in c)||!b.isEqual(a[f],
c[f]))return false;return true};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(p.call(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=l||function(a){return!!(a&&a.concat&&a.unshift&&!a.callee)};b.isArguments=function(a){return a&&a.callee};b.isFunction=function(a){return!!(a&&a.constructor&&a.call&&a.apply)};b.isString=function(a){return!!(a===""||a&&a.charCodeAt&&a.substr)};b.isNumber=function(a){return a===
+a||C.call(a)==="[object Number]"};b.isBoolean=function(a){return a===true||a===false};b.isDate=function(a){return!!(a&&a.getTimezoneOffset&&a.setUTCFullYear)};b.isRegExp=function(a){return!!(a&&a.test&&a.exec&&(a.ignoreCase||a.ignoreCase===false))};b.isNaN=function(a){return b.isNumber(a)&&isNaN(a)};b.isNull=function(a){return a===null};b.isUndefined=function(a){return typeof a=="undefined"};b.noConflict=function(){n._=A;return this};b.identity=function(a){return a};b.times=function(a,c,d){for(var e=
0;e<a;e++)c.call(d,e)};b.breakLoop=function(){throw r;};b.mixin=function(a){i(b.functions(a),function(c){E(c,b[c]=a[c])})};var F=0;b.uniqueId=function(a){var c=F++;return a?a+c:c};b.templateSettings={start:"<%",end:"%>",interpolate:/<%=(.+?)%>/g};b.template=function(a,c){var d=b.templateSettings,e=new RegExp("'(?=[^"+d.end.substr(0,1)+"]*"+d.end.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")+")","g");d=new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+a.replace(/[\r\t\n]/g,
" ").replace(e,"\t").split("'").join("\\'").split("\t").join("'").replace(d.interpolate,"',$1,'").split(d.start).join("');").split(d.end).join("p.push('")+"');}return p.join('');");return c?d(c):d};b.each=b.forEach;b.foldl=b.inject=b.reduce;b.foldr=b.reduceRight;b.select=b.filter;b.all=b.every;b.any=b.some;b.head=b.first;b.tail=b.rest;b.methods=b.functions;var k=function(a){this._wrapped=a},q=function(a,c){return c?b(a).chain():a},E=function(a,c){k.prototype[a]=function(){var d=b.toArray(arguments);
B.call(d,this._wrapped);return q(c.apply(b,d),this._chain)}};b.mixin(b);i(["pop","push","reverse","shift","sort","splice","unshift"],function(a){var c=j[a];k.prototype[a]=function(){c.apply(this._wrapped,arguments);return q(this._wrapped,this._chain)}});i(["concat","join","slice"],function(a){var c=j[a];k.prototype[a]=function(){return q(c.apply(this._wrapped,arguments),this._chain)}});k.prototype.chain=function(){this._chain=true;return this};k.prototype.value=function(){return this._wrapped}})();

if(!window['Chomp']) var Chomp = {};

//Class-based inheritance plugin for jquery, care of Dan Webb
(function($){
	var addMethods = function(source) {
		var ancestor   = this.superclass && this.superclass.prototype;
		var properties = _.keys(source);

		if (!_.keys({ toString: true }).length) properties.push("toString", "valueOf");

		for (var i = 0, length = properties.length; i < length; i++) {
			var property = properties[i], value = source[property];
			if (ancestor && $.isFunction(value) && $.argumentNames(value)[0] == "$super") {

			var method = value, value = $.extend($.wrap((function(m) {
			  return function() { return ancestor[m].apply(this, arguments) };
			})(property), method), {
			  valueOf:  function() { return method },
			  toString: function() { return method.toString() }
			});
			}
			this.prototype[property] = value;
		}

		return this;
	}

	$.extend({
		argumentNames: function(func) {
			var names = func.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(/, ?/);
			return names.length == 1 && !names[0] ? [] : names;
		},
		wrap: function(func, wrapper) {
			var __method = func;
			return function() {
				return wrapper.apply(this, [$.proxy(__method, this)].concat($.makeArray(arguments)));
			}
		},
		klass: function() {
			var parent = null, properties = $.makeArray(arguments);
			if ($.isFunction(properties[0])) parent = properties.shift();

			var klass = function() {
			this.initialize.apply(this, arguments);
			};

			klass.superclass = parent;
			klass.subclasses = [];
			klass.addMethods = addMethods;

			if (parent) {
			var subclass = function() { };
			subclass.prototype = parent.prototype;
			klass.prototype = new subclass;
			parent.subclasses.push(klass);
			}

			for (var i = 0; i < properties.length; i++)
			klass.addMethods(properties[i]);

			if (!klass.prototype.initialize)
			klass.prototype.initialize = function() {};

			klass.prototype.constructor = klass;

			return klass;
		}
	});

})(jQuery);

Chomp.autocomplete_item_tmpl = '<a><% if(icon){ %><img src="<%= icon %>"><% } %><%= label %><% if(type){ %><span class="autocomplete-topic-label"><%= type %></span><% } %></a>';
//extend jquery.ui.autocomplete a bit
$.widget("custom.topicComplete", $.ui.autocomplete, {
	_initSource: function() {
		this.requesting = false;
		this.current_request = null;
		var url = this.options.source;
		this.source = _.bind(function( request, response ) {
			if(this.requesting && this.current_request){
				this.current_request.abort();
				this.requesting = false;
			}
			this.current_request = $.getJSON( url, request, response );
			this.requesting = true;
			
		}, this);
	},
	_renderItem: function( ul, item) {
		var el = document.createElement('li');
		var a = _.template(Chomp.autocomplete_item_tmpl, {
			label: Chomp.hilite(item.label),
			icon: item.icon_url,
			type: (item.type && item.type != 'see_more') ? ((item.type =='word') ? 'topic': item.type ): ''
		});
		el.innerHTML = a;
		$(el).data( "item.autocomplete", item ).appendTo( ul );
		return el;
	},
	_response: function( content ) {
		this.requesting = false;
		this.current_request = null;
		if ( content && content.length ) {
			content = this._normalize( content );
			this._suggest( content );
			this._trigger( "open" );
		} else {
			this.close();
		}
		this.element.removeClass( "ui-autocomplete-loading" );
	},
	_normalize: function( items ) {
		var results = (items.length >= 10) ? _.first(items, 10) : items;
		results.push({
			label: 'Search for "'+this.term+'" &raquo;',
			value: this.term,
			type: 'see_more'
		});
		return results;
	}
});

// `onload` is an object that can be extended to hold all relevant onload bindings.
// Additional javascript files can extend `onload`, such as: 
// onload.developer = function(){ };
// Then, a template can call the appropriate `onload` functions when necessary, e.g.:
// $(function(){ onload.developer(); });
// The advantage here is that the onload events won't need to be written inline on each template.
// They can be shared and cached, and only the call can be included inline on the template.
Chomp.init = {
	'core': function() {
        
		var i = document.createElement('input'); // text for placeholder html5 support
		if (!('placeholder' in i)) {
			$('input[placeholder]:not([value])').filter(function() {
                return ((!$(this).val() && !$(this).hasClass('alt_placeholder')) || ($(this).val() == $(this).attr('placeholder')));
            }).each(function(i, el) {
				$(this).val($(this).attr('placeholder'));
			}).addClass('default').focus(function(e) {
				if ($(this).hasClass('default')) {
					$(this).val('').removeClass('default');
				}
			}).blur(function(e) {
				var $this = $(this);
				if ($.trim($this.val()) == '') {
					$this.val($this.attr('placeholder')).addClass('default');
				}
			});
		}
		
		$('p.success, p.error').live('click', function() {
			$(this).slideUp('slow', function() {
				$(this).text('').addClass('hidden');
			});
		});

		$('.alt_placeholder').each(Chomp.altPlaceholder);

		var q = $('#id_query');
		q.topicComplete({
			delay:200,
			source: '/api/autocomplete',
			select: function(e, li){
				var data = li.item.value;
				if(data){
					//delay to allow updating of form field value before submit.
					_.delay(function(){e.target.form.submit()}, 100);
				}
			},
			close: function(event, ui){
				Chomp.startedAC = false;
			}
		});
		q.bind('keydown', function(e){
			if((e.which >= 48 && e.which <= 90) && !Chomp.startedAC){
				$('.ui-autocomplete').html('<img src="/img/bar-loader.gif" class="loader">');
				$('.ui-autocomplete').show().position({
					my: "left top",
					at: "left bottom",
					of: q,
					collision: "none"
				});
				Chomp.startedAC = true;
			}
		});
	}
}

Chomp.loadBearhug = function(){
	var loadit = function(){
		bearhug.widget.overlay.button({"id":"34fc28a917c466d8a435a4074ca967c20f904135","position":{"top":200,"left":0}});
	};
	
	var s = document.createElement('script');
	s.type = 'text/javascript';
	s.src = 'http://chomp.bearhugapp.com/media/js/widget-overlay.js';
	document.body.appendChild(s);

	s.onreadystatechange = function(){
		if (s.readyState == 'loaded' || s.readyState == 'complete')
			loadit();
	};
	s.onload = loadit;
};

//fake placeholder text display so we can have the cursor
//appear in the search box along with placeholder text on load.
Chomp.altPlaceholder = function(){
	var input = $(this);
	var placeholder_text = input.attr('placeholder');

	if(this.value =='' && placeholder_text){
		input.attr('placeholder', '');
		//only autofocus if there are no other default actions on page
		if(!window.location.hash)
			this.focus();
			
		var placeholder = $('<div class="placeholder">'+placeholder_text+'</div>');
		placeholder.appendTo(input.parent('form')).click(function(){
			input.focus();
		});
		input.keyup(function(){
			if(this.value !='')
				placeholder.hide();
		}).blur(function(){
			if(this.value == '')
				placeholder.show();
		}).focus(function(){
			placeholder.hide();
		});
	}
};

Chomp.hiliteRE = new RegExp(/{{(.*?)}}/g);
Chomp.hilite = function(s){
	var replaced = s.replace(Chomp.hiliteRE, '<em class="hilite">$1</em>');
	return replaced;
};

Chomp.trackPageview = function(link){
	var match = link.href.match(/^http:\/\/(.*?)(\/[a-z|0-9/]+)$/i);
	var url = (match && match.length >=3) ? match[2] : link.href;
	_gaq.push(['_trackPageview', url]);
	if($(link).attr('target') == '_blank')
		window.open(link.href);
	else
		setTimeout('window.location = "' + link.href + '"', 200);
};

Chomp.trim = function(str){
	var out = str || '';
	if(out){
		out = str.replace(/^\s+|\s+$/g, '');
	}
	return out;
};

Chomp.parseQueryStr = function(s){
	var hash = {};
    var match = s.match(/([^?#]*)(#.*)?$/);
    if (!match) return hash;

	_.each(match[1].split('&'), function(pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift()),
            value = pair.length > 1 ? pair.join('=') : pair[0];
            
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (!_.isArray(hash[key])) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      
    });
    return hash;
};

Chomp.hoverBox = $.klass({
	initialize: function(el, url, callback, optional){
		this.src_element = $(el);
		this.src_url = url;
		this.id = this.src_element.attr('data-app-id');
		this.element = $('<div class="hover_box"><div class="caret"></div></div>');//container element for hover_box
		this.opened = false;
		this.over = false;
		this.dataCallback = (!!callback) ? _.bind(callback, this) : this.defaultDataCallback;
		this.start_width = $(window).width();
		
		this.optional = optional || {};
		this.data = this.optional.data || null;

		if(this.data && this.optional.autoload_data)
			this.dataCallback();

		if(this.optional.use_click){
			this.src_element.bind('click', $.proxy(this.click, this));
		}else{
			this.src_element.bind('mouseenter', $.proxy(this.hover, this));
		}
		this.src_element.bind('mouseleave', $.proxy(this.mouseleave, this));
	},
	hover: function(e){
		this.over = true;
		_.delay(_.bind(this.checkOver, this), 400);
	},
	checkOver:function(){
		if(this.over)
			this.getData();
	},
	mouseleave: function(){
		this.over = false;
		var that = this;
		_.delay(function(){
			if(that.opened && !that.over)
				that.hide(false);
		}, 100);
	},
	getData: function(){
		if(!this.opened){
			if(!this.data){
				var callback = _.bind(function(data){
					this.data = data;
					this.dataCallback();
					this.setEvents();
					this.show();
				}, this);
				
				$.getJSON(this.src_url,'app_id='+this.id, callback);
			}else{
				this.show();
			}
		}
	},
	click: function(e){
		e.preventDefault();
		if(!this.data){
			this.getData();
		}else{
			this.show();
		}
	},
	setEvents: function(){
		this.element.bind('mouseenter', $.proxy(function(){this.over = true;}, this));
		this.element.bind('mouseleave', $.proxy(this.mouseleave, this));
		var close = this.element.find('.close');
		if(close.length > 0)
			close.click($.proxy(this.hide, this));
	},
	defaultDataCallback: function(){
		var inner_content = $('<div class="hover_box_inner"></div>').append(this.data);
		this.element.append(inner_content);
		$(document.body).append(this.element);
		this.setEvents();
		this.element.hide();
	}, 
	show: function(){
		if(this.element){
			var position = this.src_element.offset(),
			box_size = {h: this.element.innerHeight(), w: this.element.innerWidth()},
			left = 0, top = 0;

			if(this.optional.offset){
				if(this.optional.offset == 'centered'){
					var src_size = {h: this.src_element.innerHeight(), w: this.src_element.innerWidth()};
					left = src_size.w/2;
					top = src_size.h/2;
				}else{
					left = this.optional.offset.left;
					top = this.optional.offset.top;
				}
			}

			
			if( (this.start_width - (position.left + this.src_element.width())) < box_size.w ){
				this.element.addClass('left');
				left = (position.left - (this.src_element.width()/2)) + 30 - left;
			}else{
				this.element.addClass('right');
				left += (position.left + (this.src_element.width() - (box_size.w/2))) - 30;
			}

			//the extra 20px here is for the caret height
			if( (position.top - $(window).scrollTop()) > box_size.h ){
				top += (position.top - box_size.h - 20); 
				this.element.addClass('top');
			}else{
				top = (position.top + this.src_element.height() + 20) - top;
				this.element.addClass('bottom');
			}

			this.element.css({
				'left': left + 'px',
				'top': top + 'px',
				'display': 'block'
			});

			this.opened = true;
			var hide_delay = _.bind(function(){
                if(this.opened)
                    this.hide(null);
            }, this);
            _.delay(hide_delay, 7000);
		}
	},
	hide: function(e){
		if(e)
			e.preventDefault();
		this.element.css('display', 'none');
		this.element.removeClass('top bottom left right');
		this.opened = false;
	}
});

Chomp.get_app_for_social_desc = 'Our apologies, but currently you must <strong><a href="/s/_chomp">download the Chomp iPhone app</a></strong> in order to follow users,\
 rate apps, or get personalized recommendations. We\'ll be adding these features to the website soon.';

$(document).ready(function() {
	Chomp.init.core();
});

