// $(function() {
// 	$('#venue_title').autocomplete({
// 		source: function(request, response) { 
// 			$.ajax({
// 				url: "/venues.json",
// 				datatype: "json",
// 				data: {	title: request.term },
// 
// 				success: function(data) {
// 					response($.map(data, function(item) {
// 						return { label: item.venue.title, value: item.venue.title	}
// 					}))
// 				}
// 			});
// 		},
// 
// 		minLength: 1
// 	});
// });

var TQ; if (!TQ) TQ = {}; if (!TQ.ui) TQ.ui = {}; if (!TQ.login) TQ.login = {};
TQ.login_visible = false;
TQ.redirect = '';
TQ.POSITIVE = "OMG!";
TQ.NEGATIVE = "WTF?";

Function.prototype.delay = function() {
	var __method = this
	var timeout = arguments[0];
	var args = arguments;
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
	}

TQ.ui.init = function() {
	new TQ.ui.ChangeLocation();
	TQ.ui.initAjax();
	TQ.ui.initCheckBoxes();
	TQ.login.init();
	$('.close a').click(function() {
		$(this).parents('.closable').hide('normal');
	});
}


TQ.login.init = function(e){
	$('#ajax_login').ajaxForm(function(req){
		 var msg = $.secureEvalJSON(req);
		 if(msg.success){
		 	$('#login_box').dropOut(TQ.ui.hideLogin);
			TQ.login.initLoggedIn(msg.user);
		 }
		 else {
		 	var error = $('<p id=\"error\">' + msg.message + '</p>');
			$('#ajax_login').before(error);
			$('#error').effect("highlight", {}, 400);
		 }
	});
	$('#login_box').onClickOutside(function(){
		if(TQ.login_visible){
			$('#login_box').dropOut(TQ.ui.hideLogin);
		}
	});
	
	$('#login_btn').click(function(e){
		e.preventDefault();
		if (!TQ.login_visible) {
			$('#login_box').dropIn(TQ.ui.showLogin);
			$('#login_input').focus();
		}
	});
	
	$('#close a').click(function(e){
		$('#login_box').dropOut(TQ.ui.hideLogin);
	});
}



TQ.ui.initAjax = function() {
	$(document).ajaxSend(function(event, request, settings) {
	  if (typeof(TQ.AUTH_TOKEN) == "undefined") return;
	  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
	  if (settings.type == "POST") {
			settings.data = settings.data || "";
			settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(TQ.AUTH_TOKEN);
		}
	});
	
	jQuery.ajaxSetup({ 
	  	'beforeSend': function(xhr) {
			    xhr.setRequestHeader("Accept", "text/javascript,text/json");
			} 
	});

}

TQ.ui.initCheckBoxes = function() {
	$('#search_box input[type="radio"]').checkbox({cls: 'search-checkbox', empty: '/stylesheets/empty.png'});
}

TQ.ui.ChangeLocation = function() {
	$('#change_location a').click(function(e){
		e.preventDefault();
		$('#cities_list ol').toggle('fast');
	});
}

TQ.login.initLoggedIn = function(user) {
	$('#login').hide();
	$('#register').hide();
	$('#nav').append(TQ.login.logout_link()).append(TQ.login.profile_link(user));
	TQ.logged_in = true;
}

TQ.login.logout_link = function() {
	var li = '<li id="logout"><a href="/logout">Logout</a></li>';
	return $(li);
}

TQ.login.profile_link = function(user) {
	var li = '<li id="profile"><a href="/users/' + user + '">Profile</a></li>';
	return $(li); 
}


TQ.login.requireLogin = function(e) {
if (!TQ.logged_in) {
			e.preventDefault();
			TQ.redirect = e.target.href;
			if(!TQ.login_visible)
				$('#login_box').dropIn(TQ.ui.showLogin);
		}
}

TQ.ui.eventLink = function(){
	var link = '/events/' + event.id
	return link;
}

TQ.ui.userLink = function(data){
	var link = '<a href=';
	data.asset = data.image || data.video;
	if(data.asset.viewable_type == "Event")
		 link += '"/users/' + data.asset.user_id + '">' + data.asset.poster.user_info.name + '</a>';
	else if(data.asset.viewable_type == "Venue")
		 link += '"/users/' + data.asset.user_id + '">' + data.asset.poster.user_info.name + '</a>';
	return link;
}

TQ.ui.eventOrVenue = function(data){
	var link = '<a class="link_color_2" href=';
	data.asset = data.image || data.video;
	if(data.asset.viewable_type=="Event")
		 link += '"/events/' + data.asset.viewable_id + '">' + data.asset.viewable.event.title + '</a>';
	else if(data.asset.viewable_type == "Venue")
		 link += '"/venues/' + data.asset.viewable_id + '">' + data.asset.viewable.venue.title + '</a>';
	return link;
}

TQ.ui.hideLogin = function() {
	TQ.login_visible = false;
		$('#error').hide();
}

TQ.ui.showLogin = function() {
	TQ.login_visible = true;
}

TQ.ui.starRateResult = function(data) {
	var response = '';
	if (data.success)
		response += data.rating_average + ' rating from ' + data.rated_total + ' vote';
	else
		response += data.message;
	return response
}


TQ.ui.Comment = function() {
	this.initEvents();
}

TQ.ui.Comment.prototype.initEvents = function() {
	var that = this;
	$('.comments_list li.clearfix').hover(that.onMouseOver, that.onMouseOut);
	$('.comments_list button.delete').bind('click', {inst: that}, that.onDelete);
}

TQ.ui.Comment.prototype.onMouseOver = function(e){
	$('.comments_list form.delete').hide();
	$(e.target).find('form.delete').show();
}

TQ.ui.Comment.prototype.onMouseOut = function(e){
	$(e.target).find('form.delete').hide();
}

TQ.ui.Comment.prototype.onDelete = function(e){
	e.preventDefault();
	var that = e.data.inst;
	var target = e.target;
	$(e.target).parent('.delete').ajaxSubmit(function(req) {
		if ($.secureEvalJSON(req).success) {
			$(target).parents('li.clearfix').fadeOut();
		}
	})
}

TQ.ui.VenuePopup = function(options) {
	this.defaults = {
		template: "<h2>#{title}</h2><p><img src='/venue_photos/#{photo_id}/thumb/#{photo_file_name}' /> #{address_line1} #{city}, #{state}</p>",
		container: 'body',
		template_name: 'popup_template',
		offsetX: 10,
		offsetY: 10
	}
	this.options = $.extend(this.defaults, options);
	$.template(this.options.template_name, this.options.template);
	this.popup = $('body').append($('<div id="venue_popup"></div>'));
	this.initEvents();
}
TQ.ui.VenuePopup.prototype.initEvents = function() {
	var that = this;
	$('.event_venue').bind('mouseover', {inst: that}, that.onHover).bind('mousemove', {inst: that}, that.update)
	.bind('mouseout', {inst: that}, that.hide);
}

TQ.ui.VenuePopup.prototype.onHover = function(e) {
	var that = e.data.inst;
	var target = e.target;
	var event = e;
	e.preventDefault();
	$('#venue_popup').empty();
	that.show(e);
	that.block($('#venue_popup'));
	$.get(e.target.href, function(req){
		that.insert(($.template(that.options.template_name, that.buildObject($.secureEvalJSON(req)))));
		
	})
}

TQ.ui.VenuePopup.prototype.block = function(el){
	$(el).append('<div class="blockMsg"></div>');
}

TQ.ui.VenuePopup.prototype.insert = function(info) {
	$('#venue_popup').html(info)
}

TQ.ui.VenuePopup.prototype.show = function(e){
	var that = e.data.inst;
	var left = e.pageX + that.options.offsetX;
	var top = e.pageY - that.options.offsetY - $('#venue_popup').outerHeight();
	$("#venue_popup").css({left: left, top: top});
	this.update(e);
	$('#venue_popup').show();
	
}

TQ.ui.VenuePopup.prototype.hide = function(e) {
	$("#venue_popup").hide();
}

TQ.ui.VenuePopup.prototype.viewport = function() {
	return {
		x: $(window).scrollLeft(),
		y: $(window).scrollTop(),
		cx: $(window).width(),
		cy: $(window).height()
	};
}

TQ.ui.VenuePopup.prototype.update = function(e) {
	var that = e.data.inst;
	var left = $('#venue_popup')[0].offsetLeft;
	var top = $('#venue_popup')[0].offsetTop;
	var v = that.viewport(),
		h = $('#venue_popup');
	if (e) {
			// position the helper 15 pixel to bottom right, starting from mouse position
			left = e.pageX + that.options.offsetX;
			top = e.pageY + that.options.offsetY;
			var right='auto';
/*
			$('#venue_popup').css({
				left: left,
				right: right,
				top: top
			});
*/
		}
	// check horizontal position
		if (v.x + v.cx < left + h[0].offsetWidth) {
			left -= h[0].offsetWidth + 20 + that.options.offsetX;
			$('#venue_popup').addClass("viewport-right");
			//$('#venue_popup').css({top: top, left: left});
		}
		// check vertical position
		if (v.y + v.cy < top + h[0].offsetHeight) {
			top -= h[0].offsetHeight + 20 + that.options.offsetY;
			$('#venue_popup').addClass("viewport-bottom");
			//$('#venue_popup').css({top: top, left: left});
		}
		
	$('#venue_popup').css({
				left: left,
				right: right,
				top: top
			});
		
	
}

TQ.ui.VenuePopup.prototype.buildObject = function(item){
	var obj = {};
	obj.title = item["venue"]["title"];
	obj.address_line1 = item["venue"]["address_line1"];
	obj.address_line2 = item["venue"]["address_line2"];
	obj.city = item["venue"]["city"];
	obj.state = item["venue"]["state"];
	if (item["venue"].venue_photos.length > 0) {
		obj.photo_file_name = item["venue"]["venue_photos"][0].venue_photo.venue_photo_file_name;
		obj.photo_id = item["venue"]["venue_photos"][0].venue_photo.id;
	}
	return obj
}


TQ.ui.JsonLoader = function(options){
	var template = '<div class="featured_venue">';
	 	template += '<div class="featured_venue_photo">';
		template += '<div class="featured_venue_photo_details clearfix">';
		template +=	'<h3 class="featured_bar">Featured Bar:</h3>';
		template +=	'<p><a href="/venues/#{id}">#{title}</a></p>';
		template +=	'</div>';
		template +=	'<a href="/venues/#{id}"><img src="http://s3.amazonaws.com/thequeerist/attachments/#{asset_id}/bw_large/#{attachment_file_name}" /></a>';
		template +=	'</div>';
		template +=	'<div class="pad_fix_left_right">';
		template +=	'<p>#{description} <a href="/venues/#{id}">View Details</a></p>';
		template += '</div>';
		template += '</div>';
		
	
	this.defaults = {
		template: template,
		insertInto: '#featured_venue'
	}
	this.options = $.extend(this.defaults,options);
	$.template('venue_template', template);
}

TQ.ui.JsonLoader.prototype.render = function(obj) {
	$(this.options.insertInto).html(this.eval(obj))
}

TQ.ui.JsonLoader.prototype.eval = function(obj){
	return $.template('venue_template', obj);
}


TQ.ui.Map = function(obj) {
	this.options = {};
	this.options.obj = obj;
	var that = this;
	$('.map_link').click(function(e) {
		e.preventDefault();
		$('#map_container').toggle('normal');
		map.checkResize();
		
		map.setCenter(that.bounds.getCenter(), 15);
	});
	if(GBrowserIsCompatible() && typeof this.options.obj != 'undefined'){
		var map = new GMap2(document.getElementById('map'));
		map.setCenter(new GLatLng(37.4419, -122.1419), 15);
		map.setZoom(15);
		map.addControl(new GLargeMapControl());
		
		function createMarker(latlng, obj){
			var marker = new GMarker(latlng)
			var html = "<strong>" + obj.title + "</strong><br />" + obj.address_line1 + "<br />" + obj.city + ", " + obj.state;
			GEvent.addListener(marker, "click", function() {
				map.openInfoWindowHtml(latlng, html);
			});
			return marker;
		}
		
		this.bounds = new GLatLngBounds;
		var latlng = new GLatLng(this.options.obj.lat, this.options.obj.lng);
		this.bounds.extend(latlng)
		map.addOverlay(createMarker(latlng, this.options.obj));
		map.setCenter(this.bounds.getCenter(), map.getBoundsZoomLevel(this.bounds));
	}
}

TQ.ui.Carousel = function(el, options){
	this.options = options;
	this.itemList = $(this.options.items);
	this.li_list = $(this.options.containers);
	var that = this;
	if(this.itemList.length > 7)
		$(el).jcarousel({
				wrap: "circular",
				scroll: 3,
				itemVisibleInCallback: {
		  		onBeforeAnimation: itemVisibleInCallback
		  	},
		  	itemVisibleOutCallback: {
		  		onAfterAnimation: itemVisibleOutCallback
		  	}
			});
	else
		this.li_list.click(this.options.onClick || null);
	function itemVisibleOutCallback(carousel, item, i, state, evt) {
		 carousel.remove(i);
	}
	
	function carouselGetIndex(item) {
		for (var i = 0; i < that.itemList.length; i++) {
		if ($(item).children('a')[0] == $(that.li_list[i]).children('a')[0]) 
			return i;
	}
	}
	function itemVisibleInCallback(carousel, item, i, state, evt){
		// The index() method calculates the index from a
		// given index who is out of the actual item range.
		var idx = carousel.index(i, that.itemList.length);
		carousel.add(i, that.itemList[idx - 1]).click(that.options.onClick || null);
	}
}

TQ.ui.Carousel.onClick = function(e){
	e.preventDefault();
	if ($(this).attr('jcarouselindex')) {
		var number = ($(this).attr('jcarouselindex') % parseInt($('#total').text()) == 0) ? parseInt($('#total').text()) : $(this).attr('jcarouselindex') % parseInt($('#total').text());
		if (number < 0) 
			number = parseInt($('#total').text()) + number;
	}
	else {
		var number = $('#images_carousel li').index($(this)) + 1;
	}
	$.get($(this).find('a').attr('href'), function(req){
			var response = $.secureEvalJSON(req);
			if(response.image){
			var img = document.createElement('img')
			img.src = ('http://s3.amazonaws.com/thequeerist/attachments/' + response.image.id + '/large/' + response.image.attachment_file_name);
			if($("#current_photo object").size() > 0){
				
				$("#current_photo object").fadeOut(function(){
					$(this).remove();
					$("#current_photo").append(img);
					$('#index').text(number);
					$('#from').html('From: ' + TQ.ui.eventOrVenue(response));
					$('#posted_by').html('Posted by ' + TQ.ui.userLink(response))
				});
			}
			if($('#current_photo img').attr('src') != img)
				$('#current_photo img').fadeTo(img, {
					postFade: function() {
						
						$('#index').text(number);
						$('#from').html('From: ' + TQ.ui.eventOrVenue(response));
						$('#posted_by').html('Posted by ' + TQ.ui.userLink(response))
					}
				});
			}
		else if(response.video){
			$('#current_photo').append($('<div id="flash_container"></div>'))
			$('#current_photo img').remove();
			var flash_params = {
				MM_ComponentVersion:1,
				skinName:"/flash/Clear_Skin_2",
				streamName:"http://s3.amazonaws.com/thequeerist/attachments/" + response.video.id + '/original/' + response.video.attachment_file_name.replace(/\.[\w]*/, ".flv"),
				autoPlay: true,
				autoRewind: false
			}
			swfobject.embedSWF("/flash/FLVPlayer_Progressive.swf", "flash_container", "398", "294", "9.0.0", false, flash_params);
			$('#index').text(number);
			$('#from').html('From: ' + TQ.ui.eventOrVenue(response));
			$('#posted_by').html('Posted by ' + TQ.ui.userLink(response))
		}
		});
}

TQ.ui.Carousel.onVenueClick = function(e){
	e.preventDefault();
	if ($(this).attr('jcarouselindex')) {
		var number = ($(this).attr('jcarouselindex') % parseInt($('#total').text()) == 0) ? parseInt($('#total').text()) : $(this).attr('jcarouselindex') % parseInt($('#total').text());
		if (number < 0) 
			number = parseInt($('#total').text()) + number;
	}
	else {
		var number = $('#venue_photos_carousel li').index($(this)) + 1;
	}
	$.get($(this).find('a').attr('href'), function(req){
		var response = $.secureEvalJSON(req);
		if(response.venue_photo)
			var img = '/venue_photos/' + response.venue_photo.id + '/large/' + response.venue_photo.venue_photo_file_name;
		else if(response.event_photo)
			var img = '/images/' + response.event_photo.id + '/large/' + response.event_photo.event_photo_file_name;
		$('#current_photo img').fadeTo(img, {
			postFade: function() {
				$('#from').html('From: ' + TQ.ui.eventOrVenue(response));
				$('#posted_by').html('Posted by ' + TQ.ui.userLink(response))
				$('#index').html(number);
			}
		});
	});
}

TQ.ui.CustomCategoryInput = function(el, model) {
	var that = this;
	this.input = "<input type='text' style='width: 75px;' name='" + model + "[custom_categories][]' />";

		$('#' + el).bind('check', {
			inst: that
		}, that.onClick);
		$('#' + el).bind('uncheck', {
			inst: that
		}, that.onClick);
	}

TQ.ui.CustomCategoryInput.prototype.onClick = function(e){
	var that = e.data.inst;
	if($(this).parent('li').find('input[type="text"]').is(":visible"))
		that.remove(e);
	else
		that.insert(e);	
}

TQ.ui.CustomCategoryInput.prototype.remove = function(e){
	$(e.target).parent('li').find('input[type="text"]').hide().val("");
}

TQ.ui.CustomCategoryInput.prototype.insert = function(e){
	var that = e.data.inst;
	$(e.target).parent('li').find('input[type="text"]').show();
} 



function fixExternalLinks() {
	var a = document.getElementsByTagName('a');
	for(var i=0; i<a.length; i++) {
		if (a[i].getAttribute('href') && (a[i].getAttribute('href').indexOf('http') == 0) && (a[i].getAttribute('href').toString().indexOf(window.location.host) == -1)) {
		a[i].onclick = function(event){
			var event = event || window.event;
			if (event.preventDefault) 
				event.preventDefault();
			if (event.cancelBubble) 
				event.cancelBubble = true;
			window.open(this.href);
			return false;
		}
	}
	}
}
 


/** on DOM ready **/
$(function(){
	if (!TQ.logged_in) {
		$.getScript("/javascripts/ui/effects.highlight.js");
		$.getScript("/javascripts/jquery.json-1.2.js");
		$('.require_login').click(function(e){
			//console.log('clicked');
			TQ.login.requireLogin(e);
		});
	}
	fixExternalLinks();
	TQ.ui.init();
});




 

1/*
2 parseUri 1.2.1
3 (c) 2007 Steven Levithan <stevenlevithan.com>
4 MIT License
5*/

function parseUri (str) {
 var o = parseUri.options,
 m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
 uri = {},
 i = 14;

 while (i--) uri[o.key[i]] = m[i] || "";

 uri[o.q.name] = {};
 uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
 if ($1) uri[o.q.name][$1] = $2;
 });

 return uri;
};

parseUri.options = {
 strictMode: false,
 key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
 q: {
 name: "queryKey",
 parser: /(?:^|&)([^&=]*)=?([^&]*)/g
 },
 parser: {
 strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
 loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
 }
};

/** custom jquery extensions **/


(function($){
	$.viewportHeight = function(){
		var h = 0;
		if (typeof(window.innerHeight) == "number") {
			h = window.innerHeight;
		}
		else {
			if (document.documentElement && document.documentElement.clientHeight) {
				h = document.documentElement.clientHeight;
			}
			else {
				if (document.body && document.body.clientHeight) {
					h = document.body.clientHeight;
				}
			}
		}
		return h;
	}
})(jQuery);


(function($){
	
	$.fn.center = function(options){
		var defaults = {
			to: window
		}
		var options = $.extend(defaults, options);
		this.each(function(i, el){
			$(el).css('top', (jQuery.viewportHeight()/2 + $(window).scrollTop()));
		});
}
})(jQuery);

(function($){
	$.fn.hasParent = function(parent){
		var lookfor = $(parent)[0];
		var found = false;
		this.parents().each(function(i, el){
			if(el == lookfor){
				found = true;
			}
		});
		return found;
}
})(jQuery);

(function($){
	$.fn.onClickOutside = function(callback){
		var target = this[0];
		this.onBodyClick = function(e){
			if(!$(e.target).hasParent(target) && !$(e.target).willFireLogin())
				callback();	
		};
		$('body').bind('click', this.onBodyClick);
	}
})(jQuery);

(function($){
	$.fn.willFireLogin = function(){
		var target = this[0];
		return $(target).hasClass('require_login');
	}
})(jQuery);

(function($){
	$.fn.dropIn = function(callback){
	this.each(function(i, el){
		$(el).center();
		$(el).show();
		$(el).animate({opacity: 1, top:parseInt($(el).css('top')) + 10 + 'px'}, callback);
	});
}
})(jQuery);

(function($){
	$.fn.dropOut = function(callback){
	this.each(function(i, el){
		$(el).center();
		$(el).animate({opacity: 0, top:parseInt($(el).css('top')) - 10 + 'px'}, function(){
			$(el).hide();
			callback();
		});
	})
}
})(jQuery);

(function($){
	$.fn.fadeTo = function(src, options){
		callbacks  = jQuery.extend({
			beforeFade: function() {
				if(options.beforeFade)
					options.beforeFade();
			},
			postFade: function() {
				if(options.postFade)
					options.postFade();
			}
		});
	/*
this.each(function(i, el){
		$(el).parent().css({height: $(this).height()});
		callbacks.beforeFade();
		$(el).animate({opacity: 0}, 'fast', 'swing', function(){
			var that = this;
			var img = $('<img>');
			img.attr("src", src).css({opacity: 0});
			img.bind('load', function(){
				$(that).parent().append(img).animate({height: $(img).height()}, 'fast');
				$(this).animate({opacity: 1})
				$(that).remove();
				callbacks.postFade();
			});
		});
	});
*/
	this.each(function(i, el){
		var el = el;
		src = $(src).attr('src') || src;
		$(el).parent().css({height: $(this).height()});
		$(this).css({position: 'absolute'});
		callbacks.beforeFade();
		if (this.src != src) {
			var that = this;
			var img = $('<img>');
			img.attr("src", src).css({
				opacity: 0
			});
			img.bind('load', function(){
				$(that).parent().append(img).animate({
					height: $(img).height()
				}, 'normal');
				$(this).animate({
					opacity: 1
				}, 'normal')
				$(el).animate({
					opacity: 0
				}, 'normal', 'swing', function(){
					$(that).remove();
					callbacks.postFade();
				});
			});
		}
	});

}
})(jQuery);



/**
 * jQuery custom checkboxes
 * 
 * Copyright (c) 2008 Khavilo Dmitry (http://widowmaker.kiev.ua/checkbox/)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @version 1.1.0 Beta
 * @author Khavilo Dmitry
 * @mailto wm.morgun@gmail.com
**/

(function($){

	$.fn.checkbox = function(options) {
	
		/* IE6 background flicker fix */
		try	{ document.execCommand('BackgroundImageCache', false, true);	} catch (e) {}
		
		/* Default settings */
		var settings = {
			cls: 'jquery-checkbox',  /* checkbox  */
			empty: 'empty.png'  /* checkbox  */
		};
		
		/* Processing settings */
		settings = $.extend(settings, options || {});
		
		/* Adds check/uncheck & disable/enable events */
		var addEvents = function(object)
		{
			var checked = object.checked;
			if(checked)
			var disabled = object.disabled;
			var $object = $(object);
			
			if ( object.stateInterval )
				clearInterval(object.stateInterval);
			
			object.stateInterval = setInterval(
				function() 
				{
					if ( object.disabled != disabled )
						$object.trigger( (disabled = !!object.disabled) ? 'disable' : 'enable');
					if ( object.checked != checked )
						$object.trigger( (checked = !!object.checked) ? 'check' : 'uncheck');
				}, 
				10 /* in miliseconds. Low numbers this can decrease performance on slow computers, high will increase responce time */
			);
			return $object;
		}
		/* Wrapping all passed elements */
		return this.each(function() 
		{
			var ch = this;
			var $ch = addEvents(ch); /* Adds custom eents and returns */
			
			if (ch.wrapper)
			{
				ch.wrapper.remove();
			}
			
			/* Creating div for checkbox and assigning "hover" event */
			ch.wrapper = $('<span class="' + settings.cls + '"><span class="mark"><img src="' + settings.empty + '" /></span></span>');
			ch.wrapperInner = ch.wrapper.children('span');
			ch.wrapper.hover(
				function() { ch.wrapperInner.addClass(settings.cls + '-hover'); },
				function() { ch.wrapperInner.removeClass(settings.cls + '-hover'); }
			);

			/* Wrapping checkbox */
			$ch.css({position: 'absolute', zIndex: -1, background: 'transparent url(/stylesheets/empty.png)', display: 'none', top:0, left:0}).after(ch.wrapper);
			
			/* Fixing IE6 label behaviour */
			var parents = $ch.parents('label');
			/* Creating "click" event handler for checkbox wrapper*/
			if ( parents.length )
			{
				parents.click(function(e) { $ch.trigger('click', [e]); return ( $.browser.msie && $.browser.version < 7 ); });
			}
			else
			{
				ch.wrapper.click(function(e) { $ch.trigger('click', [e]); });
			}
			
			delete parents;
				
			$ch.bind('disable', function() { ch.wrapperInner.addClass(settings.cls+'-disabled');}).bind('enable', function() { ch.wrapperInner.removeClass(settings.cls+'-disabled');});
			$ch.bind('check', function() { ch.wrapper.addClass(settings.cls+'-checked' );}).bind('uncheck', function() { ch.wrapper.removeClass(settings.cls+'-checked' );});
			
			/* Disable image drag-n-drop  */
			$('img', ch.wrapper).bind('dragstart', function () {return false;}).bind('mousedown', function () {return false;});
			
			/* Firefox div antiselection hack */
			if ( window.getSelection )
				ch.wrapper.css('MozUserSelect', 'none');
			
			/* Applying checkbox state */
			if ( ch.checked )
				ch.wrapper.addClass(settings.cls + '-checked');
			if ( ch.disabled )
				ch.wrapperInner.addClass(settings.cls + '-disabled');
		});
	};


})(jQuery);



//*** TEMPLATE FUNCTION ***//
//git://github.com/collin/jquery_template.git

(function(_) {
  var templates = {}
    ,syntax = {
      "\\?\\(([\\w]+)\\)": function(object) {
        return function(match, property) {
          return object[property];
        }
      }
      
      // #{property_name}
      
      ,"\\#\\{([\\w]+)\\}": function(object) {
        return function(match, attr) {
          var obj_attr = object[attr];
          if(_.isFunction(obj_attr)) return obj_attr();
          return obj_attr;
        }
      }
      
      // ={template_name}
      
      ,"=\\{([\\w]+)\\}": function(object) {
        return function(match, template) {
          return _.template(template, object);
        }
      }
      
      // ={template_name:property_name}
      
      ,"=\\{([\\w]+):([\\w]+)\\}": function(object) {
        return function(match, template, property) {
          var obj_prop = object[property];
          if(_.isFunction(obj_prop)) obj_prop = obj_prop();
          if(obj_prop.constructor === Array) {
            var len = obj_prop.length, i, render="";
            for(i=0; i<len; i++) render += _.template(template, obj_prop[i]);
            return render;
          }
          return _.template(template, obj_prop);
        }
      }
      
      // =[template_name || object_name <- list_name]
      
      ,"=\\[([\\w]+)\\|\\|([\\w]+)<-(\\w+)\\]": function(object) {
        return function(match, template, object_name, list) {
          if(_.isFunction(object[list])) list = object[list]();
          else  list = object[list];
          var i, len = list.length
            ,locals, render = "";
          
          for(i=0; i<len; i++) {
            locals = {};
            locals[object_name] = list[i];
            render += _.template(template, locals);  
          }
          return render;
        }
      }
    }
    ,compiled_syntax = [];
    
  for(var slot in syntax) compiled_syntax.push({
    regex: new RegExp(slot, 'g')
    ,compiler: syntax[slot]
  });
  
  function compile_template(contents) {
    var len = compiled_syntax.length
      ,i
      ,expr;
    
    return function(object) {
      var render = new String(contents);
      for(i=0; i<len; i++) {
        expr = compiled_syntax[i];
        render =  render.replace(expr.regex, expr.compiler(object));
      }
      return render;
    }
  }
  
  function set_template(name, contents) {
    templates[name] = compile_template(contents);
  }
  
  function render_template(name, contents) {
    return templates[name](contents);
  }

  _.template = function(name, contents) {
    if(contents.constructor === String)
      set_template(name, contents);
    else 
      return render_template(name, contents);
    return true;
  };
})(jQuery);


/** alphanumeric **/

eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(2($){$.c.f=2(p){p=$.d({g:"!@#$%^&*()+=[]\\\\\\\';,/{}|\\":<>?~`.- ",4:"",9:""},p);7 3.b(2(){5(p.G)p.4+="Q";5(p.w)p.4+="n";s=p.9.z(\'\');x(i=0;i<s.y;i++)5(p.g.h(s[i])!=-1)s[i]="\\\\"+s[i];p.9=s.O(\'|\');6 l=N M(p.9,\'E\');6 a=p.g+p.4;a=a.H(l,\'\');$(3).J(2(e){5(!e.r)k=o.q(e.K);L k=o.q(e.r);5(a.h(k)!=-1)e.j();5(e.u&&k==\'v\')e.j()});$(3).B(\'D\',2(){7 F})})};$.c.I=2(p){6 8="n";8+=8.P();p=$.d({4:8},p);7 3.b(2(){$(3).f(p)})};$.c.t=2(p){6 m="A";p=$.d({4:m},p);7 3.b(2(){$(3).f(p)})}})(C);',53,53,'||function|this|nchars|if|var|return|az|allow|ch|each|fn|extend||alphanumeric|ichars|indexOf||preventDefault||reg|nm|abcdefghijklmnopqrstuvwxyz|String||fromCharCode|charCode||alpha|ctrlKey||allcaps|for|length|split|1234567890|bind|jQuery|contextmenu|gi|false|nocaps|replace|numeric|keypress|which|else|RegExp|new|join|toUpperCase|ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('|'),0,{}));

/*
 * jQuery Form Plugin
 * version: 2.16 (17-OCT-2008)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id$
 */
 ;(function($){$.fn.ajaxSubmit=function(options){if(!this.length){log('ajaxSubmit: skipping submit process - no element selected');return this;}
if(typeof options=='function')
options={success:options};options=$.extend({url:this.attr('action')||window.location.toString(),type:this.attr('method')||'GET'},options||{});var veto={};this.trigger('form-pre-serialize',[this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');return this;}
var a=this.formToArray(options.semantic);if(options.data){options.extraData=options.data;for(var n in options.data){if(options.data[n]instanceof Array){for(var k in options.data[n])
a.push({name:n,value:options.data[n][k]})}
else
a.push({name:n,value:options.data[n]});}}
if(options.beforeSubmit&&options.beforeSubmit(a,this,options)===false){log('ajaxSubmit: submit aborted via beforeSubmit callback');return this;}
this.trigger('form-submit-validate',[a,this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-submit-validate trigger');return this;}
var q=$.param(a);if(options.type.toUpperCase()=='GET'){options.url+=(options.url.indexOf('?')>=0?'&':'?')+q;options.data=null;}
else
options.data=q;var $form=this,callbacks=[];if(options.resetForm)callbacks.push(function(){$form.resetForm();});if(options.clearForm)callbacks.push(function(){$form.clearForm();});if(!options.dataType&&options.target){var oldSuccess=options.success||function(){};callbacks.push(function(data){$(options.target).html(data).each(oldSuccess,arguments);});}
else if(options.success)
callbacks.push(options.success);options.success=function(data,status){for(var i=0,max=callbacks.length;i<max;i++)
callbacks[i].apply(options,[data,status,$form]);};var files=$('input:file',this).fieldValue();var found=false;for(var j=0;j<files.length;j++)
if(files[j])
found=true;if(options.iframe||found){if($.browser.safari&&options.closeKeepAlive)
$.get(options.closeKeepAlive,fileUpload);else
fileUpload();}
else
$.ajax(options);this.trigger('form-submit-notify',[this,options]);return this;function fileUpload(){var form=$form[0];if($(':input[@name=submit]',form).length){alert('Error: Form elements must not be named "submit".');return;}
var opts=$.extend({},$.ajaxSettings,options);var s=jQuery.extend(true,{},$.extend(true,{},$.ajaxSettings),opts);var id='jqFormIO'+(new Date().getTime());var $io=$('<iframe id="'+id+'" name="'+id+'" />');var io=$io[0];if($.browser.msie||$.browser.opera)
io.src='javascript:false;document.write("");';$io.css({position:'absolute',top:'-1000px',left:'-1000px'});var xhr={aborted:0,responseText:null,responseXML:null,status:0,statusText:'n/a',getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(){this.aborted=1;$io.attr('src','about:blank');}};var g=opts.global;if(g&&!$.active++)$.event.trigger("ajaxStart");if(g)$.event.trigger("ajaxSend",[xhr,opts]);if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&jQuery.active--;return;}
if(xhr.aborted)
return;var cbInvoked=0;var timedOut=0;var sub=form.clk;if(sub){var n=sub.name;if(n&&!sub.disabled){options.extraData=options.extraData||{};options.extraData[n]=sub.value;if(sub.type=="image"){options.extraData[name+'.x']=form.clk_x;options.extraData[name+'.y']=form.clk_y;}}}
setTimeout(function(){var t=$form.attr('target'),a=$form.attr('action');$form.attr({target:id,method:'POST',action:opts.url});if(!options.skipEncodingOverride){$form.attr({encoding:'multipart/form-data',enctype:'multipart/form-data'});}
if(opts.timeout)
setTimeout(function(){timedOut=true;cb();},opts.timeout);var extraInputs=[];try{if(options.extraData)
for(var n in options.extraData)
extraInputs.push($('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />').appendTo(form)[0]);$io.appendTo('body');io.attachEvent?io.attachEvent('onload',cb):io.addEventListener('load',cb,false);form.submit();}
finally{$form.attr('action',a);t?$form.attr('target',t):$form.removeAttr('target');$(extraInputs).remove();}},10);function cb(){if(cbInvoked++)return;io.detachEvent?io.detachEvent('onload',cb):io.removeEventListener('load',cb,false);var operaHack=0;var ok=true;try{if(timedOut)throw'timeout';var data,doc;doc=io.contentWindow?io.contentWindow.document:io.contentDocument?io.contentDocument:io.document;if(doc.body==null&&!operaHack&&$.browser.opera){operaHack=1;cbInvoked--;setTimeout(cb,100);return;}
xhr.responseText=doc.body?doc.body.innerHTML:null;xhr.responseXML=doc.XMLDocument?doc.XMLDocument:doc;xhr.getResponseHeader=function(header){var headers={'content-type':opts.dataType};return headers[header];};if(opts.dataType=='json'||opts.dataType=='script'){var ta=doc.getElementsByTagName('textarea')[0];xhr.responseText=ta?ta.value:xhr.responseText;}
else if(opts.dataType=='xml'&&!xhr.responseXML&&xhr.responseText!=null){xhr.responseXML=toXml(xhr.responseText);}
data=$.httpData(xhr,opts.dataType);}
catch(e){ok=false;$.handleError(opts,xhr,'error',e);}
if(ok){opts.success(data,'success');if(g)$.event.trigger("ajaxSuccess",[xhr,opts]);}
if(g)$.event.trigger("ajaxComplete",[xhr,opts]);if(g&&!--$.active)$.event.trigger("ajaxStop");if(opts.complete)opts.complete(xhr,ok?'success':'error');setTimeout(function(){$io.remove();xhr.responseXML=null;},100);};function toXml(s,doc){if(window.ActiveXObject){doc=new ActiveXObject('Microsoft.XMLDOM');doc.async='false';doc.loadXML(s);}
else
doc=(new DOMParser()).parseFromString(s,'text/xml');return(doc&&doc.documentElement&&doc.documentElement.tagName!='parsererror')?doc:null;};};};$.fn.ajaxForm=function(options){return this.ajaxFormUnbind().bind('submit.form-plugin',function(){$(this).ajaxSubmit(options);return false;}).each(function(){$(":submit,input:image",this).bind('click.form-plugin',function(e){var form=this.form;form.clk=this;if(this.type=='image'){if(e.offsetX!=undefined){form.clk_x=e.offsetX;form.clk_y=e.offsetY;}else if(typeof $.fn.offset=='function'){var offset=$(this).offset();form.clk_x=e.pageX-offset.left;form.clk_y=e.pageY-offset.top;}else{form.clk_x=e.pageX-this.offsetLeft;form.clk_y=e.pageY-this.offsetTop;}}
setTimeout(function(){form.clk=form.clk_x=form.clk_y=null;},10);});});};$.fn.ajaxFormUnbind=function(){this.unbind('submit.form-plugin');return this.each(function(){$(":submit,input:image",this).unbind('click.form-plugin');});};$.fn.formToArray=function(semantic){var a=[];if(this.length==0)return a;var form=this[0];var els=semantic?form.getElementsByTagName('*'):form.elements;if(!els)return a;for(var i=0,max=els.length;i<max;i++){var el=els[i];var n=el.name;if(!n)continue;if(semantic&&form.clk&&el.type=="image"){if(!el.disabled&&form.clk==el)
a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});continue;}
var v=$.fieldValue(el,true);if(v&&v.constructor==Array){for(var j=0,jmax=v.length;j<jmax;j++)
a.push({name:n,value:v[j]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:n,value:v});}
if(!semantic&&form.clk){var inputs=form.getElementsByTagName("input");for(var i=0,max=inputs.length;i<max;i++){var input=inputs[i];var n=input.name;if(n&&!input.disabled&&input.type=="image"&&form.clk==input)
a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});}}
return a;};$.fn.formSerialize=function(semantic){return $.param(this.formToArray(semantic));};$.fn.fieldSerialize=function(successful){var a=[];this.each(function(){var n=this.name;if(!n)return;var v=$.fieldValue(this,successful);if(v&&v.constructor==Array){for(var i=0,max=v.length;i<max;i++)
a.push({name:n,value:v[i]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:this.name,value:v});});return $.param(a);};$.fn.fieldValue=function(successful){for(var val=[],i=0,max=this.length;i<max;i++){var el=this[i];var v=$.fieldValue(el,successful);if(v===null||typeof v=='undefined'||(v.constructor==Array&&!v.length))
continue;v.constructor==Array?$.merge(val,v):val.push(v);}
return val;};$.fieldValue=function(el,successful){var n=el.name,t=el.type,tag=el.tagName.toLowerCase();if(typeof successful=='undefined')successful=true;if(successful&&(!n||el.disabled||t=='reset'||t=='button'||(t=='checkbox'||t=='radio')&&!el.checked||(t=='submit'||t=='image')&&el.form&&el.form.clk!=el||tag=='select'&&el.selectedIndex==-1))
return null;if(tag=='select'){var index=el.selectedIndex;if(index<0)return null;var a=[],ops=el.options;var one=(t=='select-one');var max=(one?index+1:ops.length);for(var i=(one?index:0);i<max;i++){var op=ops[i];if(op.selected){var v=$.browser.msie&&!(op.attributes['value'].specified)?op.text:op.value;if(one)return v;a.push(v);}}
return a;}
return el.value;};$.fn.clearForm=function(){return this.each(function(){$('input,select,textarea',this).clearFields();});};$.fn.clearFields=$.fn.clearInputs=function(){return this.each(function(){var t=this.type,tag=this.tagName.toLowerCase();if(t=='text'||t=='password'||tag=='textarea')
this.value='';else if(t=='checkbox'||t=='radio')
this.checked=false;else if(tag=='select')
this.selectedIndex=-1;});};$.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=='function'||(typeof this.reset=='object'&&!this.reset.nodeType))
this.reset();});};$.fn.enable=function(b){if(b==undefined)b=true;return this.each(function(){this.disabled=!b});};$.fn.selected=function(select){if(select==undefined)select=true;return this.each(function(){var t=this.type;if(t=='checkbox'||t=='radio')
this.checked=select;else if(this.tagName.toLowerCase()=='option'){var $sel=$(this).parent('select');if(select&&$sel[0]&&$sel[0].type=='select-one'){$sel.find('option').selected(false);}
this.selected=select;}});};function log(){if($.fn.ajaxSubmit.debug&&window.console&&window.console.log)
window.console.log('[jquery.form] '+Array.prototype.join.call(arguments,''));};})(jQuery);

//
//	jQuery Slug Generation Plugin by Perry Trinier (perrytrinier@gmail.com)
//  Licensed under the GPL: http://www.gnu.org/copyleft/gpl.html

// jQuery.fn.slug = function(options) {
// 	var settings = {
// 		slug: 'slug', // Class used for slug destination input and span. The span is created on $(document).ready() 
// 		hide: true	 // Boolean - By default the slug input field is hidden, set to false to show the input field and hide the span. 
// 	};
// 	
// 	if(options) {
// 		jQuery.extend(settings, options);
// 	}
// 	
// 	$this = $(this);
// 
// 	$(document).ready( function() {
// 		if (settings.hide) {
// 			$('input.' + settings.slug).after("<span class="+settings.slug+"></span>");
// 			$('input.' + settings.slug).hide();
// 		}
// 	});
// 	
// 	makeSlug = function() {
// 			var slugcontent = $this.val();
// 			var slugcontent_hyphens = slugcontent.replace(/\s/g,'-');
// 			var finishedslug = slugcontent_hyphens.replace(/[^a-zA-Z0-9\-]/g,'');
// 			$('input.' + settings.slug).val(finishedslug.toLowerCase());
// 			$('span.' + settings.slug).text(finishedslug.toLowerCase());
// 
// 		}
// 		
// 	$(this).keyup(makeSlug);
// 		
// 	return $this;
// };

// function to_slug(str){
// 	var slugcontent = str;
// 	var slugcontent_hyphens = slugcontent.replace(/\s/g,'-');
// 	var finishedslug = slugcontent_hyphens.replace(/[^a-zA-Z0-9\-]/g,'');
// 	return finishedslug;
// }


