var QENS_PER_DOLLAR = 800;
var page; // which page or type of page are we on
var needs_login = false;
var logged_in = false;
var IMAGE_URL = "/static/images";
var cur_overlay = 0;
var on_close_fns = [];
var posts = "";

function getIEVersion(){var rv = -1;if (navigator.appName == 'Microsoft Internet Explorer'){var ua = navigator.userAgent;var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");if (re.exec(ua) != null)rv = parseFloat( RegExp.$1 );}return rv;}
var ie = getIEVersion();

function Overlay() {}

Overlay.show = function(name, data, on_close, options) {
	cur_overlay++;
	on_close_fns.push(on_close);
	var clone = $("#overlay-template").clone();
	clone.attr("id", "overlay-" + cur_overlay);
	if (options && options.width) {
		$(".pop-over",clone).width(options.width);
	}
	$("#overlays").append(clone);
	//$(".pop-over", clone).hide();
	clone.css('z-index', '200');
	clone.show();
	resize_overlay();
	var ajx = new Ajax('/ajax/overlay/'+name, data);
	ajx.fetch(function(response) {
		$(".pop-over-body", clone).html(response.overlay);
		resize_overlay();
		//$('.pop-over', clone).show();
	});
	return false;
}

Overlay.show_map = function(location, lat, lng)
{
	data = {'location':location, 'lat':lat, 'lng':lng};
	Overlay.show('story/show_map', data);
	return false;
}

Overlay.close = function(result)
{
	var overlay = $("#overlay-" + cur_overlay);
	overlay.remove();
	var on_close = on_close_fns.pop();
	if (on_close) {
		on_close(result);
	}
	cur_overlay--;
}

// used for ordering responses
var ajax_calls_by_index = {};
var first_ajax_call = 0, last_ajax_call = 0; // last_call is one past the end

function Ajax(url, data)
{
	this.url = url;
	this.data = data;
	
	this.type = 'GET';
	
	this.parent_obj = false;
	this.pending_func = false;
	this.callback = null;
	this.done = false;
	this.error = false;
	this.result = null;
	this.jquery_ajax = null;
	this.index = 0;
	
	//methods
	this.fetch = fetch;
	this.abort = abort;
		
	function fetch(callback)
	{
		// queue object
		this.index = last_ajax_call;
		ajax_calls_by_index[last_ajax_call++] = this;
		
		// make call
		this.callback = callback;
		var obj = this;
		this.jquery_ajax = $.ajax({
			cache: false,
			url: this.url,
			data: this.data,
			type: this.type,
			obj: this,
			dataType: "text",
			beforeSend: function(x) {
				if (obj.pending_func) {
					eval(obj.pending_func);
				}
			},
			success: function(msg, textStatus, xmlHttpRequest){
				try{
					eval('var msg_json='+msg);
					this.obj.result = msg_json;
				}
				catch(e)
				{
					//alert(e);
				}
			},
			error: function(xmlHttpRequest, textStatus, errorThrown) {
				this.obj.error = true;
			},
			complete: function(xmlHttpRequest, textStatus) {
				// complete requests in order
				this.obj.done = true;
				var index = this.obj.index;				
				if (index == first_ajax_call) {
					for (var i = first_ajax_call; i < last_ajax_call; i++) {
						var call = ajax_calls_by_index[i];
						if (call.done) {
							
							// evaluate callback
							if (!call.error) {
								renderJSON(call.result, obj.parent_obj);
								if (call.result['logged_in'] == 0) {
									Overlay.show("users/signup", {}, function() {
										window.location.reload();
									});
								} else {
									if (call.callback) {
										call.callback(call.result);
									}
								}
							}
							
							// remove ajax object
							delete ajax_calls_by_index[i];
							first_ajax_call++;
						} else {
							break;
						}
					}
				}
			}
		});
	}
	
	function abort() {
		if (!this.done) {
			this.error = true;
			this.jquery_ajax.abort();
		}
	}
	
	function renderJSON(x, parent_obj)
	{
		if (x.div)
		{
			$.each(x.div, function(key, value)
			{
				if (key == "script")
				{
					eval(value);
				}
				else
				{
					var elm;
					if (parent_obj)
					{
						elm = $(parent_obj).find(key);
					}
					else
					{
						elm = $(key);
					}
					$(elm).html(value);	
				}
			});
		}
	}
}

Ajax.submit = function (form, callback)
{
	while (!form.is('form'))
	{
		form = form.parent();
	}
	var data = form.serialize();
	var type = form.attr('method').toUpperCase();
	var action = form.attr('action');
	var ajx = new Ajax(action, data);
	ajx.type = type;
	ajx.fetch(callback);
	return false;
};

// MISC UTILS //
function make_active(element, index) {
	if (!element) return;
	var ul;
	if (index) {
		ul = $('ul', element).get();
		element = $(':nth-child(' + index + 'n)', ul).get();
	} else {
		while (element.tagName != 'LI') {
			element = element.parentNode;
		}
		ul = element;
		while (ul.tagName != 'UL') {
			ul = ul.parentNode;
		}
	}
	$(element).addClass('active');
	$('li', ul).each(function(i) {
		if (this != element) {
			$(this).removeClass('active');
		}
	});
}

function make_active_2(element, index, tagname, classname) {
	if (!tagname) tagname = 'li';
	if (!classname) classname = "active";
	var child = $(tagname + ':eq(' + (index-1) + ')', element);
	if ($('.'+classname, element) != child) {
		$('.'+classname, element).removeClass(classname);
	}
	$(child[0]).addClass(classname);
}

function make_all_inactive(element, tagname, classname) {
	if (!tagname) tagname = 'li';
	if (!classname) classname = "active";
	var child = $(tagname + ':eq(' + (0) + ')', element);
	if ($('.'+classname, element) != child) {
		$('.'+classname, element).removeClass(classname);
	}
}

function make_active_sidebar(element, index) {
	var child = $(':nth-child(' + index + 'n)', element);
	if ($('.on', element) != child) {
		$('.on', element).removeClass('on');
	}
	$(child[0]).addClass('on');
}

function qAjax(url, data)
{
	var ajx = new Ajax(url, data);
	ajx.fetch();
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function require_login() {
		if (!logged_in) {
				Overlay.show("users/signup", {});
				return true;
		}
		return false;
}

function popup_window(url, name, width, height) {
	var settings = {"url": url, "name": name, "width": width, "height": height};
	var windowFeatures = "location=0,menubar=0,directories=0,toolbar=0,width=" + settings.width + ",height=" + settings.height;
	var centeredX, centeredY;
	if ($.browser.msie) {//hacked together for IE browsers
		centeredY = (window.screenTop - 120) + ((((document.documentElement.clientHeight + 120)/2) - (settings.height/2)));
		centeredX = window.screenLeft + ((((document.body.offsetWidth + 20)/2) - (settings.width/2)));
	}else{
		centeredY = window.screenY + (((window.outerHeight/2) - (settings.height/2)));
		centeredX = window.screenX + (((window.outerWidth/2) - (settings.width/2)));
	}
	var myWin = window.open(settings.url, settings.name, windowFeatures+',left=' + centeredX +',top=' + centeredY);
	myWin.focus();
	return myWin;
}

function update_location(callback) {
	var time = $.cookie("location_dirty");
	if (time) {
		if (new Date().getTime() < time) {
			var lat = $.cookie("lat");
			var lng = $.cookie("lng");
			if (lat && lng) {
				if (callback) {
					callback(lat, lng);
				}
			} else {
				if (callback) {
					callback(null, null);
				}
			}
			return;
		}
	}
	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(pos) {
			$.cookie("lat", pos.coords.latitude);
			$.cookie("lng", pos.coords.longitude);
			$.cookie("location_dirty", new Date().getTime() + 1000*60*10);
			if (callback) {
				callback(pos.coords.latitude, pos.coords.longitude);
			}
		}, function(error) {
			$.cookie("location_dirty", new Date().getTime() + 1000*60*60*2);
			if (callback) {
				callback(null, null);
			}
		},
		{maximumAge: 1000*60*10});
	} else {
		if (callback) {
			callback(null, null);
		}
	}
}

function resize_overlay() {
	var ph = $(window).height();
	$(".pop-over").each(function() {
		var ah = $(this).outerHeight();
		if (ah < 50) {
			return;
		}
		var mh = (ph - ah) / 2;
		var top = mh;
		$(this).css("top", top + "px");						
	});
}
$(".pop-over").resize(function(e) { resize_overlay(); });
if (ie <= 0) {
	$(window).resize(function() { resize_overlay(); });
}
jQuery(document).ready(function($) {
	 //Set maxlength of all the textarea (call plugin)
	 $().maxlength();
})
jQuery.fn.maxlength = function(){
	$("textarea[maxlength]").keypress(function(event){
		var key = event.which;
		//all keys including return.
		if(key >= 32 || key == 13) {
			var maxLength = $(this).attr("maxlength");
			var length = this.value.length;
			if(length >= maxLength) {
				event.preventDefault();
			}
		}
	});
	$("textarea[maxlength]").blur(function(event){
		var maxLength = $(this).attr("maxlength");
		var length = $(this).val().length;
		if (length > maxLength) {
			this.value = this.value.substring(0, maxLength);
			this.scrollTop = this.scrollHeight;
		}
	});
}

$.fn.extend({
    insertAtCaret: function(myValue){
		this.each(function() {
			if (document.selection) {
				this.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				this.focus();
			}
			else if (this.selectionStart || this.selectionStart == '0') {
				var startPos = this.selectionStart;
				var endPos = this.selectionEnd;
				var scrollTop = this.scrollTop;
				this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
				this.focus();
				this.selectionStart = startPos + myValue.length;
				this.selectionEnd = startPos + myValue.length;
				this.scrollTop = scrollTop;
			} else {
				this.value += myValue;
				this.focus();
			}
		});
    }
});

function pprint(object) {
	var output = '';
	for (property in object) {
	  output += property + ': ' + object[property]+"\n";
	}
	alert(output);
}

function preventbubble(e){
 if (e && e.stopPropagation) //if stopPropagation method supported
  e.stopPropagation()
 else
  event.cancelBubble=true
}

/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);
 
 
 
function make_tooltip(jquery_object) {
	jquery_object.tooltip({
		track: true, delay: 0, showURL: false, showBody: " - ", fade: 250
		});
	}
	
function $_GET(q,s) {
	s = (s) ? s : window.location.search;
	var re = new RegExp('&amp;'+q+'=([^&amp;]*)','i');
	return (s=s.replace(/^\?/,'&amp;').match(re)) ?s=s[1] :s='';
}
 
 
 
