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

$(function() {
	
	var authenticated = false,
		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',
        pageTracker = _gat._getTracker("UA-451602-11");
		
        pageTracker._trackPageview();
        console.log( 'inital user id = '+ currentUserId );
	//====================================================================================================================================//
	//DEFAULT BEHAVIOURS FOR FORM ELEMENTS
	//====================================================================================================================================//
	$( 'input:text, textarea' ).livequery( 'focus', function() {
		$( this ).addClass( 'focus' ).removeClass('default').select();
	}).livequery( 'blur', function() {
		$( this ).removeClass( 'focus' );
        
        var defaultVal = $( this ).attr( 'defaultVal' ),
            currentVal = $( this ).val();
            
        if( currentVal === defaultVal || currentVal === '' ) {
            $( this ).addClass( 'default' );
            $( this ).val( defaultVal );
        }
	});
    if (!$.browser.msie) {
        $( 'textarea' ).autogrow();
    }
	//====================================================================================================================================//
	//_contact handlers
	//====================================================================================================================================//
	$( '#utility a.contact' ).livequery( 'click', function() {
        $( '#registration, #welcome' ).hide();
        $( '#contact' ).toggle(); 
    });
	$( '#contact a.close' ).click(function() {
       $( '#contact' ).hide(); 
    });
	
	//====================================================================================================================================//
	// _load EVENT HANDLERS
	//====================================================================================================================================//
	
    $( document ).endlessScroll({
        fireOnce: true,
        bottomPixels: 200,
        fireDelay: 5000,
        callback: function() {
            getOlderPosts();
        }
    });
	$(window).scroll(function() {
        if( $( '#offerItem' ).is(':hidden')) {
            var documentTop = $( document ).scrollTop();
            if( documentTop >= 190 ) {
                $( '#mapWrapper' ).css('position','fixed').css('top','18px');
            }      
            else {
                $( '#mapWrapper').css('position','relative').css('top','0px');
            } 
        }
    });
    whoAmI();
	getUserStatus();
	setWelcomeMessageStatus();
	initMap();
	
    //====================================================================================================================================//
    // _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);
                        
                    map.setCenter( new GLatLng( lat, lng ), zoom );
				}
				else {
					map.setCenter(new GLatLng(51.514, -0.137), 7);
				}
            },
            complete: function() {
                GEvent.addListener( map, 'moveend', function() {
                    setUserDefaultLocation();
                    getPosts( 'replace' );
                    
                    if ( $( '#search input:text' ).val() !== '' ) {
                        var labels = $( '#search input:text' ).val()+", "+ map.getCenter();
                    }
                    else {
                        var labels = map.getCenter();
                    }
                    var category = "Search",
                        action = "Map move",
                        value = currentUserId;
                        
                    analytics( category, action, labels, value );
                });
                
                setUserDefaultLocation();
            }
		});
	}
	
	function getPlacename() {
		geocoder.getLocations( map.getCenter(), function( response ) {
            if( response.Placemark ) {
                var place = response.Placemark[0],
				address = place.address;
			
                if (place.AddressDetails.Country.AdministrativeArea !== undefined) {
                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea !== undefined) {
                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality !== undefined) {
                            var placeName = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                        }
                        else 
                            if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName !== undefined) {
                                var placeName = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;
                            }
                            else 
                                if (county = place.AddressDetails.Country.AdministrativeArea !== undefined) {
                                    var placeName = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
                                }
                    }
                }
                else {
                    var placeName = address;
                }
            }
			else {
                var placeName = "UK";
            }
            
            $( '#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() {
        if (typeof map == 'undefined') return {"ne" : {"lat" : "0", "lng" : "0"}, "sw": {"lat": "0", "lng" : "0"}};
		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 );
        
        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' );
            
            if( $( '#search input:text' ).val() !== '' ) {
                var labels = $( '#search input:text' ).val()+", "+ map.getCenter();
            }
            else {
                var labels = map.getCenter();
            }
            var category = "Search",
                action = "Do",
                //labels = $( '#search input:text' ).val()+", "+ getMapBounds(),
                value = currentUserId;
                
            analytics( category, action, labels, value );
        }
    });
    
	$( '#search input:text' ).keypress(function(event) {
		if( event.keyCode === 13 ) {
			$( '#search a.search' ).click();
		}
	});
    
    $( '#search a.clearSearch' ).livequery( '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' );
        
        if( $( '#search input:text' ).val() !== '' ) {
            var labels = $( '#search input:text' ).val()+", "+ map.getCenter();
        }
        else {
            var labels = map.getCenter();
        }
        var category = "Search",
            action = "Clear",
            //labels = $( '#search input:text' ).val()+", "+ getMapBounds(),
            value = currentUserId;
            
        analytics( category, action, labels, value ); 
    }
    
    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' ).livequery( 'click' , function() {
		$( this ).parent('div.actions').siblings( 'div.tellAFriend' ).toggle();
    });
	$( '#items ul li div.actions a.contactUser' ).livequery( 'click', function() {
        var form = $(this).parent('div.actions').siblings('div.contactUser');
        if( $(form).is(':hidden')) {
            $(form).show().children('input:first').select().addClass('focus');
        }
		else {
            $(form).hide().children('input, textarea').removeClass('error').end().children('div.error').remove();
        }
	});
    $( '#items ul li div.actions a.flag' ).livequery( 'click', function() {
		flagPost( ( $( this ).parents( 'li.offered' ).attr( 'id' ) ).replace( 'post_', '') );
	});
	$( '#items ul li a.cancel' ).livequery( '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();
	});
    $( 'a.saveSearch' ).livequery( 'click', function() {
        saveSearch();
    });
    $( '#items ul li div.contactUser a.send' ).livequery('click', function() {
        var id = ( $( this ).parents( 'li.offered' ).attr( 'id' ) ).replace( 'post_', '');
		iWantThis( id );
	});
	$( '#items ul li div.contactUser input:text' ).livequery('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' ).livequery( 'click', function() {
		var id = ( $( this ).parents( 'li.offered' ).attr( 'id' ) ).replace( 'post_', '');
		tellAFriend( id );
	});
    $( '#items ul li div.tellAFriend input:text' ).livequery('keypress', function( event ) {
		if( event.keyCode === 13 ) {
			var id = ( $( this ).parents( 'li' ).attr( 'id' ) ).replace( 'post_', '');
		    tellAFriend( id );
		}
	});
    $( '#items a.location' ).livequery('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);
                    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);
    				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
    			},
    			success: function( data ) {
                    if( data.msg.type !== 'error' ) {
                        var postsCount = data.msg.posts.length;
                        if ( postsCount > 0 ) {
                            buildPostList( data, 'append' );
                            /*if( $( '#search input:text' ).val() !== '' ) {
                                var labels = $( '#search input:text' ).val()+", "+ map.getCenter();
                            }
                            else {
                                var labels = map.getCenter();
                            }
                            var category = "Item",
                                action = "Endless scroll",
                                //labels = $( '#search input:text' ).val()+", "+ getMapBounds(),
                                value = currentUserId;
                                
                            analytics( category, action, labels, value );*/
                        }
                        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);
				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
			},
			success: function( data ) {
				if( data.msg.type !== 'error' ) {
                    var postsCount = data.msg.posts.length;
                    if ( postsCount > 0 ) {
                        $( '.noMorePostsToFetch' ).hide();
                        buildPostList( data, 'replace' );
                    }
                    else {
                        $( '.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 ) {
        console.log( 'buildPostList : '+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_highlighted = 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 !== "") {
                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: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() +' ';
        //snippet.replace( new RegExp(searchTerm, "gi") , '<em class="searchTerm">'+ searchTerm +'</em>' );
		var newSnippet = snippet.replace( new RegExp(searchTerm, "gi") , '<em class="searchTerm">'+ searchTerm +'</em>' );
		return newSnippet;
	}
	
	function saveItem() {
		var title = $( '#offerItem input:text.title' ).val(),
			defaultTitle = $( '#offerItem input:text.title' ).attr( 'defaultval' ),
			description = $( '#offerItem textarea.description' ).val(),
			defaultDescription = $( '#offerItem textarea.description' ).attr( 'defaultval' ),
			lat = $( '#mapWrapper input:hidden.lat' ).val(),
			lng = $( '#mapWrapper input:hidden.lng' ).val(),
			placename = $( '#mapWrapper input:hidden.placename' ).val();
			
		if( ( title !== '' && title !== defaultTitle ) || ( description !== '' && description !== defaultDescription ) ) {
            //Give the button an ajax spinner to show the state of the process happening
            $( '#offerItem a.add' ).addClass( 'ajaxSpinner' );
			params = $.toJSON( {"title": title, "content" : description, "location" : {"lat" : lat,"lng" : lng}, "location_description" : placename} );
			
			$.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);
					alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
				},
				success: function( data ) {
					if( data.msg.type === 'success' ) {
                        showMessage( "Added successfully", $( '#offerItem' ) );
						$( '#offerItem a.add' ).removeClass( 'ajaxSpinner' );
                        $( '#offerItem' ).slideUp( 'normal', function() {
                            $( '#offerItem input:text.title' ).val( $( '#offerItem input:text.title' ).attr( 'defaultval' ) ).select();
                            $( '#offerItem textarea' ).val( $( '#offerItem textarea' ).attr( 'defaultval' ) );
                            $( '#offerItemButton' ).removeClass( 'open' );
                        });
                        
                        var label = data.msg.post.id,
                            value = data.msg.post.from_user_id,
                            category = "Item",
                            actions = "Offer";
                            
                        analytics( category, actions, label, value );
					}
					else {
						showMessage( data.msg.text, $( '#offerItem' ) );
						return false;
					}
				}
			});
			
		}
		else if( title === '' || title === defaultTitle ) {
			error( 'field', 'You must enter a title', $( '#offerItem input:text.title' ) );
			return false;
		}
		else if( description === '' || description === defaultDescription ) {
			error( 'field', 'You must enter a description', $( '#offerItem textarea.description' ) );
			return false;
		}
	}
	
	function iWantThis( id ) {
        if ($('#post_' + id).find('div.contactUser a.send span.icon').is(':visible')) {
            var email = $('#post_' + id).find('div.contactUser').children('input:text.email').val(),
                message = $('#post_' + id).find('div.contactUser').children('textarea.message').val(),
                params = $.toJSON( {'myEmail': email, 'postId' : id, 'message' : message} );
                    
            if (!isValidEmailAddress(email)) {
                error('field', "This is not an email address", $('#post_' + id).find('div.contactUser').children('input:text.email'));
            }
            else {
                $("#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);
                        alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
                    },
                    success: function( data ) {
                        if( data.msg.type !== 'error' ) {
                            var message = data.msg.text,
                            email = $( '#post_'+id ).find( 'div.contactUser input:text.email' ).val();
                            showMessage( message, $( '#post_'+id ).find( 'div.contactUser label' ) );
                            setTimeout( function() {
                                $( '#post_'+id ).find( 'div.contactUser' ).slideUp('normal', function() {
                                    setNewDefaultMyEmail( email );
                                    $( '#feedback' ).hide();
                                });
                            }, 2000);
                            
                            var postId = id,
                                userEmail = email,
                                category = "Item",
                                actions = "Want";
                                
                            analytics( category, actions, postId, userEmail );
                        }
                        else {
                            alert( data.msg.text );
                            return false;
                        }
                    },
                    complete: function() {
                        $("#post_" + id).find('div.contactUser a.send span.loading').removeClass('loading').addClass('icon');
                        $("#post_" + id).find('textarea').val( $("#post_" + id).find('textarea').attr('defaultVal') );
                    }
                });
            }
        }
	}
	
	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);
    				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
    			},
    			success: function( data ) {
    				if( data.msg.type === 'success' ) {
    					var message = data.msg.text,
            			    email = $( "#post_"+id ).find( 'div.tellAFriend.form input:text.myEmail' ).val();
                            
            			showMessage( message, $( '#post_'+id ).find( 'div.tellAFriend label' ) );
                        
                        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 {
    					var message = data.msg.text;
                        showMessage( message, $( '#post_'+id ).find( 'div.tellAFriend label' ) );
    				}
    			},
    			complete: function() {
    				$( '#post_'+id ).find( 'a.send' ).removeClass( 'ajaxSpinner' );
    			}
    		});  
        }
    }
	
    function flagPost( id ) {
        var reason = "inappropriate",
            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);
				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
			},
			success: function( data ) {
				if( data.msg.type === 'success' ) {
					$( '#post_'+id ).fadeOut('normal', function() {
                        $( this ).remove();
                    });
				}
				else {
					var message = data.msg.text;
                    showMessage( message, $( '#post_'+id ).find( 'div.tellAFriend label' ) );
				}
			}
		});  
    }
	//====================================================================================================================================//
	// _offer ITEM EVENTS
	//====================================================================================================================================//
	$( '#offerItemButton' ).click(function() {
		if ( authenticated === true ) {
			$( '#offerItem input:text.title' ).select();
			$( '#offerItem' ).toggle();
			$( this ).toggleClass( 'open' );
            $( '#offerItem input:first' ).select().removeClass( 'default' ).addClass( 'focus' );
            $( '#mapWrapper' ).css( 'position', 'relative' );
		}
		else {
			if( $( '#registration' ).is( ':hidden' ) ) {
				$( '#registration' ).show();
			}
            $( '#registration div.signin input:first' ).addClass( 'focus' ).removeClass( 'default' ).select();
            showHeaderMessage( 'You need to Sign In or Register to offer something' );
		}
	});
	$( '#offerItem a.cancel' ).click( function() {
		$( '#offerItem' ).hide();
		$( '#offerItemButton' ).removeClass( 'open' );
	});
	$( '#offerItem a.add' ).click( function() {
		saveItem();
	});
	$( '#offerItem a.addImage').click(function() {
		alert( 'Popup file browser, pick file, then use googley loader inline.');
		$( '#offerItem a.addImage' ).html( 'oldpairofPants.jpg | <u>pick different picture</u>' )
	});
	
    //====================================================================================================================================//
	// _user FUNCTIONs
	//====================================================================================================================================//
	$( '#utility a.signIn').livequery( 'click', function() {
        $( '#contact, #welcome' ).hide();
		$( '#registration' ).toggle();
        $( '#registration div.signin input:first' ).addClass( 'focus' ).removeClass( 'default' ).select();
	});
	$( '#utility a.signOut').livequery( 'click', function() {
		signOut();
	});
	$( '#registration a.close' ).livequery( 'click', function() {
		$( '#registration' ).hide();
	});
	$( '#registration a.signUp' ).livequery( 'click', function() {
		signUp();
	});
	$( '#registration a.signIn' ).livequery( 'click', function() {
		signIn();
	});
	$( '#registration div.signin input:text' ).keypress(function( event ) {
		if( event.keyCode === 13 ) {
			signIn();
		}
	});
    $( '#registration div.signup input:text' ).keypress(function( event ) {
		if( event.keyCode === 13 ) {
			signUp();
		}
	});
    if( $( '#flashErrorMessageContainer:visible' ) ) {
        var timer = setTimeout( hideFlashErrorMessageContainer, pauseTimer );
    }
	
	function signUp() {
		
		var username = $( '#registration div.signup input.email' ).val(),
			password = $( '#registration div.signup input.password' ).val(),
			params = $.toJSON( {"username" : username, "password" : password} );
		
        $( '#registration a.signUp 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);
				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
			},
			success: function( data ) {
				if( data.msg.type === 'success' ) {
					$( '#registration' ).fadeOut('normal', function() {
                        showHeaderMessage( "We've sent you an email to confirm your address." );
					    whoAmI();
                    });
				}
				else {
					error( 'field', data.msg.text, $( '#registration div.signup label.email' ) );
				}
			},
            complete: function() {
                $( '#registration a.signUp span.loading' ).removeClass( 'loading' ).addClass( 'icon' );
            }
		});
	}
	
	function signIn() {
		var username = $( '#registration div.signin input.email' ).val(),
			password = $( '#registration div.signin input.password' ).val(),
			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);
				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();
                    showHeaderMessage( "You're signed in" );
                    whoAmI();
				}
				else {
                    error( 'field', data.msg.text, $( '#registration div.signin label.email' ) );
				}
			},
            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);
				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
			},
			success: function( data ) {
				if( data.msg.type !== 'error' ) {
					showHeaderMessage( "You're signed out" );
                    $( "#registration input.password" ).val( $( "#registration input.password" ).attr( 'defaultVal' ) ).addClass( 'default' );
                    whoAmI();
				}
				else {
					alert( data.msg.text );
					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);
				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
			},
			success: function( data ) {
                if( data.msg.type === "success" ) {
                    if( data.msg.loggedIn === true ) {
    					authenticated = true;
                        currentUserId = data.msg.loggedInAsUserID;
                        if( $('#utility div.utilityLinks span.user').length === 0 ) {
                            var username = data.msg.loggedInAsDisplayName,
        						id = data.msg.loggedInAsUserID,
                                snippet = '<span class="user"><strong>Hi</strong> <span class="username" id="user_'+ id +'">'+ username +'<span class="divider">|</span></span>';
                                
        					$( '#utility div.utilityLinks' ).prepend( snippet );
        					$( '#utility .utilityLinks a.signIn' ).removeClass( 'signIn' ).addClass( 'signOut' ).text( 'Sign Out' );
                        }
    				}
                    else {
    					authenticated = false;
                        currentUserId = 'Anon'
                        
    					$( '#utility div.utilityLinks span.user' ).remove();
    					$( '#utility .utilityLinks a.signOut' ).removeClass( 'signOut' ).addClass( 'signIn' ).text( 'Sign In' );
    					$( '#offerItem:visible' ).hide();
                        $( '#offerItemButton' ).toggleClass( 'open' );
    				}
                }
			}
        });
	}
    
    function getUserStatus() {
        if( $( '#utility .utilityLinks span.user' ).is( ':visible' ) ) {
			authenticated = true;
            return true;
		}
		else {
			authenticated = false;
            return false;
		}
    }
	
    function getUserId() {
        
        $.ajax({
			type: "POST",
			url: BASE_URL + "users/whoami",
			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 id = 0;
                    if( data.msg.loggedIn === true ) {
    					authenticated = true;
    					id = data.msg.loggedInAsUserID;
    				}
                    else {
    					authenticated = false;
    					//var id = data.msg.loggedInAsUserID;
                        id = "Anon";
    				}
                    console.log( 'id = '+ id );
                    return id;
                }
			}
        });
        
       return true;
	}
    
	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);
				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
			},
			success: function( data ) {
				if( data.msg.type !== 'error' ) {
					console.log( params +' added to user data object' );
				}
				else {
					alert( data.msg.text );
					return false;
				}
			}
		});
	}
	
	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);
				alert( 'The ajax call had a problem: xmlHttpRequest : '+xmlHttpRequest+', textStatus : '+textStatus+', errorThrown : '+errorThrown );
			},
			success: function( data ) {
				return data;
			}
		});
	}
	//====================================================================================================================================//
    // _welcome
	//====================================================================================================================================//
	
	$('#welcome li' ).mouseover(function() {
		$( this ).css('background-position','-1000px -1000px').children( 'p' ).css('visibility', 'visible');
	}).mouseout(function() {
		$( this ).css('background-position','center bottom').children( 'p' ).css('visibility', 'hidden');
	});
	$( '#welcome a.close' ).click(function() {
		$( '#welcome' ).hide();
	});
    
    function setWelcomeMessageStatus() {
        if($( '#welcome' ).length > 0) {
            var params = '{"key" : "welcomeMessage", "value" : "false"}';
            setUserData( params );
        }
    }
	
    //====================================================================================================================================//
    // _social functions
	//====================================================================================================================================//
    
    $( '#items ul li div.actions span.social a.facebook' ).livequery( '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() ),
            category = "Share",
            action = "Facebook",
            labels = ( $( this ).parents( 'li' ).attr( 'id' ) ).replace( 'post_', '' ),
            value = currentUserId;
            
        facebookShare( id, title, location );
        analytics( category, action, labels, value );
    });
    
    $( '#items ul li div.actions span.social a.twitter' ).livequery( 'click', function() {
        var category = 'Share',
            action = 'Twitter',
            labels = ( $( this ).parents( 'li' ).attr( 'id' ) ).replace( 'post_', '' ),
            value = currentUserId;
            
        analytics( category, action, labels, value );
    });
    
    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 analytics( category, action, labels, value ) {
        
        if(pageTracker && !pageTracker.cb) {
            setTimeout(function() {
                analytics( category, action, labels, value );
            }, 200);
            return;
        }
        pageTracker._trackEvent( category, action, labels, value );
        
        console.log( category+ ', '+ action +', '+ labels +', '+ value );
    }
    
    function buzzUp() {
        
    }
    
    function diggIt() {
        
    }
    
    function stumbleUponIt() {
        
    }
    
	//====================================================================================================================================//
	// _misc FUNCTIONS
	//====================================================================================================================================//
	$( '#utility a.about' ).livequery( 'click', function() {
        $( '#registration, #contact' ).hide();
		$( '#welcome' ).toggle();
	});
	
	function error( type, message, obj ) {
		$( 'input, textarea' ).removeClass( 'error' );
		$( 'div.error' ).remove();
		
		if( type === 'field' ) {
			$( obj ).addClass( 'error' ).before( '<div class="error">'+message+'</div>');
            $( 'div.error' ).show();
			$( 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 showHeaderMessage( message ) {
        if( $.browser.msie ) {
            alert( message );
        }
        else {
            $( '#header div.feedback' ).text( message );
            $( '#header div.feedback' ).show();
            var timer = setTimeout( hideHeaderMessage, pauseTimer );
        }
    }
    function hideHeaderMessage() {
        $( '#header div.feedback' ).fadeOut('normal', function() {
            $( this ).text( '' );
        });
    }
    
    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 + "/");
    }
});
