// --------------------------------------------------------------------

/**
 * jqModal
 *
 * This script enables our modal pop-up panels. We have cut and pasted it into our main JS file in order to cut down on the number of files that are necessary to download for each page load.
 *
 * This script needs to appear prior to our code which invokes it further down in this file.
 *
 * jqModal - Minimalist Modaling with jQuery
 *   (http://dev.iceburg.net/jquery/jqmodal/)
 *
 * Copyright (c) 2007,2008 Brice Burgess <bhb@iceburg.net>
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 * 
 * $Version: 07/06/2008 +r13
 */
(function($) {
$.fn.jqm=function(o){
var p={
overlay: 50,
overlayClass: 'jqmOverlay',
closeClass: 'jqmClose',
trigger: '.jqModal',
ajax: F,
ajaxText: '',
target: F,
modal: F,
toTop: F,
onShow: F,
onHide: F,
onLoad: F
};
return this.each(function(){if(this._jqm)return H[this._jqm].c=$.extend({},H[this._jqm].c,o);s++;this._jqm=s;
H[s]={c:$.extend(p,$.jqm.params,o),a:F,w:$(this).addClass('jqmID'+s),s:s};
if(p.trigger)$(this).jqmAddTrigger(p.trigger);
});};

$.fn.jqmAddClose=function(e){return hs(this,e,'jqmHide');};
$.fn.jqmAddTrigger=function(e){return hs(this,e,'jqmShow');};
$.fn.jqmShow=function(t){return this.each(function(){$.jqm.open(this._jqm,t);});};
$.fn.jqmHide=function(t){return this.each(function(){$.jqm.close(this._jqm,t);});};

$.jqm = {
hash:{},
open:function(s,t){var h=H[s],c=h.c,cc='.'+c.closeClass,z=(parseInt(h.w.css('z-index'))),z=(z>0)?z:3000,o=$('<div></div>').css({height:'100%',width:'100%',position:'fixed',left:0,top:0,'z-index':z-1,opacity:c.overlay/50});if(h.a)return F;h.t=t;h.a=true;h.w.css('z-index',z);
 if(c.modal) {if(!A[0])L('bind');A.push(s);}
 else if(c.overlay > 0)h.w.jqmAddClose(o);
 else o=F;

 h.o=(o)?o.addClass(c.overlayClass).prependTo('body'):F;
 if(ie6){$('html,body').css({height:'100%',width:'100%'});if(o){o=o.css({position:'absolute'})[0];for(var y in {Top:1,Left:1})o.style.setExpression(y.toLowerCase(),"(_=(document.documentElement.scroll"+y+" || document.body.scroll"+y+"))+'px'");}}

 if(c.ajax) {var r=c.target||h.w,u=c.ajax,r=(typeof r == 'string')?$(r,h.w):$(r),u=(u.substr(0,1) == '@')?$(t).attr(u.substring(1)):u;
  r.html(c.ajaxText).load(u,function(){if(c.onLoad)c.onLoad.call(this,h);if(cc)h.w.jqmAddClose($(cc,h.w));e(h);});}
 else if(cc)h.w.jqmAddClose($(cc,h.w));

 if(c.toTop&&h.o)h.w.before('<span id="jqmP'+h.w[0]._jqm+'"></span>').insertAfter(h.o);	
 (c.onShow)?c.onShow(h):h.w.show();e(h);return F;
},
close:function(s){var h=H[s];if(!h.a)return F;h.a=F;
 if(A[0]){A.pop();if(!A[0])L('unbind');}
 if(h.c.toTop&&h.o)$('#jqmP'+h.w[0]._jqm).after(h.w).remove();
 if(h.c.onHide)h.c.onHide(h);else{h.w.hide();if(h.o)h.o.remove();} return F;
},
params:{}};
var s=0,H=$.jqm.hash,A=[],ie6=$.browser.msie&&($.browser.version == "6.0"),F=false,
i=$('<iframe src="javascript:false;document.write(\'\');" class="jqm"></iframe>').css({opacity:0}),
e=function(h){if(ie6)if(h.o)h.o.html('<p style="width:100%;height:100%"/>').prepend(i);else if(!$('iframe.jqm',h.w)[0])h.w.prepend(i); f(h);},
f=function(h){try{$(':input:visible',h.w)[0].focus();}catch(_){}},
L=function(t){$()[t]("keypress",m)[t]("keydown",m)[t]("mousedown",m);},
m=function(e){var h=H[A[A.length-1]],r=(!$(e.target).parents('.jqmID'+h.s)[0]);if(r)f(h);return !r;},
hs=function(w,t,c){return w.each(function(){var s=this._jqm;$(t).each(function() {
 if(!this[c]){this[c]=[];$(this).click(function(){for(var i in {jqmShow:1,jqmHide:1})for(var s in this[i])if(H[this[i][s]])H[this[i][s]].w[i](this);return F;});}this[c].push(s);});});};
})(jQuery);

/*	End jqModal script */

// --------------------------------------------------------------------

/**
 * Snap Digs
 *
 * Custom JS for Snap Digs from this point down.
 *
 */

jQuery(document).ready(function()
{	
	// Activate show / hide for links and divs
	jQuery("a[rel=showhide]").click( function(evt)
	{
		jQuery(this).next("div").toggle();
		
		var cls	= "show";
		
		if ( jQuery(this).attr("class") == "show" )
		{
			cls = "hide";
		}
		
		jQuery(this).attr("class", cls);
		
		return false;
	});
	
	//	Activate address concatenation
	jQuery("div#address_fields input,div#address_fields select").change(address_title);
	
	//	Activate delete search function
	jQuery("a.delete_search").click(delete_search);
	
	//	Activate forget last search function
	jQuery("a.forget_last_search").click(forget_last_search);
	
	//	Activate swap default function
	swapDefault();
	
	// Handle sale/rent filtering submission form
	jQuery("select[name=field_id_16]").filterOn("input:radio[name=field_id_31]", {
        'rent': ['-','Co-op','Condo','Condop','Townhouse','Rental Property'],
        'sale': ['-','Co-op','Condo','Townhouse','Condop']
	});
	
	//	Activate sale/rent toggles and run on page load
	sale_rent();
	jQuery("input.sale_rent").click(function(event) {
		sale_rent(event);
	});
	
	//	Activate neighborhood and borough category fields
	jQuery("input[name=category[]]").click(neighborhood_borough_category_fields);
	
	//	Activate neighborhood smart category checking and unchecking
	jQuery("div.neighborhoods input[name=category[]]").change(neighborhood_smart_checks);
	
	//	Activate status change modal windows
	jQuery("div#jqmodal").jqm({ajax:'@href', ajaxText:'<div class="jqmLoading">Loading...</div>', modal:false, onLoad:popStatusModal, overlay:30, overlayClass:'jqmOverlay', target:false, toTop:true, trigger:'a.modal_status'});
	
	//	Activate modal floor plan windows
	jQuery("div#jqmodalfloorplan").jqm({ajax:'@href', ajaxText:'<div class="jqmLoading">Loading...</div>', modal:false, onLoad:popFloorPlanModal, overlay:30, overlayClass:'jqmOverlay', target:false, toTop:true, trigger:'a.modal_floor_plan'});
	
	//	Activate modal photo edit windows
	jQuery("div#jqmodalphotoedit").jqm({ajax:'@href', ajaxText:'<div class="jqmLoading">Loading...</div>', modal:false, onLoad:popPhotoEditModal, overlay:30, overlayClass:'jqmOverlay', target:false, toTop:true, trigger:'a.modal_photo_edit'});
	
	//	Activate modal photo lead change windows
	jQuery("div#jqmodalphotolead").jqm({ajax:'@href', ajaxText:'<div class="jqmLoading">Loading...</div>', modal:false, onLoad:popPhotoLeadModal, overlay:30, overlayClass:'jqmOverlay', target:false, toTop:true, trigger:'a.modal_photo_lead'});

	//	Always calculate the cart total
	calc();

	//	Sniff for cart removals
	remove_from_cart();

	//	Sniff for cart additions
	add_to_cart();
	
	//	Sniff for cart checkboxes
	jQuery("table.mycart input[type='checkbox']").click( function(event) {
		calc();
	});

	//	Sniff for add favorites
	add_to_favorites();

	//	Sniff for remove favorites
	remove_from_favorites();
	
	//	Change the entry form to multi-part for Mac and IE
	jQuery("form#entryform").attr( "enctype", "multipart/form-data" );
	jQuery("form#entryform").attr( "encoding", "multipart/form-data" );
	
	//	Handle show / hide on loginreg forms
	jQuery("input[name='type']").click( function (event) {
		jQuery("div#register_fields").hide();
		jQuery("div#" + jQuery(this).attr("id") + "_fields").show();
	});
	
	//	Handle show hide on image delete
	jQuery("input.remove").click( function(event) {
		var id	= jQuery(this).attr("id").substr( 6 );
		if ( jQuery(this).attr("checked") == true ) {
			jQuery("div#upload" + id ).show();
		} else {
			jQuery("div#upload" + id ).hide();
		}
	});
	
	// Handle character count on summary field whenever we find it in a page.
	if ( jQuery('textarea#summary').length > 0 )
	{
		jQuery('textarea#summary').charCounter(1000, {
			container: '<div></div>',
			classname: 'char-count',
			format: '%1 characters remain',
			pulse: true,
			delay: 0
		});
	}
	
	// Handle which toggle group to display
	if ( jQuery(".toggler:checked") != null ) {
		var checked_id = jQuery(".toggler:checked").attr("id");
		jQuery("div.toggler_group").hide();
		jQuery("div."+checked_id).show();
	}
});

// --------------------------------------------------------------------

/**
 * Address title
 *
 * When people submit listings, we create the required EE blog entry title by combining a few custom fields. This method does that for us on the fly inside the page.
 *
 * @access	public
 * @return	string
 */

function address_title()
{
	var title = '';
	
	title += jQuery("input#street").val() + ' ';
	//title += jQuery("select#street_type").val() + ' ';
	title += jQuery("input#city").val() + ' ';
	if ( jQuery("select#state").val() != '-' )
	{
		title += jQuery("select#state").val() + ' ';
	}
	title += jQuery("input#zip").val() + ' ';
	
	jQuery("input#title").val( title );
}

/* End address title */

// --------------------------------------------------------------------

/**
 * Delete search
 *
 * Sometimes people will not their last search to be remembered. Maybe they want a clear search form.
 *
 * @access	public
 * @return	string
 */

function delete_search()
{
	var ths	= jQuery(this);
	
	jQuery(this).addClass('loading');
	
	jQuery.post( jQuery(this).attr('href'), {}, function(data)
	{
		jQuery(ths).removeClass('loading');
		jQuery(ths).parent('td').parent('tr').remove();
	});
	
	return false;
}

/* End end delete search */

// --------------------------------------------------------------------

/**
 * Forget last search
 *
 * Sometimes people will not their last search to be remembered. Maybe they want a clear search form.
 *
 * @access	public
 * @return	string
 */

function forget_last_search()
{
	var ths	= jQuery(this);
	
	jQuery(this).addClass('loading');
	
	jQuery.post( jQuery(this).attr('href'), {}, function(data)
	{
		jQuery(ths).removeClass('loading');
		window.location.reload();
	});
	
	return false;
}

/* End forget last search */

// --------------------------------------------------------------------

/**
 * Swap default
 *
 * Handle default field values.
 *
 * @access	public
 * @return	string
 */

function swapDefault() {
	jQuery("input.blankout").each(function() {
		jQuery(this).focus(function() {
			if(this.defaultValue && this.value == this.defaultValue) this.value = "";
			jQuery(this).addClass("focus");
		}).blur(function() {
			if(this.defaultValue && !this.value.length) this.value = this.defaultValue;
			jQuery(this).removeClass("focus");
		});
	});
}

/*	End swap default */

// --------------------------------------------------------------------

/**
 * Sale / Rent
 *
 * Depending on whether a listing is a rental listing or a for sale listing, some fields are hidden or shown. This function enables that behavior.
 *
 * We also piggy back some behavior here since some other odd behaviors are dependent on sale/rent toggle.
 *
 * @access	public
 * @return	null
 */

jQuery.fn.filterOn = function(radio, values) {
    return this.each(function() {
        var select = this;
        var options = [];
        jQuery(select).find('option').each(function() {
            options.push({value: jQuery(this).val(), text: jQuery(this).text(), select: jQuery(this).attr("selected")});
        });
        jQuery(select).data('options', options);
        jQuery(radio).click(function() {
            var options = jQuery(select).empty().data('options');
            var haystack = values[jQuery(this).attr('id')];
            jQuery.each(options, function(i) {
                var option = options[i];
                if ( jQuery.inArray(option.value, haystack) !== -1 ) {
                    jQuery(select).append(
                    	jQuery('<option>').text(option.text).val(option.value).attr("selected", option.select)
                    );
                }
            });
        });            
    });
};

function sale_rent(event)
{
	if ( event == undefined ) {
		var init 	= true;
		var el		= ( window.location.href.indexOf('mine/edit') >= 0 ) ? jQuery("input:radio[name=field_id_31]") : jQuery("input:radio[name=exact-sale_rent]");
	} else {
		var el = jQuery(event.target);
	}
	
	if ( el.attr("name") == "field_id_31" ) {
		if ( el.length != 0 )
		{
			var sr			= jQuery('input:radio[name=field_id_31]:checked').val();
			if ( init === true ) {
				var values		= {
			        'rent': ['-','Co-op','Condo','Condop','Townhouse','Rental Property'],
			        'sale': ['-','Co-op','Condo','Townhouse','Condop']
				};
				var options		= jQuery("select[name=field_id_16]").empty().data('options');
	            var haystack	= values[jQuery("input:radio[name=field_id_31]:checked").attr('id')];
	            jQuery.each(options, function(i) {
	                var option = options[i];
	                if ( jQuery.inArray(option.value, haystack) !== -1 ) {
	                    jQuery("select[name=field_id_16]").append(
	                    	jQuery('<option>').text(option.text).val(option.value).attr("selected", option.select)
	                    );
	                }
	            });
			}
		}
		
		jQuery(".sale,.rent").hide();
		
		if ( sr == 'Sale' )
		{
			jQuery(".sale").show();
		}

		if ( sr == 'Rent' )
		{
			jQuery(".rent").show();
		}
	} else {
		if ( el.length != 0 )
		{
			var sr	= jQuery('input[name=exact-sale_rent]:checked').val();
		}
		
		jQuery(".sale,.rent").hide();

		if ( sr == 'Sale' )
		{
			jQuery(".sale").show();
			jQuery("input#4exact-condocoop,label[for=4exact-condocoop]").show();
			jQuery("input#5exact-condocoop,label[for=5exact-condocoop]").hide();
		}

		if ( sr == 'Rent' )
		{
			jQuery(".rent").show();
			jQuery("input#5exact-condocoop,label[for=5exact-condocoop]").show();
		}
	}
}

/* End sale / rent */

// --------------------------------------------------------------------

/**
 * Neighborhood borough category fields
 *
 * Depending on whether a listing is a rental listing or a for sale listing, some fields are hidden or shown. This function enables that behavior.
 *
 * We also piggy back some behavior here since some other odd behaviors are dependent on sale/rent toggle.
 *
 * @access	public
 * @return	null
 */

function neighborhood_borough_category_fields()
{
	jQuery( 'input[name=field_id_98]' ).val( jQuery(this).next('label').text() );
	jQuery( 'input[name=field_id_99]' ).val( jQuery(this).attr('alt') );
}

/*	End neighborhood borough category fields */

// --------------------------------------------------------------------

/**
 * Neighborhood smart category checkboxes
 *
 * We use a hierarchy of categories to represent neighborhoods. We use checkboxes to represent that hierarchy. When you check a checkbox, the child checks should be active. When you uncheck a parent, the child checks should uncheck.
 *
 * @access	public
 * @return	null
 */

function neighborhood_smart_checks()
{
	// Save the current checkboxes checked state.
	var checked	= jQuery( this ).attr( "checked" );
	
	//	Exception for the "All Neighborhood" level category like All Manhattan, All Brooklyn, etc.
	if ( jQuery( this ).val() == jQuery( this ).closest( "div.neighborhoods" ).find( "input[type=checkbox]" ).first().val() )
	{
		jQuery( this ).closest( "div.neighborhoods" ).find( "input[type=checkbox]" ).attr( "checked", checked );
		return;
	}
	
	//	If someone unchecks a child category of an "All Manhattan" type category, we need to uncheck that top level cat.
	else
	{
		if ( checked == false )
		{
			jQuery( this ).closest( "div.neighborhoods" ).find( "input[type=checkbox]" ).first().attr( "checked", checked )
		}
	}

	// Set all children of the parent to the parent's checked state.
	jQuery( this ).parent( "li" ).find( "input[type=checkbox]" ).attr( "checked", checked );
}

/*	End neighborhood smart category checkboxes */

// --------------------------------------------------------------------

/**
 * Pop floor plan modal
 *
 * People can change the floor plan photo attached to their listings using this modal window.
 *
 * @access	public
 * @return	null
 */

function popFloorPlanModal() {
	jQuery("div#jqmodalfloorplan button.submit").click( function()
	{
		jQuery("div#jqmodalfloorplan span#messaging p.message").text('Loading...');
		
		var entry_id	= jQuery("div#jqmodalfloorplan input[name=entry_id]").val();
		
		jQuery("div#jqmodalfloorplan span#messaging").load( '/mine/modal_floorplan_delete/' + entry_id, function(data)
		{
			jQuery("div#jqmodalfloorplan button.jqmClose").click( function()
			{
				window.location.reload();
			});
		});
	});
};

/*	End pop floor plan modal */

// --------------------------------------------------------------------


/**
 * Pop photo lead modal
 *
 * People can delete photos attached to their listings using this modal window.
 *
 * @access	public
 * @return	null
 */

function popPhotoLeadModal() {
	jQuery("div#jqmodalphotolead button.submit").click( function()
	{	
		jQuery("div#jqmodalphotolead span#messaging p.message").text('Loading...');
		
		var entry_id	= jQuery("div#jqmodalphotolead input[name=entry_id]").val();
		
		jQuery("div#jqmodalphotolead span#messaging").load( '/mine/modal_photo_lead/' + entry_id, function(data)
		{
			jQuery("div.photo-box-lister ul li").attr("class", "lead-image-off");
			jQuery("div.photo-box-lister ul li#photo" + entry_id).attr("class", "lead-image-on");			
		});
	}
	);
};

/*	End pop photo lead modal */

// --------------------------------------------------------------------

/**
 * Pop photo lead modal
 *
 * People can change the lead photo attached to their listings using this modal window.
 *
 * @access	public
 * @return	null
 */

function popPhotoEditModal() {
	jQuery("div#jqmodalphotoedit button.submit").click( function()
	{	
		jQuery("div#jqmodalphotoedit span#messaging p.message").text('Loading...');
		
		var entry_id	= jQuery("div#jqmodalphotoedit input[name=entry_id]").val();
		
		jQuery("div#jqmodalphotoedit span#messaging").load( '/mine/modal_photo_delete/' + entry_id, function(data)
		{
			jQuery("li#photo" + entry_id).hide("", function(element) { jquery(this).remove();});
		});
	}
	);
};

/*	End pop photo lead modal */

// --------------------------------------------------------------------

/**
 * Pop status modal
 *
 * People can change the status of their listings by clicking a change link and getting a jQuery modal window. Inside the window they confirm their change and get additional messaing.
 *
 * @access	public
 * @return	null
 */

function popStatusModal() {
	jQuery("div#jqmodal input.submit").hover(
		function() {
			// jQuery(this).attr("src","/static/css/jqm/send-it-over.gif");
		},
		function() {
			// jQuery(this).attr("src","/static/css/jqm/send-it-out.gif");
		}
	);
	
	/*
	
	jQuery("div#jqmodal form").submit( function(evt) {
		var XID					= jQuery("input[@name='XID']").val();
		var ACT					= jQuery("input[@name='ACT']").val();
		var user_recipients		= jQuery("input[@name='user_recipients']").val();
		var charset				= jQuery("input[@name='charset']").val();
		var tell_friend_ajax	= jQuery("input[@name='tell_friend_ajax']").val();
		var track_views			= jQuery("input[@name='track_views']").val();
		var entry_id			= jQuery("input[@name='entry_id']").val();
		var to					= jQuery("input[@name='to']").val();
		var name				= jQuery("input[@name='name']").val();
		var from				= jQuery("input[@name='from']").val();
		var subject				= jQuery("input[@name='subject']").val();
		var message				= jQuery("textarea[@name='message']").val();
		jQuery("div#jqmResponse p").attr("class","loading");
		jQuery("div#jqmResponse p").load( "/?ACT=" + ACT, {RET:'', XID:XID, user_recipients:user_recipients, charset:charset, tell_friend_ajax:tell_friend_ajax, track_views:track_views, entry_id:entry_id, to:to, name:name, from:from, subject:subject, message:message}, function(i) {
			jQuery("div#jqmResponse p").attr("class","error");	// We can't tell the difference at the moment between success and error messages. Blah.
			// This is hacky, I know, but we don't want the user to be able to submit twice.
			// And since we can't tell the diff between success and error (see above), this
			// is what we're stuck with.
			var el = jQuery("div#jqmResponse p")[0];
			var eltxt = jQuery(el).text().replace(/^\s+|\s+$/g, '');
			var txt = "Your email message has been sent.";
			if (eltxt == txt)
			{
				jQuery("form#tellafriend_form input.submit").hide();
			}
		});
		return false;
	});
	
	*/
};

/*	End status change */

// --------------------------------------------------------------------

/**
 * Calc
 *
 * Calculate the cart total.
 *
 * @access	public
 * @return	number
 */

function calc()
{
	var total		= 0;
	var products	= false;
	
	jQuery("table.mycart tr td input[type=hidden]").each(function(i,n)
	{
		products	= true;
		total		+= ( jQuery(n).attr("alt") * 1 );
	});
	
	total	= total.toFixed(2);
	
	jQuery("#total").text( "$" + total);
	
	return products;
}

/*	End calc */

// --------------------------------------------------------------------

/**
 * Add to cart
 *
 * @access	public
 * @return	null
 */
 
function add_to_cart()
{
	jQuery(".listings-table table a.add").click( function(event) {
		event.preventDefault();
	
		var ths	= jQuery(this);
		var id	= jQuery(this).attr("alt");
		
		jQuery(this).addClass( "loading" );
		
		jQuery.post( "/mine/add_to_cart/" + id, function(data) {
			if ( data.error() == true ) {
				jQuery(ths).removeClass( "loading" );
				alert( data.prepError() );
			} else {
				jQuery(ths).hide();
				jQuery(ths).siblings("a").show();
				jQuery(ths).removeClass( "loading" );
			}
		});
	});
}

/*	End add to cart */

// --------------------------------------------------------------------

/**
 * Remove from cart
 *
 * @access	public
 * @return	null
 */
 
function remove_from_cart()
{
	jQuery(".listings-table table a.remove, table.mycart a.remove").click( function(event) {
		event.preventDefault();
		
		var ths	= jQuery(this);
		var id	= jQuery(this).attr("alt");
		
		jQuery(this).addClass( "loading" );
		
		jQuery.post( "/mine/remove_from_cart/" + id, function(data) {
			if ( data.error() == true ) {
				jQuery(ths).removeClass( "loading" );
				alert( data.prepError() );
			} else {
				jQuery(ths).hide();
				jQuery(ths).removeClass( "loading" );
				if ( jQuery(ths).attr("rel") == 'cart' )
				{
					jQuery("tr#item" + id).remove();
					calc();
				}
				else
				{
					jQuery(ths).siblings("a").show();
				}
			}
		});
	});
}

/*	End delete from cart */

// --------------------------------------------------------------------

/**
 * Delete from cart
 *
 * @access	public
 * @return	null
 */
 
function delete_from_cart()
{
	jQuery("table.mycart a.delete").click( function(event) {
		event.preventDefault();
	
		var id	= jQuery(this).attr("alt");
		
		jQuery(this).parent("td").addClass( "loading" );
		
		jQuery.post( "/mine/ajax_remove/" + id, function(data) {
			if ( data.error() == true ) {
				alert( data.prepError() );
			} else {
				jQuery("table.mycart tr#item" + id ).remove();
				if ( count_elements( "table.mycart tr td input[type=checkbox]" ) == 0 ) {
					jQuery("tr.empty").toggle();
				}
				calc();
				jQuery("table.mycart td#loading").removeClass( "loading" );
			}
		});
	});
}

/*	End delete from cart */

// --------------------------------------------------------------------

/**
 * Add to favorites
 *
 * @access	public
 * @return	null
 */
 
function add_to_favorites()
{
	jQuery("a[rel=add_to_favorites]").click( function(event) {
		event.preventDefault();
	
		var ths	= jQuery(this);
		var id	= jQuery(this).attr("alt");
		
		// jQuery(this).addClass( "loading" );
		
		jQuery.post( "/mine/add_to_favorites/" + id, function(data) {
			if ( data.error() == true ) {
				jQuery(ths).removeClass( "loading" );
				alert( data.prepError() );
			} else {
				jQuery(ths).hide();
				// jQuery(ths).removeClass( "loading" );
				jQuery(ths).siblings("a.btn-remove-favorites").show();
				jQuery(ths).siblings("a.btn-remove").show();
			}
		});
	});
}

/*	End add to favorites */

// --------------------------------------------------------------------

/**
 * Remove from favorites
 *
 * @access	public
 * @return	null
 */
 
function remove_from_favorites()
{
	jQuery("a[rel=remove_from_favorites]").click( function(event) {
		event.preventDefault();
	
		var ths	= jQuery(this);
		var id	= jQuery(this).attr("alt");
		
		// jQuery(this).addClass( "loading" );
		
		jQuery.post( "/mine/add_to_favorites/" + id + "/delete", function(data) {
			if ( data.error() == true ) {
				jQuery(ths).removeClass( "loading" );
				alert( data.prepError() );
			} else {
				jQuery(ths).hide();
				// jQuery(ths).removeClass( "loading" );
				jQuery(ths).siblings("a.btn-add-favorites").show();
				jQuery(ths).siblings("a.btn-add").show();
			}
		});
	});
}

/*	End remove from favorites */

// --------------------------------------------------------------------

/**
 * Count elements
 *
 * @access	public
 * @return	number
 */

function count_elements ( element ) {
	var count = 0;
	jQuery( element ).each( function(i,n) {
		count++;
	});
	return count;
}

/*	End count elements */

// --------------------------------------------------------------------

/**
 * Prototype - extensions
 *
 * Various extensions to the prototype object
 *
 * @access	public
 * @return	null
 */

String.prototype.error = function ()
{
	if ( this.indexOf( "!", 0 ) == 0 ) return true;
	
	return false;
};

String.prototype.prepError = function ()
{
	return this.substr( 1 );
};

Array.prototype.inArray	= function ( element )
{
	for ( i=0; i<this.length; i++ )
	{
		if ( this[i] == element ) return true;
	}
	
	return false;
};

Date.prototype.paddedMonth	= function ()
{
	var str		= ( this.getMonth() + 1 ) + '';
	return str	= ( str.length == 1 ) ? '0' + str: str;
};

Date.prototype.paddedDate	= function ()
{
	var str		= this.getDate() + '';
	return str	= ( str.length == 1 ) ? '0' + str: str;
};

Date.prototype.paddedHours	= function ()
{
	if ( this.getHours() == 0 ) return '12';
	if ( this.getHours() > 12 ) var str	= ( this.getHours() - 12 ) + '';
	return str	= ( str.length == 1 ) ? '0' + str: str;
};

Date.prototype.paddedMinutes	= function ()
{
	var str		= this.getMinutes() + '';
	return str	= ( str.length == 1 ) ? '0' + str: str;
};

Date.prototype.getMeridien	= function ()
{
	if ( this.getHours() > 11 )
	{
		return 'PM';
	}
	else
	{
		return 'AM';
	}
};

Date.prototype.increment	= function ( secs )
{
	this.setTime( this.getTime() + ( secs * mls ) );
	return this;
};

/**	----------------------------------------
/**	Extend get EE time format onto Date() object
/**	----------------------------------------*/

Date.prototype.getEeTime	= function ()
{
	var str		= "";
	var offset	= this.getTimezoneOffset();
	
	str	+= this.getFullYear() + "-";
	str	+= this.paddedMonth() + "-";
	str	+= this.paddedDate();
	
	var hours	= this.paddedHours();
	var m		= this.getMeridien();
	
	str	+= " " + hours + ":";
	str	+= this.paddedMinutes() + " " + m;
	
	return str;
};

/**	----------------------------------------
/**	Extend set EE time format onto Date() object
/**	----------------------------------------*/

Date.prototype.setEeTime	= function ( str )
{
	var arr		= str.split(' ');
	var date	= arr[0].split('-');
	var time	= arr[1].split(':');
	var m		= arr[2];
	var hours	= ( m == 'PM' ) ? ( time[0] * 1 ) + 12: time[0] * 1;
	hours		= ( hours == 24 ) ? 0: hours;
	this.setFullYear( date[0] * 1 );
	this.setMonth( ( date[1] * 1 ) - 1 );
	this.setDate( date[2] * 1 );
	this.setHours( hours );
	this.setMinutes( time[1] * 1 );
	return this;
};

/*	End prototype - extensions */
