var addthis_config = {
    services_compact: 'facebook, twitter, stumbleupon, digg, delicious, myspace'
};

(function($) {
    $.fn.trigweelist = function() {
        
        return this.each( function() {
            
            $(this).find('.list-controls button').click( function(e) {
                e.stopPropagation();

                trigweeDialog
                    .show()
                    .showLoader()
                    .loadContent( $(this).attr('action') );

                return false;
            } );

        } );
        
    }
} )(jQuery);

(function($) {

    $.fn.trigweerelated = function() {

        return this.each( function() {
            var $this = $(this);
            var $ul = $this.find('ul');
            var $handler = $this.find('span.related-rs-show-more');

            var height = $ul.find('li:first').height();

            var max_height = height * ( $ul.find('li').length / $this.attr('cols') ) - height;
            $ul.find('li').hover( 
                function() { $(this).animate( { opacity: 0.5 }, 100 ); },
                function() { $(this).animate( { opacity: 1 }, 200 ); }
            );

            $handler.click( function() {
                var this_height = $ul.height();
                $ul.animate( { height: this_height + height }, 1000 );
                $(this).animate( { marginTop: 20 + this_height }, 1000 );
                
                if( $ul.height() >= max_height ) $(this).hide();
            } );

            if( $ul.find('li').length <= $this.attr('cols') ) $handler.hide();

        } );

    }

})(jQuery);

(function($) {
    $.fn.trigweetabs = function() {
        return this.each( function() {

            var $menu = $(this).find('ul li');
            var $menu_a = $(this).find('ul li a');
            var $content = $(this).find('#tab-content');

            $menu_a.click( function() {
                var $me = $(this);
                var $li = $(this).parents('li:first');

                $menu.removeClass('active');
                $li.addClass('active');
                $content.empty().append( $('#loader').clone().show() );
                $content.load( $(this).attr('href'), function() {
                    var href = location.href;
                    
                    if( href.indexOf('#') > 0 )
                        href = href.substr(0, href.indexOf('#'));

                    location.assign( href + $me.attr('path') );

                    if( $('.paging-list').length ) new Loader();
                    if( $('.dream-block').length ) trigweeDream.setActions();
                    
                    if( $('.related-rs').length ) $('.related-rs').trigweerelated();
        
                    if( $('#fbconnect-handler').length ) Trigwee.FBConnect();
                } );

                return false;
            } );

            var href = location.href;
            var path = $(this).find('ul li.active a').attr('path');
            if( href.indexOf('#') > 0 ) {
                var end = href.length;
                if( href.indexOf('?') > 0 ) end = href.indexOf('?');

                var new_path = href.substring(href.indexOf('#'), end);
                if( $(this).find('li a[path='+new_path+']').length )
                    path = new_path;
            }
            $(this).find('li a[path='+path+']').click();
        } );
    }
} )(jQuery);

(function($) {
	$.fn.timestamp = function() {
		return this.each( function() {
            if( $(this).attr('timestamped') ) return;

            var s_nd = $.trim( $(this).text() ).split(/[ :,]/);

            var nd = new Array();
            for(var i = 0; i < s_nd.length; i++) if(s_nd[i] && s_nd[i] != undefined) nd[nd.length] = s_nd[i];

            var my_date = new Date( Date.UTC(nd[5], Trigwee.month[nd[3]], nd[4], nd[0], nd[1]) );
        
            var y = my_date.getFullYear();
            var m = Trigwee.get_month[my_date.getMonth()];
            var d = my_date.getDate() < 10 ? "0"+my_date.getDate() : my_date.getDate();
            var h = my_date.getHours(); if(h>12) h=h-12; if(h<10) h="0"+h;
            var min = my_date.getMinutes(); if(min<10) min="0"+min;
            var tz = my_date.getHours() <= 12 ? "AM" : "PM";
            
        
            var new_date = h+":"+min+" "+tz+" "+m+" "+d+", "+y;
            
            if( $(this).find('a').length ) {
                $(this).find('a:first').text(new_date);
            }
            else {
                $(this).text(new_date);
            }

            $(this).attr('timestamped', true);

            var s_nd = $
		} );
	}
	
})(jQuery);



(function($){

	$.fn.shuffle = function() {
		return this.each(function(){
			var items = $(this).children();
			return (items.length) ? $(this).html($.shuffle(items)) : this;
		});
	}
	
	$.shuffle = function(arr) {
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	}
	
})(jQuery);


(function($) {
 
    $.fn.autogrow = function(options) {
        
        this.filter('textarea').each(function() {
            
            var $this       = $(this),
                minHeight   = $this.height(),
                lineHeight  = $this.css('lineHeight');

            var shadow = $('<div></div>').css({
                position:   'absolute',
                'top':      -10000,
                left:       -10000,
                width:      420,
                'font-size':   $this.css('fontSize'),
                'font-family': $this.css('fontFamily'),
                'line-height': $this.css('lineHeight')
            }).appendTo(document.body);

            var update = function() {
    
                var times = function(string, number) {
                    for (var i = 0, r = ''; i < number; i ++) r += string;
                    return r;
                };
                
                var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
                                    .replace(/\n$/, '<br/>&nbsp;')
                                    .replace(/\n/g, '<br/>')
                                    .replace(/ {2,}/g, function(space) { return times('&nbsp;', space.length -1) + ' ' });
                
                shadow.html(val);
                $(this).css('height', Math.max(shadow.height() + 20, minHeight));
            
            }
            
            $(this).change(update).keyup(update).keydown(update);
            
            update.apply(this);
            
        });
        
        return this;
        
    }
    
})(jQuery);



function focus_blur( element ) {
    var me = this;

    $(element)
        .focus( function() {
            if( $(this).val() != $(this).attr('default_value') ) return;
            $(this).val('');
        } )
        .blur( function() {
            if( $(this).val() == $(this).attr('default_value') || $(this).val().length == 0 ) {
                $(this).val( $(this).attr('default_value') );
            }
        } );

}



var Trigwee = {
	params: {
		searchFieldValue: "",
		regionSelector: "none",
		languageSelector: "none"
	},
	month: {
		"Jan": 0,
		"Feb": 1,
		"Mar": 2,
		"Apr": 3,
		"May": 4,
		"Jun": 5,
		"Jul": 6,
		"Aug": 7,
		"Sep": 8,
		"Oct": 9,
		"Nov": 10,
		"Dec": 11
	},
	get_month: {
		0: "Jan",
		1: "Feb",
		2: "Mar",
		3: "Apr",
		4: "May",
		5: "Jun",
		6: "Jul",
		7: "Aug",
		8: "Sep",
		9: "Oct",
		10: "Nov",
		11: "Dec"
	},

	init: function() {
		Trigwee.loader_buttons();

		Trigwee.active_form_fields();

        Trigwee.FBConnect();
		
		if( $('.me-block ul').length ) $('.me-block ul').shuffle();
	
		if( $('form#design').length ) Trigwee.design();

		if( $('.dream-subscription').length ) Trigwee.notify();

		if( $('#bookmarklet-wrap').length ) Bookmarklet.init();
		
		if( $('.paging-list').length ) { new Loader(); }

		if( $('#own-avatar').length || $('#register-fbconnect-image') ) { Avatar.init(); }

		$('#page-info')
			.animate({ opacity: 1.0 }, 5000)
			.fadeOut(2000, function() { $(this).remove(); } );

		$('a.email').each( function() {
			var email = this.rel.replace(' at ','@');
			this.href = 'mailto:' + email;
			$(this).text(email);
		} );

        if( $('#tabs').length ) $('#tabs').trigweetabs();

        if( $('#privacy-options').length ) {
            $('#privacy-options input').click( function() {
                $('#privacy-options input').attr('checked', false);
                $(this).attr('checked', true);
            } );
        }

        $('#list-rs').trigweelist();

	},

    FBConnect: function() {

        $('form#register_fb input, form#register_fb select').each( function() {
            $(this).attr('default_value', $(this).val() );
        } );

        $('input[name=use_fbconnect_details]').change( function() {
            var checked = $(this).attr('checked');
            if( checked ) {
                $('form#register_fb input[type!=submit], form#register_fb select').each( function() {
                    $(this).val( $(this).attr('default_value') );
                } );
                $('#register-fbconnect-image').show();
            }
            else {
                $('form#register_fb input[type!=submit], form#register_fb select').each( function() {
                    $(this).val( "" );
                } );
                $('#register-fbconnect-image').hide();
            }
        } );    
    
        $('#fbconnect-handler').click( function() {

            if( $(this).attr('pageTrackerRef') && pageTracker ) {
                pageTracker._trackPageview( $(this).attr('pageTrackerRef')+"?ref=facebook" );
            }

            FB.ensureInit( function() {
                try {
                    FB.Connect.requireSession( function() {
                        FB.Facebook.get_sessionState().waitUntilReady( function() {
                            var session = FB.Facebook.apiClient.get_session();

                            var url = '/auth/facebook' + '?fb_sig_added=1';

                            for (var key in session) {
                                url += '&' + 'fb_sig_' + key + '=' + session[key];
                            }

                            $.post( url, function() { location.href = "/"; } );

                        } );
                    } );
                } catch(err) {

                    trigweeDialog
                        .show()
                        .showLoader()
                        .loadContent('/fbconnect/error');

                }
            } );


        } );

    },
    
	notify: function() {
		$('.dream-subscription form').ajaxForm( {
            dataType: 'json',
            beforeSubmit: function( data, form ) {
                $(form).append( $('#loader').show() );
                $(form).children('fieldset:first').hide();
            },
            success: function(response, st, form) {
                $(document.body).append( $('#loader').hide() );

                if( response.success ) $(form).children('fieldset').show();
                else $(form).parents('div:first').slideUp( 'slow' );
            }
		} );

		$('.dream-subscription form input[type=checkbox]').click( function() {
			$(this).parents('form:first').submit();
		} );
	},


	design: function() {
		var focused = {
			'background-color': 'body',
			'outer-border': '#wrapper',
			'inner-border': '#content-border'
		};
	
		$('#picker').farbtastic( function(color) {
			$(focused[focused.div]).css( { 'background-color': color } );
			$(focused.field)
				.css( { 'background-color': color } )
				.val(color);
		} );

		var selected;
		$('input').focus( function() {
			$('#picker').hide();
		} );
		$('.pick-color')
			.click( function() {
				$('#design input[value=personal]').attr('checked', true);
				$('#picker').show();

				focused.field = $(this);
				focused.div = $(this).attr('name');

				var color = $(this).val();

				$(focused[focused.div]).css( { 'background-color': color } );
				$(focused.field)
					.css( { 'background-color': color } )
					.val(color);
			} )
			.focus( function() {
				$('#picker').show();
			} )
			.keyup( function() {
				$(this).click();
			} );
	},

	active_form_fields: function() {
		$('form input[type=text], form input[type=password], form textarea').focus( function() {
			$('.active-field').removeClass('active-field');
			$('.active-search-field').removeClass('active-search-field');
			if($(this).parent().parent().hasClass('search-friends-field')) {
				$(this).parent().parent().addClass('search-friends-field-active');
			}
			else {
				$(this).addClass('active-field');
			}
		} );

		$('form.search input[type=text]').click( function() {
			$(this).removeClass('active-field');

			Trigwee.params.searchFieldValue = $(this).attr('class');
			var currentValue = $('form.search input[type=text]').val();
			if( currentValue == Trigwee.params.searchFieldValue )
				$(this).val("");

			$(this).parent().addClass('active-search-field');
		} );
		$('form.search input[type=submit]').hover( function() {
				$(this).addClass('active-search-submit');
			},
			function () {
				$(this).removeClass('active-search-submit');
		} );

	},

	loader_buttons: function() {
		$('button.normal-button').click( function() {
            if( $(this).hasClass('normal-button-inactive') )
                return false;
            if(
                $(this).hasClass('dream-design-continue') ||
                $(this).hasClass('dream-design-cancel')
            ) {
                //do nothing
            }
            else {
                if( 
                    $(this).hasClass('normal-button-inactive') ||
                    $(this).hasClass('prev') ||
                    $(this).hasClass('next')
                )
                    return false;

                $(this).addClass('normal-button-inactive');
            }
		} );
	}


};

var Avatar = {
	mouseDown: false,
	x: 0,
	y: 0,
	imgWidth: undefined,
	imgHeight: undefined,
	containerWidth: 188,
	containerHeight: 255,
	stop: false,
	init: function() {

		Avatar.scrollList();

		$('.muse-avatar-img-container').css( { position: 'relative' } );
		$('.muse-avatar-img-container img').css( { position: 'absolute' } );
	
		if( $('.muse-avatar-img-container img').length ) Avatar.initDrag();

		$('#own-avatar').append( $('<div id="own-avatar-output" class="hidden"></div>') );
		$('#own-avatar input[type=file]').change( function() {

			$('#own-avatar form').ajaxSubmit( {
				target: '#own-avatar-output',
				beforeSubmit: function() {
					$('#own-avatar form:first div.file span.error_message').remove();
					$('#own-avatar form:first div.file').removeClass('error');
				},
				success: function(response, st) {
					$('#own-avatar-output').append( $( response ) );
			
					var $data = $('#own-avatar-output span:first');
					var text = $data.text();
					if( $data.hasClass( 'path' ) ) {
						$('.muse-avatar-img-container img')
							.attr( 'src', text + "?" + Date.parse( new Date() ) )
							.css( { position: 'absolute', cursor: 'move', top:0, left:0 } );

						Avatar.initDrag();
					}
					else {
						$data.addClass('error_message')
							.css( 'color', '#f497bf' )
							.insertBefore( $('#own-avatar form:first input[type=file]' ) );
						$('#own-avatar form:first div.file').addClass('error');
					}	

					$('#own-avatar-output span').remove();
				}

			} );

		} );
	},

	initDrag: function() {
		$('.muse-avatar-img-container img').css( { cursor: 'hand' } );
		Avatar.x = parseInt( $('.muse-avatar-img-container img').css( 'left' ) );
		Avatar.y = parseInt( $('.muse-avatar-img-container img').css( 'top' ) );
		$('.muse-avatar-img-container img').mousedown( function(e) {
			Avatar.mouseDown = true;
			Avatar.startX = e.clientX;
			Avatar.startY = e.clientY;

			Avatar.imgWidth = $(this).width();
			Avatar.imgHeight = $(this).height();

			return false;

		} );
		$('.muse-avatar-img-container img').mouseup( function() {
			Avatar.mouseDown = false;

			$('input[name=own_avatar_x]').val( Avatar.x );
			$('input[name=own_avatar_y]').val( Avatar.y );

			return false;
		} );
			
		$('.muse-avatar-img-container img').mousemove( function(e) {
			if( !Avatar.mouseDown || Avatar.stop ) return;
		
			Avatar.x += e.clientX - Avatar.startX;
			Avatar.y += e.clientY - Avatar.startY;

			Avatar.startX = e.clientX;
			Avatar.startY = e.clientY;
			
			if( Avatar.x < 0 ) {
				if( Avatar.x < Avatar.containerWidth - Avatar.imgWidth ) {
					Avatar.x = Avatar.containerWidth - Avatar.imgWidth;
				}
			}
			else {
				Avatar.x = 0;
			}

			if( Avatar.y < 0 ) {
				if( Avatar.y < Avatar.containerHeight - Avatar.imgHeight ) {
					Avatar.y = Avatar.containerHeight - Avatar.imgHeight;
				}
			}
			else {
				Avatar.y = 0
			}


			$(this).css( {
				top: Avatar.y+'px',
				left: Avatar.x+'px'
			} );

		} );
		
		$('.muse-avatar-img-container img').mouseout( function() {
			$('.muse-avatar-img-container img').mouseup();
		} );
	},

	scrollList: function() {
		var maxWidth = $('#muse-list-wrapper .muse-list').width();
		var maxMarginLeft = maxWidth - 357;
		var marginLeft = 0;
		var selected = $('#avatar-list form input[name=avatar_fk]').val();
		var countToSelected = 0;
		var found = false;

		if(selected) {
			$('#muse-list-wrapper .muse-list li img').each( function() {
				if( !found ) countToSelected += 1;
				if( $(this).attr('alt') == selected ) {
					found = true;
					var frameCount = Math.floor( countToSelected / 5 );
					if(countToSelected % 5 == 0) frameCount -= 1;
					marginLeft = frameCount * 375;
					if( marginLeft > maxMarginLeft ) marginLeft = maxMarginLeft;
					$('.muse-list').css('margin-left', -marginLeft);
				}
			} );

		}

        if(marginLeft == 0)
            $('#avatar-list button.prev').addClass('normal-button-inactive');
        if(marginLeft == maxMarginLeft)
		    $('#avatar-list button.next').addClass('normal-button-inactive');

		$('#avatar-list button.prev').click( function() {
			if( $(this).hasClass('normal-button-inactive') ) return false;

			marginLeft = marginLeft - 375;
			if(marginLeft < 0) marginLeft = 0;

			$('.muse-list').css( { 'margin-left': -marginLeft + 'px' } );

			if(marginLeft == 0) $(this).addClass('normal-button-inactive');
			$('#avatar-list button.next').removeClass('normal-button-inactive');;

			return false;
		} );

		$('#avatar-list button.next').click( function() {
			if( $(this).hasClass('normal-button-inactive') ) return false;

			marginLeft = marginLeft + 375;
			if(marginLeft > maxMarginLeft) marginLeft = maxMarginLeft;
			
			$('.muse-list').css( { 'margin-left': -marginLeft + 'px' } );

			if(marginLeft == maxMarginLeft) $(this).addClass('normal-button-inactive');
			$('#avatar-list button.prev').removeClass('normal-button-inactive');;

			return false;
		} );
	
		$('#muse-list-wrapper .muse-list li img').click( function() {
			var id = $(this).attr('alt');
			
			$('.muse-avatar-img-container img').css( { cursor: 'hand' } );

			$('#choose-avatar .muse-avatar-img-container img')
				.attr('src', "/static/avatar/predefined/188x255/" + id + ".jpg")
				.attr('style', '');
			$('#choose-avatar .muse-avatar-img-container img').load( function() {
				$('#avatar-list form input[name=avatar_fk]').val(id);
			} );
		} );

	}



};


function debug( msg ) {
	$('#debug').html( $('#debug').html() + "<br/>" + msg );
}




var Dream = {

    init: function() {
        if( !$('#dream-design-container').length ) return;

        Dream.setEvents();
    },

    setEvents: function() {

        new focus_blur( $('input[name=title]') );
        new focus_blur( $('input[name=tags]') );

        $('button.dream-design-cancel').click( function() {
            if( $('#step-1').length == 0 ) {
                history.back();
                return false;
            }

            if( parseInt( $('#dream-design-container').css( 'margin-left' ), 10 ) == 0 ) {
                $('#step-3 #info-upload div').show();
                $('#step-3 #info-upload img').remove();
                $('#step-3 a').removeClass('active');

                $('#step-2, #step-3, #step-confirm').hide();
                $('#step-1 button:eq(0)' ).show();
                $('#step-1 button:eq(1)' ).hide();
                $('#step-1 input[name=title]').val( $('#step-1 input[name=title]').attr('default_text') );
            }
            else {
                $('#dream-design-container').animate( { marginLeft: '0' }, "slow" );
            }
            return false;
        } );

        $('#step-2 #step-2-show-more').click( function() {
            if( $('#step-2 #step-2-reload').height() > 400 ) { return false; }
            var height = parseInt( $('#step-2 #step-2-reload').height(), 10 ) + 130;
            $('#step-2 #step-2-reload').animate( { height: height }, "fast" );

            var marginTop = parseInt( $(this).css( 'margin-top' ), 10 ) + 130;
            $(this).animate( { marginTop: marginTop }, "fast", function() {
                if( $('#step-2 #step-2-reload').height() > 400 ) { $(this).hide(); }
            } );
        } );

        $('#step-3 a:eq(0)').click( function() {
            $('#info-upload, #step-3 form:eq(1)').hide();
            $('#step-3 form:eq(0)').show();
            $('#step-3 a').removeClass('active');
            $(this).addClass('active');
            return false;
        } );
        
        $('#step-3 a:eq(1)').click( function() {
            $('#info-upload, #step-3 form:eq(0)').hide();
            $('#step-3 form:eq(1)').show();
            $('#step-3 a').removeClass('active');
            $(this).addClass('active');
            return false;
        } );

		$('#step-4 select[name=realise_until]').change( function() {
			var dateContainer = $('#step-4 div.date').parents('div:first');
			if( $(this).val() == "0" ) dateContainer.css( { visibility: "visible" } );
			else dateContainer.css( { visibility: "hidden" } );
		} ).change();

        $('#step-1 form, #step-3 form:eq(1), #step-4 form').ajaxForm( {
            dataType: "json",
            beforeSubmit: function( undefined, form ) {
                $('#page-error').remove();
                var stepNr = parseInt( form.parents('div:first').attr('id').split('-')[1] );

                form.find('.error').removeClass('error');
                form.find('span.error_message').remove();
                
                if( stepNr == 1 ) {
                    $('#similar-dream-loader').show();
                    $('#step-1 button.normal-button:eq(0)').hide();
                    $('#step-1 button.normal-button:eq(1)').show();
                }
                if( stepNr == 4 ) {
                    $('#step-4 button.normal-button').addClass('normal-button-inactive');
                }
            },
            success: function( data, rs, form ) {
                var stepNr = parseInt( form.parents('div:first').attr('id').split('-')[1] );
                    
                form.find('button.normal-button').removeClass('normal-button-inactive');

                if( data.errors ) { 
                    new Validator( data, form ); 
                    if( stepNr == 1 ) {
                        $('#similar-dream-loader').hide();
                        $('#step-1 button.normal-button:eq(0)').show();
                        $('#step-1 button.normal-button:eq(1)').hide();

                    }
                    return false;
                }

                if( data.success ) {
                    if( data['preview_html'] ) {
                        $('#step-4-preview *').remove();
                        $('#step-4-preview').append( data['preview_html'] );
                    } 
                
                    if( stepNr == 1 ) {
                        $('#similar-dream-loader').hide();

                        if( $('#step-3 #info-upload img').length ) {
                            $('#step-confirm').show();
                            Dream.nextStep( 2 );
                            return;
                        }

                        if( !data['similar_html'] ) {
                            Dream.nextStep( 2 );
                            return;
                        }
                    }

                    if( stepNr == 3 ) {
                        Dream.setImg( $('#step-4-preview').find('img').attr('src') );
                        $('#step-confirm').show();
                        return;
                    }

                    if( data['similar_html'] ) {
                        $('#step-2-reload *').remove();
                        $('#step-2-reload').append( data['similar_html'] );
                    }

                    Dream.nextStep( stepNr );
                
                    if( stepNr == 4 ) document.location.href = data.url;
                }
                
            }
        } );

        $('#step-3 form:eq(0)').ajaxForm( {
            dataType: 'xml',
            success: function( data_text, rs, form ) {
                form.find('button.normal-button').removeClass('normal-button-inactive');

                var text = $(data_text).text();
                var data = eval( '(' + text + ')' );

                if( data.errors ) {
                    new Validator( data, form );
                    return false;
                }

                var src = $(data_text).find('img').attr('src');

                $('#step-4-preview *').remove();
                $('#step-4-preview').append( $(data_text).find('div:first').html() );

                Dream.setImg( src );

                $('#step-confirm').show();
            }
        } ); 
    },

    setImg: function( src ) {
        $('#step-3 #info-upload div').hide();
        $('#step-3 #info-upload img').remove();
        $('#step-3 #info-upload').append(
            $('<img />').attr( 'src', src ) );

        $('#step-3 #info-upload').show();
        $('#step-3 form').hide();
    },

    nextStep: function( stepNr ) {
        if( stepNr == 2 ) $('#step-2').hide();
        var nextStepNr = stepNr + 1;
        if( nextStepNr == 4 ) {
            $('#dream-design-container').animate( { marginLeft: '-100%' }, "slow" );
        }
        else {
            $('#step-'+nextStepNr).show();
            if( nextStepNr == 3 && $('#info-upload img').length ) {
                $('#step-confirm').show();
            } 
        }
    }

};


function Validator( data, form ) {
    var me = this;

    me.setErrors = function() {
        var errors = data.errors;

        for( var i = 0; i < errors.length; i++ ) {
            var name = errors[i]['name'];
            var message = errors[i]['message'];

            if( name == 'title' ) {
                $('#dream-design').find('input[name='+name+']:first').parents('div:first').addClass('error');
                $('#dream-design').find('input[name='+name+']:first').parents('div:first').prepend(
                    $('<span class="error_message">'+message+'</span>')
                );

            }

            form.find('input[name='+name+']:first').parents('div:first').addClass('error');
            form.find('input[name='+name+']:first').parents('div:first').prepend(
                $('<span class="error_message">'+message+'</span>')
            );
        }        
    }

    me.clearErrors = function() {
        form.find('.error').removeClass('error');
        form.find('span.error_message').remove();
    } 

    me.clearErrors();
    me.setErrors();

}





$(document)
    .ready( function() {
        
        Trigwee.init(); Dream.init();

        trigweeConversation = new TrigweeConversation();
        trigweeDream = new TrigweeDream();
        trigweeDialog = new TrigweeDialog();
    } )
    .ajaxComplete( function() {
        $('.ts').timestamp();

        setTimeout( function() { addthis.button( '.addthis_button' ); }, 500 );
    } );

