/**
 * @author jrobinson
 */
if (typeof console == "undefined" || typeof console.log == "undefined") var console = {log: function() {}};

$(function() {
	loadJavascript();
});

var loadJavascript = function() {
	var authenticated = parseInt( $('#snippets input:hidden.authenticated').val(), 10 ),
	    userObject = new Object(),
		weekdays = ['Sun','Mon','Tue','Wed','Thur','Fri','Sat'],
		months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
		limit = '25',
        pauseTimer = 5000,
		postCheckInterval = 30000,
		postsTimer = startPostsTimer(),
        map = '',
        geocoder = '',
        pageTracker = (typeof _gat != "undefined" ? _gat._getTracker( "UA-7677054-2" ) : ''),
        currentUserId = 'Anon',
		browser = $.browser;
		
		
	//====================================================================================================================================//
	//DEFAULT BEHAVIOURS FOR FORM ELEMENTS
	//====================================================================================================================================//
	$( 'input:text, textarea' ).live( 'focus', function() {
		$( this ).addClass( 'focus' ).removeClass('default').select();
		console.log('focus field or textarea');
	}).live( 'blur', function() {
		$( this ).removeClass( 'focus' );
        var defaultVal = $( this ).attr( 'defaultVal' ),
            currentVal = $( this ).val();
        
		if( currentVal === defaultVal || currentVal === '' ) {
            $( this ).addClass( 'default' );
            $( this ).val( defaultVal );
        }
		console.log('blur field or textarea');
	});
	
    //====================================================================================================================================//
	//_contact handlers
	//====================================================================================================================================//
	$( '#utility a.contact' ).live( 'click', function() {
        $( '#registration, #welcome' ).hide();
        $( '#contact' ).toggle(); 
    });
	$( '#contact a.close' ).click(function() {
       $( '#contact' ).hide(); 
    });
	
	//====================================================================================================================================//
    // _maps
	//====================================================================================================================================//
	$( '#mapWrapper div.where a.go' ).click( function() {
        var whereField = $( this ).siblings( 'input:text.where' ),
            address = $( whereField ).val();
            
        if( address !== ( $( whereField ).attr( 'defaultval' ) || '' ) ) {
            findAddress( address );
        }
        else {
            $( whereField ).select();
        }
    });
    $( '#mapWrapper div.where input:text' ).keypress( function(event) {
		if( event.keyCode === 13 ) {
			$( '#mapWrapper div.where a.go' ).click();
		}
	});
    $( '#mapWrapper div.where input:text' ).focus( function() {
        $( '#mapWrapper div.where a.go' ).css('background-color','#FFFDE2');
    }).blur(function() {
        $( '#mapWrapper div.where a.go' ).css('background-color','#ffffff');
    });
    
	function initMap() {
        if (typeof GMap2 == "undefined") {
		    return;	
		}
        map = new GMap2( document.getElementById( "map" ) );
		geocoder = new GClientGeocoder();
		
        map.setUIToDefault();
		map.disableScrollWheelZoom();
		centreMap();
    }
    
	function centreMap() {
		var params = $.toJSON( {"key": "defaultLocation"} );
		
		$.ajax({
			type: "POST",
			url: BASE_URL + "users/getUserData",
			data: params,
			dataType: "json",
			error: function( xmlHttpRequest, textStatus, errorThrown ) {
				console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
			},
			success: function( data ) {
                if( data.msg.type === "success" ) {
                    var lat = parseFloat(data.msg.userdata.lat),
                        lng = parseFloat(data.msg.userdata.lng),
                        zoom = parseInt(data.msg.userdata.zoom, 10);
                        
                    map.setCenter( new GLatLng( lat, lng ), zoom );
				}
				else {
					map.setCenter(new GLatLng(51.514, -0.137), 10);
				}
            },
            complete: function() {
                GEvent.addListener( map, 'moveend', function() {
                    setUserDefaultLocation();
                    getPosts( 'replace' );
                });
                setUserDefaultLocation();
            }
		});
	}
	
	function getPlacename() {
		geocoder.getLocations( map.getCenter(), function( response ) {
            if( response.Placemark ) {
                var place = response.Placemark[0],
				    address = place.address,
					placeName = 'UK';
                
				console.log( place );
				
				if( place !== '' || place !== undefined ) {
					if( place.AddressDetails.Country.AdministrativeArea !== undefined ) {
						placeName = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
						
						if( place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea !== undefined ) {
							placeName = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
							
							if( place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality !== undefined ) {
								placeName = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.DependentLocality.DependentLocalityName;
							}
						}
					}
					else if( place.AddressDetails.Country.Locality !== undefined ) {
						placeName = place.AddressDetails.Country.Locality.LocalityName;
						
						if( place.AddressDetails.Country.Locality.DependentLocality !== undefined ) {
							placeName = place.AddressDetails.Country.Locality.DependentLocality.DependentLocalityName;
						}
					}
				}
			}
			$( '#mapWrapper input:hidden.placename, #mapWrapper input:text.where' ).val( placeName );
		});
	}
    
    function findAddress( address ) {
        geocoder.getLatLng( address, function(point) {
            if (!point) {
                alert(address + " not found");
            }
            else {
                map.setCenter(point, map.getZoom());
            }
        });
    }
	
	function getMapBounds() {
        var bounds = map.getBounds(),
			southWest = bounds.getSouthWest(),
			northEast = bounds.getNorthEast(),
			jsonArray = {"ne": {"lat": northEast.lat(), "lng": northEast.lng()}, "sw": {"lat": southWest.lat(), "lng": southWest.lng()}};
			
		return jsonArray;
	}
    
    function setUserDefaultLocation() {
		var point = map.getCenter(),
            lat = point.lat(),
            lng = point.lng(),
			zoom = map.getZoom(),
            placename = getPlacename(),
			bounds = map.getBounds(),
            southWest = bounds.getSouthWest(),
			northEast = bounds.getNorthEast(),
			defaultBounds = $.toJSON( {"key" : "defaultBounds", "value" : {"ne": {"lat": northEast.lat(), "lng": northEast.lng()}, "sw": {"lat": southWest.lat(), "lng": southWest.lng()}}} ),
			defaultLocation = $.toJSON( {"key" : "defaultLocation", "value" : {"lat" : lat, "lng" : lng, "zoom" : zoom}} );
		
        $( '#mapWrapper input:hidden.lat' ).val( lat );
        $( '#mapWrapper input:hidden.lng' ).val( lng );
		$( '#mapWrapper input:text.where' ).val( placename );
        
        setUserData( defaultBounds );
        setUserData( defaultLocation );
	}
	
    function placeMarker( lat, lng ) {
        var point = new GLatLng( lat, lng );
        map.clearOverlays();
        map.addOverlay( new GMarker(point) );
    }
    
	//====================================================================================================================================//
	// _search FUNCTIONS
	//====================================================================================================================================//
	$( '#search a.search' ).click(function() {
		if( $( '#search input:text' ).val() !== '' ) {
            $( '#items ul' ).css( 'opacity', 0.5 );
            $( '#items div.searchFeedback' ).show();
            $( '#search a.clearSearch' ).show();
            getPosts( 'replace' );
        }
    });
    
	$( '#search input:text' ).keypress(function(event) {
		if( event.keyCode === 13 ) {
			$( '#search a.search' ).click();
		}
	});
    
    $( '#search a.clearSearch' ).live( 'click', function() {
        clearSearch();
    });
    
    function clearSearch() {
        $( '#search input:text' ).val('');
        $( '#search a.clearSearch' ).hide();
        $( '#items ul' ).css( 'opacity', 0.5 );
        $( '#items div.searchFeedback' ).show();
        getPosts( 'replace' );
    }
    
    function saveSearch() {
		var searchTerm = $( '#items .searchFeedback span.label strong' ).text();
		
		var li = $( '#snippets div.savedSearches' ).html();
		li = li.replace( '%SEARCHTERM%', searchTerm);
		$( '#search .savedSearches ul.searches' ).append( li );
		
		$( '#items .searchFeedback a.saveSearch' ).before( '<span class="confirm">Search saved</span>' ).hide();
	}
	
    //====================================================================================================================================//
	// _posts _items FUNCTIONS
	//====================================================================================================================================//
    $( '#items ul li div.actions a.tellAFriend' ).live( 'click' , function() {
		$( this ).parent('div.actions').siblings( 'div.tellAFriend' ).toggle();
    });
	
	$( '#items ul li div.actions a.contactUser' ).live( 'click', function() {
        var form = $(this).parent('div.actions').siblings('div.contactUser');
        if( $(form).is(':hidden')) {
			if( authenticated===1 ) {
				$( form ).children( 'input.email' ).hide();
			}
			$( form ).show();
        }
		else {
            $( form ).hide().children('input, textarea').removeClass('error').show().end().children('div.error').remove();
			$( form ).siblings( '.actions' ).show();
        }
		//$( form ).children('textarea').removeClass('default').addClass('focus').select();
	});
	
    $( '#items ul li div.actions a.flag' ).live( 'click', function() {
		flagPost( ( $( this ).parents( 'li.offered' ).attr( 'id' ) ).replace( 'post_', '') );
	});
	
	$( '#items ul li a.cancel' ).live( 'click', function() {
		$(this).siblings('textarea').val( $(this).siblings('textarea').attr('defaultVal') ).addClass('default');
        $(this).parent('div.form:visible').children('input, textarea').removeClass('error').siblings('div.error').remove();
        $(this).parent( 'div.form:visible' ).hide().siblings('.actions').show();
	});
	
    $( 'a.saveSearch' ).live( 'click', function() {
        saveSearch();
    });
	
    $( '#items ul li div.contactUser a.send' ).live('click', function() {
        var id = ( $( this ).parents( 'li.offered' ).attr( 'id' ) ).replace( 'post_', '');
		iWantThis( id );
	});
	
	$( '#items ul li div.contactUser input:text' ).live('keypress', function( event ) {
		if( event.keyCode === 13 ) {
            var id = ( $( this ).parents( 'li' ).attr( 'id' ) ).replace( 'post_', '');
		    iWantThis( id );
		}
	});
	
	$( '#items ul li div.tellAFriend a.send' ).live( 'click', function() {
		var id = ( $( this ).parents( 'li.offered' ).attr( 'id' ) ).replace( 'post_', '');
		tellAFriend( id );
	});
	
    $( '#items ul li div.tellAFriend input:text' ).live('keypress', function( event ) {
		if( event.keyCode === 13 ) {
			var id = ( $( this ).parents( 'li' ).attr( 'id' ) ).replace( 'post_', '');
		    tellAFriend( id );
		}
	});
    $( '#items a.location' ).live('click', function() {
        var lat = $(this).siblings('input:hidden.lat').val(),
            lng = $(this).siblings('input:hidden.lng').val();
            
        placeMarker( lat, lng );
    });
    $('#items .loadNewPosts a').click(function() {
        getPosts( 'replace' );
        $( '#items .loadNewPosts' ).hide(); 
    });

	function getOffset() {
        var offset = $( '#items ul li' ).size();
        return offset;
    }
    
    function newPostsFeedback( data ) {
		var newPostsCount = data.count;
		
		if( newPostsCount > 0 ) {
			snippet = 'There are <strong>'+newPostsCount+'</strong> new posts waiting to be loaded. <a class="getNewPosts">Load new posts</a>';
		}
	}
	
	function checkForNew() {
        var fromPostID = getFirstPostId(),
            searchQuery = getSearchTerm(), 
            bounds = getMapBounds(), 
            params = $.toJSON( {"types": ["offered"], "groups" : ["all"], "limit" : limit, "fromPostID" : fromPostID, "searchQuery" : searchQuery, "bounds" : bounds} );
        
        $.ajax({
            type: "POST",
            url: BASE_URL + "posts/checkForNew",
            data: params,
            dataType: "json",
            error: function(xmlHttpRequest, textStatus, errorThrown){
                console.log('xmlHttpRequest : ' + xmlHttpRequest + ', textStatus : ' + textStatus + ', errorThrown : ' + errorThrown);
            },
            success: function(data){
                if (data.msg.type !== 'error') {
                    var count = parseInt(data.msg.count, 10);
                    if (count > 0) {
                        $('#items div.loadNewPosts').find('.count').text(count).end().show();
                    }
                }
                else {
                    postsTimer = 0;
                    return false;
                }
            }
        });
    }

    function getSearchTerm() {
        var searchTerm = $( '#search input:text' ).val();
        
        return searchTerm;
    }
    
    function getNewPosts() {
        $( '#items ul' ).css( 'opacity', 0.5 );
        getPosts( 'replace' );
    }
    
    function getOlderPosts() {
        var searchQuery = getSearchTerm(),
			bounds = getMapBounds(),
            toPostID = getLastPostId(),
            params = "";
            
        if( $( '.noMorePostsToFetch' ).is(':hidden') && $( '.endlessScrollLoader' ).is( ':hidden' ) ) {
            $( '.endlessScrollLoader' ).show();
            
            params = $.toJSON( {"types": ["offered"], "groups" : ["all"], "limit" : limit, "toPostID" : toPostID, "searchQuery" : searchQuery, "bounds" : bounds} );
            
            $.ajax({
    			type: "POST",
    			url: BASE_URL + "posts/get",
    			data: params,
    			dataType: "json",
    			error: function( xmlHttpRequest, textStatus, errorThrown) {
    				console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
    				growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
    			},
    			success: function( data ) {
                    if( data.msg.type !== 'error' ) {
                        var postsCount = data.msg.posts.length;
                        if ( postsCount > 0 ) {
                            buildPostList( data, 'append' );
                        }
                        else {
                            $( '.endlessScrollLoader' ).hide();
                            $( '.noMorePostsToFetch' ).show();
                            return false;
                        }
    				}
    				else {
    					alert( data.msg.text );
    					return false;
    				}
    			}
    		});
        }
    }
    
	function getPosts( listRefreshType ) {
		var searchQuery = getSearchTerm(),
			bounds = getMapBounds(),
            params = "";
            
        $( '#items ul' ).css( 'opacity', 0.5 );
        $( '#items div.searchFeedback' ).show();
        
       params = $.toJSON( {"types": ["offered"], "groups" : ["all"], "limit" : limit, "searchQuery" : searchQuery, "bounds" : bounds} );
        
		$.ajax({
			type: "POST",
			url: BASE_URL + "posts/get",
			data: params,
			dataType: "json",
			error: function( xmlHttpRequest, textStatus, errorThrown) {
				console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
				growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
			},
			success: function( data ) {
				if( data.msg.type !== 'error' ) {
                    var postsCount = data.msg.posts.length;
                    if ( postsCount > 0 ) {
                        $( '.noMorePostsToFetch' ).hide();
                        buildPostList( data, 'replace' );
                    }
                    else {
						if(listRefreshType==='replace') {
							$( '#items div.loadNewPosts' ).hide();
				            $( '.searchFeedback' ).hide();
							var snippet = '<li class="noPostsToShow"><p><strong>Nothing matches your search</strong><br />Broaden your search area by <strong>zooming out</strong></p></li>';
                            $( '#items ul' ).html(snippet);
							return false;
						}
                        $( '.endlessScrollLoader' ).hide();
                        $( '.noMorePostsToFetch' ).show();
                        return false;
                    }
				}
				else {
					alert( data.msg.text );
					return false;
				}
			},
            complete: function() {
                $( '#items ul' ).css( 'opacity', 1 );
                updateRssLink();
            }
		});
	}
	
	function buildPostList( data, listRefreshType ) {
        var newItem = $( '#snippets div.postsSnippet' ).html(),
            snippet = '',
			posts = data.posts,
			postDate,
			postDay,
			postMonth,
			postDayDate,
			postTime,
			postHoursAgo,
			postMinutesAgo,
            postSecondsAgo,
            timeString,
			postId,
			title,
            title_highlighted,
			description,
			groupName,
            locationDescription,
            location_x,
            location_y,
			type,
			fragment;
			
		$.each( data.msg.posts, function( n ) {
			postDay = this.post_day_of_week;
			postMonth = this.post_month;
			postHoursAgo = this.post_hours_ago;
			postMinutesAgo = this.post_minutes_ago;
            postSecondsAgo = this.post_seconds_ago;
			
            if ( postHoursAgo >= 24 ) {
                timeString = Math.floor( ( postHoursAgo / 24 ) ) +' days ago';
            }
            else if (postHoursAgo < 24 && postHoursAgo > 0) {
                timeString = postHoursAgo + ' hours ago';
            }
            else if (postMinutesAgo > 1) {
                timeString = postMinutesAgo + ' minutes ago';
            }
            else if( postMinutesAgo === 1 ) {
                timeString = postMinutesAgo + ' minute ago';
            }
            else {
                timeString = postSecondsAgo + ' seconds ago';
            }
            
			type = this.type;
			postId = this.id;
            
            title = (this.title).replace('"', "'");
            title_highlighted = title;
			description = (this.content).replace('"', "'");
			groupId = this.group_id;
      		groupName = this.group_name;
            locationDescription = this.location_description;
            location_x = this.location_x;
            location_y = this.location_y;
            
            fragment = newItem;
			
            if( getSearchTerm() !== '' ) {
                title_ed = hiliteSearchTerm( title );
                description = hiliteSearchTerm( description );
            }

			fragment = fragment.replace( new RegExp( '%POSTID%', 'g' ), postId );
			fragment = fragment.replace( new RegExp( '%TYPE%', 'g' ), type );
			fragment = fragment.replace( new RegExp( '%TITLE%', 'g' ), title );
			fragment = fragment.replace( new RegExp( '%TITLE_HIGHLIGHTED%', 'g' ), title_highlighted );
			fragment = fragment.replace( new RegExp( '%DESCRIPTION%', 'g' ), description );
            if (locationDescription !== "" && locationDescription !== null) {
                fragment = fragment.replace( new RegExp( '%POSTLOCATION%', 'g' ), locationDescription );
            }
            else if (groupName !== "" && groupName !== null) {
                fragment = fragment.replace( new RegExp( '%POSTLOCATION%', 'g' ), groupName );
            }
            else {
                fragment = fragment.replace( new RegExp( '%POSTLOCATION%', 'g' ), "Unspecified location");
            }
            fragment = fragment.replace( new RegExp( '%LOCATION_X%', 'g' ), location_x );
            fragment = fragment.replace( new RegExp( '%LOCATION_Y%', 'g' ), location_y );
            fragment = fragment.replace( new RegExp( '%TIME_AGO%', 'g' ), timeString );
			
			snippet += fragment;
		});
		
		if ( snippet === "" ) {
            snippet = "<li>Nothing matches your search! Zoom out on the map to search a wider area.</li>";
        }
        
        if( listRefreshType === 'replace' ) {
            $( '#items div.loadNewPosts' ).hide();
            $( '#items ul' ).html( snippet );
            $( '.searchFeedback' ).hide();
            $( document ).scrollTop( 0 );
        }
        else if( listRefreshType === 'append' ) {
			$( '#items ul' ).append( snippet );
            $( '.endlessScrollLoader' ).hide();
        }
        else if( listRefreshType === 'prepend' ) {
            $( '#items ul' ).prepend( snippet ).fadeIn();
        }
		
		$( '#items ul' ).css( 'opacity', 1 );
        $( '#items div.searchFeedback' ).hide();
    }
    
	function getFirstPostId() {
		var fromId = ( $( '#items ul li.offered:first' ).attr( 'id' ) ).replace( 'post_', '' );
		return fromId;
	}
	
	function getLastPostId() {
		var fromId = ( $( '#items ul li:last' ).attr( 'id' ) ).replace( 'post_', '' );
		return fromId;
	}
	
    function startPostsTimer() {
		$( '#items' ).everyTime( postCheckInterval, function( i ) {
			checkForNew();
		});
	}
	
	function hiliteSearchTerm( snippet ) {
        var searchTerm = $( '#search .searchField input:text' ).val(),
            newSnippet = snippet.replace( new RegExp(searchTerm, "gi") , '<em class="searchTerm">'+ searchTerm +'</em>' );
		
		return newSnippet;
	}
	
	function saveItem() {
		var title = $( 'div.offerItem input:text.title' ).val(),
			defaultTitle = $( 'div.offerItem input:text.title' ).attr( 'defaultval' ),
			description = $( 'div.offerItem textarea.description' ).val(),
			defaultDescription = $( 'div.offerItem textarea.description' ).attr( 'defaultval' ),
			lat = $( '#mapWrapper input:hidden.lat' ).val(),
			lng = $( '#mapWrapper input:hidden.lng' ).val(),
			placename = $( '#mapWrapper input:hidden.placename' ).val(),
			postToFacebook = false;
			
			if(placename === '' || placename === null) { 
                placename = "UK";
			}
			if( $('div.offerItem div.postToFacebook:visible a').is('.yes') ) {
				postToFacebook = true;
			}
		
		if( ( title !== '' && title !== defaultTitle ) && ( description !== '' && description !== defaultDescription ) ) {
            //Give the button an ajax spinner to show the state of the process happening
            $( 'div.offerItem a.add span.icon' ).attr( 'class', 'loading' );
			params = $.toJSON( {"title": title, "content" : description, "location" : {"lat" : lat,"lng" : lng}, "location_description" : placename, "postToFacebook" : postToFacebook} );
			
			$.ajax({
				type: "POST",
				url: BASE_URL + "posts/add",
				data: params,
				dataType: "json",
				error: function( xmlHttpRequest, textStatus, errorThrown) {
					console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
					growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
				},
				success: function( data ) {
					if( data.msg.type === 'success' ) {
                        growl( "Added successfully", 'confirmation' );
						$( 'div.offerItem a.add span.icon' ).removeClass( 'loading' );
                        $( 'div.offerItem' ).hide( 'normal', function() {
                            $( 'div.offerItem input:text.title' ).val( $( 'div.offerItem input:text.title' ).attr( 'defaultval' ) ).select();
                            $( 'div.offerItem textarea' ).val( $( 'div.offerItem textarea' ).attr( 'defaultval' ) );
                            $( '#offerItemButton' ).removeClass( 'open' );
                        });
					}
					else {
						showMessage( data.msg.text, $( 'div.offerItem' ) );
						return false;
					}
				}
			});
		}
		else if( title === '' || title === defaultTitle ) {
			error( 'field', 'You must enter a title', $( 'div.offerItem input:text.title' ) );
			return false;
		}
		else if( description === '' || description === defaultDescription ) {
			error( 'field', 'You must enter a description', $( 'div.offerItem textarea.description' ) );
			return false;
		}
	}
	
	function iWantThis( id ) {
		//CHECK TO SEE IF THE USER HAS ALREADY CLICKED TO PREVENT MULTIPLE CLICKING
        if ($('#post_' + id).find('div.contactUser a.send span.icon').is(':visible')) {
            var textarea = $('#post_' + id).find('div.contactUser').children('textarea.message'),
			    message = textarea.val(),
			    //debugToEmail = "justinteractive@gmail.com",
                email = '';
            
			//IF USER IS LOGGED IN GET THEIR EMAIL ADDRESS FROM THE BACKEND AS WE DIDN'T DISPLAY THE EMAIL FIELD
			if( authenticated === 1 ) {
				if( userObject.loggedInAsUsername ) {
					email = userObject.loggedInAsUsername;
				}
				else if( userObject.fbEmail ) {
					email = userObject.fbEmail;
				}
				else {
					alert('need to check the logic in iWantThis');
				}
			}
			else {
				email = $('#post_' + id).find('div.contactUser').children('input:text.email').val();
				if (!isValidEmailAddress(email)) {
	                error('field', "This is not an email address", $('#post_' + id).find('div.contactUser').children('input:text.email'));
					return false;
	            }
			}
			
			if( message === $( textarea ).attr('defaultval') ) {
				message = '';
			}
            
			//DEBUG PARAMS
			//var params = $.toJSON( {'myEmail': email, 'debugToEmail' : debugToEmail, 'postId' : id, 'message' : message} );
            //PRODUCTION PARAMS
			var params = $.toJSON( {'myEmail': email, 'postId' : id, 'message' : message} );
			    
            //ADD LOADING SPINNER TO THE BUTTON
            $("#post_" + id).find('div.contactUser a.send span.icon').removeClass('icon').addClass('loading');
			
            $.ajax({
                type: "POST",
                url: BASE_URL + "posts/iWantThis",
                data: params,
                dataType: "json",
                error: function( xmlHttpRequest, textStatus, errorThrown) {
                    console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                    growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
                },
                success: function( data ) {
                    if( data.msg.type !== 'error' ) {
                        growl( data.msg.text, 'confirmation' );
                    }
                    else {
                        growl( data.msg.text, 'error' );
                        return false;
                    }
                },
                complete: function() {
                    if( authenticated === 0 ) {
				        setNewDefaultMyEmail( email );
				    }
				    //REMOVE LOADING SPINNER TO THE BUTTON AND RESET ALL THE DEFAULTS
	                $( textarea ).siblings('a.send').children('span.loading').attr('class', 'icon');
				    $( textarea ).val( $( textarea ).attr( 'defaultval' ) ).removeClass('focus').addClass('default');
				    var form = $( textarea ).parent('div.form');
				    $( form ).hide('fast', function() {
						$( form ).children('input, textarea').removeClass('error').end().children('div.error').remove();
	                    $( form ).siblings( '.actions' ).show();
					});
                }
            });
        }
		else {
			growl( "Hold tight, give us another second or two. If it doesn't happen, cancel and try again.", "confirmation");
		}
	}
	
	function tellAFriend( id ) {
		var myEmail = $( '#post_'+id ).find( 'div.tellAFriend' ).children( 'input:text.myEmail' ).val(),
            friendsEmail = $( '#post_'+id ).find( 'div.tellAFriend' ).children( 'input:text.friendsEmail' ).val(),
			params = $.toJSON( {"fromEmail" : friendsEmail, "toEmail": myEmail,"postId" : id} );
		
        if( !isValidEmailAddress( myEmail ) ) {
            error( 'field', "This is not an email address", $( '#post_'+id ).find( 'div.tellAFriend' ).children( 'input:text.myEmail' ) );
        }
        else if( !isValidEmailAddress( friendsEmail ) ) {
            error( 'field', "This is not an email address", $( '#post_'+id ).find( 'div.tellAFriend' ).children( 'input:text.friendsEmail' ) );
        }
        else {
            $( "#post_"+id ).find( 'div.tellAFriend a.send' ).addClass( 'ajaxSpinner' );
		
    		$.ajax({
    			type: "POST",
    			url: BASE_URL + "posts/tellAFriend",
    			data: params,
    			dataType: "json",
    			error: function( xmlHttpRequest, textStatus, errorThrown) {
    				console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
    				growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
    			},
    			success: function( data ) {
					var message = '',
                        email = '';
						
    				if( data.msg.type === 'success' ) {
    					message = data.msg.text;
            			email = $( "#post_"+id ).find( 'div.tellAFriend.form input:text.myEmail' ).val();
                            
            			growl( message, "error" );
                        
                        setTimeout( function() {
                			$( '#post_'+id ).find( 'div.tellAFriend' ).hide('normal', function() {
                                $( this ).find( 'input:text.friendsEmail' ).val( $( this ).find( 'input:text.friendsEmail' ).attr( 'defaultval' ) );
                                setNewDefaultMyEmail( email );
                            });
                		}, 5000);
    				}
    				else {
    					message = data.msg.text;
                        growl( message, "error" );
    				}
    			},
    			complete: function() {
    				$( '#post_'+id ).find( 'a.send' ).removeClass( 'ajaxSpinner' );
    			}
    		});  
        }
    }
	
    function flagPost( id ) {
        //feedback changes label to read Flagging...
        $( '#post_'+ id +' a.flag' ).text( 'Flagging post...' );
        
        var reason = "inappropriate",
		    postTitle = $( '#post_'+ id +' strong.title' ).text(),
            params = $.toJSON( {"postId" : id, "reason": reason} );
            
        $.ajax({
			type: "POST",
			url: BASE_URL + "posts/flagAsJunk",
			data: params,
			dataType: "json",
			error: function( xmlHttpRequest, textStatus, errorThrown) {
				console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
				growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
			},
			success: function( data ) {
				if( data.msg.type === 'success' ) {
					$( '#post_'+id ).fadeOut('normal', function() {
                        $( this ).remove();
                    });
				}
				else {
					var message = data.msg.text;
                    growl( message, "error" );
				}
			},
			complete: function() {
                $( '#post_'+ id +' a.flag' ).text( 'Flag as inappropriate' );
				var message = postTitle+ ' has been flagged for review. Thank you';
				growl( message, "confirmation" );
			}
		});  
    }
	
	//====================================================================================================================================//
	// _offer ITEM EVENTS
	//====================================================================================================================================//
	$( '#offerItemButton' ).click(function() {
		if(authenticated === 1) {
			if( userObject.loggedInToFB === true ) {
				$('div.offerItem div.postToFacebook').show();
				$('div.offerItem div.facebookConnect').hide();
			}
			else {
				$('div.offerItem div.postToFacebook').hide();
				$('div.offerItem div.facebookConnect').show();
			}
			$('div.offerItem a.add span.loading').attr('class', 'icon');
			$('div.offerItem input:text').val( $('div.offerItem input:text').attr('defaultval') );
			$('div.offerItem textarea').val( $('div.offerItem textarea').attr('defaultval') );
			$('div.offerItem').slideToggle().children( 'input, textarea' ).addClass('default').removeClass('error');
			$('div.offerItem input:text:first').addClass('focus').removeClass('default').select();
			$('div.error').remove();
		}
		else {
			$('#registration div.forgotPassword').hide();
            $('#registration, #registration div.facebook, #registration div.signup').show();
			$('#registration input:text:first').removeClass('default').addClass('focus').select();
		}
    });
	$( 'div.offerItem a.cancel, div.offerItem a.close' ).live('click', function() {
		$( 'div.offerItem').hide().children( 'input, textarea' ).addClass('default').val( $(this).attr('defaultval'));
        $('div.offerItem input, div.offerItem textarea').removeClass('error');
        $('div.error').remove();
	});
	$( 'div.offerItem a.add' ).live('click' , function() {
		saveItem();
	});
	$( 'div.offerItem a.addImage').live('click', function() {
		$( 'div.offerItem a.addImage' ).html( 'oldpairofPants.jpg | <u>pick different picture</u>' )
	});
	
	$('div.offerItem div.postToFacebook a').live('click', function() {
		$( this ).toggleClass('yes');
		if($( this ).hasClass('yes') ) {
			$( this ).children('input:checkbox').attr('checked','checked');
		}
		else {
			$( this ).children('input:checked').attr('checked','');
		}
	});
	
	//====================================================================================================================================//
    // _user FUNCTIONs
    //====================================================================================================================================//
    $( '#utility a.signIn').live( 'click', function() {
		$('#registration div.forgotPassword').hide();
        $('#registration, #registration div.facebook, #registration div.signup, #registration p.or').show();
		$('#registration input:text:first').removeClass('default').addClass('focus').select();
    });

    function onFacebookSessionChange(response)
    {
        if (response.session) {
            if (response.perms) {
                // user is logged in and granted some permissions.
                // perms is a comma separated list of granted permissions

                // TODO check the permissions
                var params = $.toJSON( {} );

                $.ajax({
                    type: "POST",
                    url: BASE_URL + "users/fbSignIn",
                    data: params,
                    dataType: "json",
                    error: function( xmlHttpRequest, textStatus, errorThrown) {
                        console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                        alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
                        $( '#registration a.signIn span.loading' ).removeClass( 'loading' ).addClass( 'icon' );
                    },
                    success: function( data ) {
                        if( data.msg.type === 'success' ) {
                            $( '#registration' ).hide();
                            growl( "You're connected to Facebook" );
							$('div.leftCol div.offerItem').hide();
                            whoAmI();
                        }
                        else {
                            error( 'field', data.msg.text, $( '#registration div.signin label.email' ) );
                        }
                    }
                });
            } else {
             // user is logged in, but did not grant any permissions
            }
        } else {
            // user is not logged in
            whoAmI();
		}
    }

    $('.fbLoginButton').click(function() {
        FB.login(onFacebookSessionChange, {
            perms:'read_stream,publish_stream,offline_access'
        });
    });
	
	$('#registration a.close, #registration div.signup a.cancel').click(function() {
		$('#registration').hide();
	});
	
	$('#registration div.forgotPassword a.cancel').live('click', function() {
		$('#registration div.forgotPassword').hide();
		$('#registration div.facebook, #registration div.signup, #registration p.or').show();
	});
	
    $( '#utility a.signOut').live( 'click', function() {
        signOut();
    });
	
    $("#registration fieldset.password a").live( 'click', function() {
        if( !$(this).is('.active') ) {
            $("#registration fieldset.password a").toggleClass('active');
            if( $(this).is('.passwordYes') ) {
                $(this).siblings('input:text.password').val('Enter your password');
            }
            else {
                $(this).siblings('input:text.password').val('Choose a password');
            }
        }
    });
	
    $( '#registration a.signIn' ).live( 'click', function() {
        register();
    });
	
    $( '#registration div.signup input:text' ).live('keypress', function( event ) {
        if( event.keyCode === 13 ) {
            register();
        }
    });
	
	$('#registration div.signup a.forgotPassword ').live('click', function(object) {
		var email = $('#registration input:text.email').val();
		$('#registration div.signup, #registration p.or, #registration div.facebook').hide();
		$('#registration div.forgotPassword').show();
		$('#registration div.forgotPassword input:text.email').val( $('#registration div.signup').val() ).select();
	});
	
	$('#registration a.sendReminder').live('click', function() {
		passwordReminder();
	});
	$( '#registration div.forgotPassword input:text' ).live('keypress', function( event ) {
        if( event.keyCode === 13 ) {
            passwordReminder();
        }
    });
	
    if( $( '#flashErrorMessageContainer:visible' ) ) {
        var timer = setTimeout( hideFlashErrorMessageContainer, pauseTimer );
    }
    
	function passwordReminder( email ) {
		var email = $('#registration div.forgotPassword input:text.email').val();
		
		//show loader on button
		$('#registration a.sendReminder span.icon').removeClass('icon').addClass('loading');
		
		//if email is not valid show error message
        if(!isValidEmailAddress( email )) {
            error( 'field', 'Not a valid email address', $('#registration div.forgotPassword input:text.email') );
			//remove loader on button
            $('#registration a.sendReminder span.icon').removeClass('loading').addClass('icon');
        }
		else {
			var params = $.toJSON( {"username" : email} );
            $.ajax({
	            type: "POST",
	            url: BASE_URL + "users/passwordReminder",
	            data: params,
	            dataType: "json",
	            error: function( xmlHttpRequest, textStatus, errorThrown) {
	                console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
	                growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
	            },
	            success: function( data ) {
	                if( data.msg.type === 'success' ) {
	                    growl( "Password reminder sent to "+ email, "confirmation" );
						$('#registration a.close').click();
	                }
	                else {
	                    error( 'field', data.msg.text, $( '#registration label.email' ) );
	                }
	            },
				complete: function() {
					//remove loader on button
                    $('#registration a.sendReminder span.loading').removeClass('loading').addClass('icon');
				}
	        });
		}
	}
	
	function register() {
		var username = $( '#registration input.email' ).val(),
            password = $( '#registration input.password' ).val(),
            params = $.toJSON( {"username" : username} );
			
		$.ajax({
            type: "POST",
            url: BASE_URL + "users/getUsername",
            data: params,
            dataType: "json",
            error: function( xmlHttpRequest, textStatus, errorThrown) {
                console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
				$( '#registration a.signIn span.loading' ).removeClass( 'loading' ).addClass( 'icon' );
            },
            success: function( data ) {
				console.log('username exists = '+ data.exists);
                if( data.exists === 'yes' ) {
					signIn(username, password);
                }
                else {
					signUp(username, password);
                }
            }
        });
	}
	
	function signUp(username, password) {
        var params = $.toJSON( {"username" : username, "password" : password} );
        
        $( '#registration a.signIn span.icon' ).removeClass('icon').addClass( 'loading' );
        
		$.ajax({
            type: "POST",
            url: BASE_URL + "users/signUp",
            data: params,
            dataType: "json",
            error: function( xmlHttpRequest, textStatus, errorThrown) {
                console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
            },
            success: function( data ) {
                if( data.msg.type === 'success' ) {
                    growl( "We've sent you an email to confirm your address.", "confirmation" );
					$('#registration a.close').click();
                    whoAmI();
                }
                else {
                    error( 'field', data.msg.text, $( '#registration label.email' ) );
					growl( data.msg.text, "error" );
                }
            },
            complete: function() {
                $( '#registration a.signIn span.loading' ).removeClass( 'loading' ).addClass( 'icon' );
            }
        });
    }
    
    function signIn(username, password) {
		var params = $.toJSON( {"username" : username, "password" : password} );
		
		$( '#registration a.signIn span.icon' ).removeClass('icon').addClass( 'loading' );
            
        $.ajax({
            type: "POST",
            url: BASE_URL + "users/signIn",
            data: params,
            dataType: "json",
            error: function( xmlHttpRequest, textStatus, errorThrown) {
                console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
                $( '#registration a.signIn span.loading' ).removeClass( 'loading' ).addClass( 'icon' );
            },
            success: function( data ) {
                if( data.msg.type === 'success' ) {
					$('#registration').hide();
					whoAmI();
                    growl( "You're signed in", "confirmation" );
                }
                else {
                    error( 'field', data.msg.text, $( '#registration label.email' ) );
					growl( data.msg.text, "error" );
                }
            },
            complete: function() {
                $( '#registration a.signIn span.loading' ).removeClass( 'loading' ).addClass( 'icon' );
            }
        });
    }
    
    function signOut() {
        $.ajax({
            type: "POST",
            url: BASE_URL + "users/signOut",
            dataType: "json",
            error: function( xmlHttpRequest, textStatus, errorThrown) {
                console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
            },
            success: function( data ) {
                if( data.msg.type !== 'error' ) {
					whoAmI();
					growl( "You're signed out", "confirmation" );
                    $( "#registration input.password" ).val( $( "#registration input.password" ).attr( 'defaultVal' ) ).addClass( 'default' );
                }
                else {
                    growl( data.msg.text, 'error' );
                    return false;
                }
            }
        });
    }
    
    function whoAmI() {
        $.ajax({
            type: "POST",
            url: BASE_URL + "users/whoami",
            dataType: "json",
            error: function( xmlHttpRequest, textStatus, errorThrown) {
                console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
            },
            success: function( data ) {
                if( data.msg.type === "success" ) {
                    if( data.msg.loggedInToFB === true ) {
						authenticated = 1;
						userObject.loggedInToFB = data.msg.loggedInToFB;
                        userObject.fbID = data.msg.fbUserData.id;
                        userObject.fbUsername = data.msg.fbUserData.name;
                        userObject.fbEmail = data.msg.fbUserData.email;
                        $('span.facebookButton').remove();
                        $('div.utilityLinks span.status').html('<a class="connectedToFb" href="http://www.facebook.com"><strong>'+ userObject.fbUsername +' connected to Faceboook</strong></a>');
					}
					else if( data.msg.loggedIn === true ) {
                        authenticated = 1;
						if( $('#utility div.utilityLinks span.user').length === 0 ) {
                            var username = data.msg.loggedInAsDisplayName,
                                id = data.msg.loggedInAsUserID;
                            
							userObject.loggedInAsUserID = id;
					        userObject.loggedInAsDisplayName = username;
					        userObject.loggedInAsUsername = username;
					        userObject.loggedInToFB = data.msg.loggedInToFB;
							
							$( 'div.utilityLinks span.status' ).html('<a class="signOut" title="Sign Out">Sign Out</a><span class="user"><strong class="username" id="user_'+ id +'">'+ username +'</strong></span><span class="divider"></span>');
						}
                    }
                    else {
						if( authenticated !== 0 ) {
							location.reload( true );
						}
					}
                }
            },
			complete: function() {
				console.log( userObject );
			}
        });
    }
    
    function getUserStatus() {
        if( $( '#utility .utilityLinks span.user' ).is( ':visible' ) ) {
            authenticated = 1;
            return true;
        }
        else {
            authenticated = 0;
            return false;
        }
    }
    
    function setUserData( params ) {
        $.ajax({
            type: "POST",
            url: BASE_URL + "users/setUserData",
            data: params,
            dataType: "json",
            error: function( xmlHttpRequest, textStatus, errorThrown) {
                console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
            },
            success: function( data ) {
                if( data.msg.type === 'error' ) {
                    console.log( 'error = '+ data );
                }
            }
        });
    }
    
    function getUserData( params ) {
        $.ajax({
            type: "POST",
            url: BASE_URL + "users/getUserData",
            data: params,
            dataType: "json",
            error: function( xmlHttpRequest, textStatus, errorThrown) {
                console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
            },
            success: function( data ) {
                return data;
            }
        });
    }
	
    //====================================================================================================================================//
    // _welcome
	//====================================================================================================================================//
	
    $( '#welcome a.close' ).click(function() {
		$( '#welcome' ).hide();
		var params = '{"key" : "welcomeMessage", "value" : "doNotShow"}';
        setUserData( params );
	});
	
	function welcomeMessage() {
		var params = '{"key" : "welcomeMessage"}';
            
        $.ajax({
            type: "POST",
            url: BASE_URL + "users/getUserData",
            data: params,
            dataType: "json",
            error: function( xmlHttpRequest, textStatus, errorThrown) {
                console.log( 'xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown);
                growl( "Sorry, we seem to have a problem and that didn't work. Click refresh and try again.", "error" );
            },
            success: function( data ) {
                console.log( data );
                if( data.msg.type === 'success' ) {
                    $( '#welcome' ).hide();
                }
                else {
                    $( '#welcome' ).show();
                }
            }
        });
    }
	
    //====================================================================================================================================//
    // _social functions
	//====================================================================================================================================//
    
    $( '#items ul li div.actions span.social a.facebook' ).live( 'click', function() {
        var title = $.trim( $( this ).parents( 'div.social' ).siblings( 'div.details' ).find( 'strong.title' ).text() ),
            id = ( $( this ).parents( 'li.offered' ).attr( 'id' ) ).replace( 'post_', '' ),
            location = $.trim( $( this ).parents( 'div.social' ).siblings( 'div.details' ).find( 'a.location' ).text() ),
            value = currentUserId;
            
        facebookShare( id, title, location );
    });
    
    $( '#items ul li div.actions span.social a.twitter' ).live( 'click', function() {
        var category = 'Share',
            action = 'Twitter',
            labels = ( $( this ).parents( 'li' ).attr( 'id' ) ).replace( 'post_', '' ),
            value = currentUserId;
    });
    
    function facebookShare( id, title, location ) {
        var url = 'http://www.reyooz.com/posts/view/'+id,
            title = title +', '+ location;
        
        document.location.href = "http://www.facebook.com/sharer.php?u="+ url +"&t="+ title;
    }
    
    function tweetThis(id, title, location) {
        var url = 'http://www.reyooz.com/posts/view/'+id,
            params = title+', '+ location +', '+url;
        
        //window.open('http://twitter.com/?status='+ params,'twitterWindow','width=400,height=200,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes')
        //document.location.href = "http://twitter.com/?status="+ params;
    }
	
    function buzzUp() {
        
    }
    
    function diggIt() {
        
    }
    
    function stumbleUponIt() {
        
    }
    
	//====================================================================================================================================//
	// _misc FUNCTIONS
	//====================================================================================================================================//
	$( '#utility a.about' ).live( 'click', function() {
        $( '#contact' ).hide();
		$( '#welcome' ).toggle().children('.keyPoints').css('margin-top','24px');
	});
	
	function error( type, message, obj ) {
		$( 'input, textarea' ).removeClass( 'error' );
		$( 'div.error' ).remove();
		
		if( type === 'field' ) {
			$( obj ).addClass( 'error' ).removeClass('default');
            growl(message, "error");
			$( obj ).focus();
		}
		else {
			console.log( 'error type undefined' );
		}
	}
	
	function resetFieldDefaults() {
		$( '#items ul li input:text' ).each(function() {
			$( this ).val( $( this ).attr( 'defaultVal' ));
			$( this ).removeClass( 'error' );
		});
		
		$( 'div.error' ).remove();
	}
	
	function addItemImage() {
		
	}
	
	function checkTime(i) {
		if (i<10) {
  			i="0" + i;
  		}
		return i;
	}
	
    function hideFlashErrorMessageContainer() {
        $( '#flashErrorMessageContainer' ).fadeOut();
    }
	function showMessage( msg, obj ) {
        $( obj ).before( $( '#feedback' ).text( msg ).show() );
		var timer = setTimeout( hideMessage, pauseTimer );
	}
	function hideMessage() {
		$( '#feedback' ).fadeOut( 'normal', function() {
			$( this ).text( '' );
		});
	}
	function showErrorMessage( msg, obj ) {
       $( obj ).before( $( 'div.inlineError p' ).text( msg ).show() );
		var timer = setTimeout( hideErrorMessage, pauseTimer );
	}
	function hideErrorMessage() {
		$( 'div.inlineError' ).fadeOut( 'normal', function() {
			$( this ).children( 'p' ).text( '' );
		});
	}
	
	function hideHeaderMessage() {
        $( '#feedback' ).fadeOut('normal', function() {
            $( this ).text( '' );
        });
    }
    
	function growl( msg, growlType ) {
        if (growlType == null) growlType = 'confirmation'; // Default to a confirmation type.
		if( $.browser.msie ) {
            alert( msg );
        }
        else {
			if( growlType === undefined || growlType === '' ) {
				growlType = "confirmation";
			}
			$( '#feedback' ).text( msg ).attr( 'class', growlType ).show();
			var timer = setTimeout( hideHeaderMessage, pauseTimer );
        }
    }
	
    function setNewDefaultMyEmail ( email ) {
        $( '#items div.contactUser input:text.email, #items div.tellAFriend input:text.myEmail' ).val( email );
    }
    
    function isValidEmailAddress(emailAddress) {
 		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
 		return pattern.test(emailAddress);
	}

    function updateRssLink() {
        var mapBounds = getMapBounds();
        var searchTerm = getSearchTerm();
        $('a#rssLink').attr('href', '/posts/rss' + (searchTerm !== "" ? '/searchQuery/' + searchTerm : "") + "/bounds/" +
            mapBounds.ne.lat + ":" + mapBounds.ne.lng + ":"  + mapBounds.sw.lat + ":"  + mapBounds.sw.lng + "/");
    }
	
	$('div.lightbox a.close').live('click', function() {
		lightboxHide();
	});
	
	function lightboxShow( element ) {
		var winWidth = $( window ).width(),
            winHeight = $( window ).height(),
			docHeight = $( document ).height();
			
			
		$('#lightboxMask').css('height', docHeight).css('width', winWidth).show();
		$('div.lightbox').html( element ).show().append('<a class="close">close</a>');
		
		var lightboxHeight = $( element ).height(),
            lightboxWidth = $( element ).width(),
            lightboxTop = (winHeight / 2 ) - ( lightboxHeight / 2),
            lightboxLeft = (winWidth / 2) - (lightboxWidth / 2);
			
		$('div.lightbox').css('top', lightboxTop).css('left', lightboxLeft).css('width', lightboxWidth).css('height', lightboxHeight);
	}
	
	function lightboxHide() {
		$('#lightboxMask, div.lightbox').hide();
		$('#snippets').append( $('div.lightbox').html() );
		$('div.lightbox').html('');
	}
	
	function facebookInit() {
		FB.init({appId: '111152802240303', status: true, cookie: true, xfbml: true});
        FB.Event.subscribe('auth.sessionChange', onFacebookSessionChange );
	}
	
	function clearLoadingFeedback( domObject ) {
		$(domObject).removeClass('loading');
	}
	
	function fixLayoutForIE() {
		$('#welcome .keyPoints').children('div').css('top','-56px');
	}
	//====================================================================================================================================//
    // _load EVENT HANDLERS
    //====================================================================================================================================//
    
	if ($.browser.msie) {
		fixLayoutForIE();
	}
	
	$('#lightboxMask').click(function() {
		$('#lightboxMask, div.lightbox').hide();
	});
	
	$( document ).endlessScroll({
        fireOnce: true,
        bottomPixels: 200,
        fireDelay: 5000,
        callback: function() {
            getOlderPosts();
        }
    });
    
    $(window).scroll(function() {
		if(!browser.msie) {
			var mapPos = $( 'div.rightCol' ).offset(),
	            mapTop = mapPos.top-20,
	            documentTop = $( document ).scrollTop();
				
	        if( documentTop >= ( mapTop ) ) {
	            $( '#mapWrapper' ).css('position','fixed').css('top','20px');
	        }
			else {
				$( '#mapWrapper').css('position','relative').css('top','0px');
	        }
		}
	});
	
	facebookInit();
	welcomeMessage();
	whoAmI();
    getUserStatus();
    initMap();
}

