jQuery(document).ready(function(){

    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;

    map={
    
        user: 0,
        lot: 0,
        continueTo: '',
    
        getUser: function()
        {
            jQuery.ajaxSetup({async:false});
            jQuery.post(  
                
                "http://www.tidalwalk.com/manage_favorites.php",
                {action: 'get_user'},
                function(data)
                {
                    map.user = data;
                },
                "html"
            );
            
          return map.user;
        },
        
        getLot: function()
        {
            jQuery.ajaxSetup({async:false});
            jQuery.post(  
                
                "http://www.tidalwalk.com/manage_favorites.php",
                {action: 'get_lot'},
                function(data)
                {
                    map.lot = data;
                },
                "html"
            );
            
          return map.lot;
        },
        
        addFavorite: function()
        {
            jQuery.post(
                "http://www.tidalwalk.com/manage_favorites.php",
                {user:map.getUser(), lot:map.getLot(), action:'add'},
                function(data)
                {
                    jQuery("#returnMessage").html(data);
                    jQuery("#returnMessage").dialog();
                },
                "html"
            );
        },
        
        getManager: function()
        {  
            jQuery.post(
                "http://www.tidalwalk.com/manage_favorites.php",
		{user: map.user, action: 'manage'},
		function(data)
		{
                    if(data == '0')
                    {
                        jQuery("#mf_last_action").html('You do not have any favorites currently.');
                        jQuery("#mf_instruct").css('display','none');
                    }
                    else
                    {
                        jQuery("#mf_table").html(data);
                    }
		    
		    jQuery("#manageFavorites").dialog({title:'Manage Favorites'});
		    jQuery('a[name~="delete"]').click(function(event)
                    {
                        event.preventDefault();
			var delete_lot = jQuery(this).attr("id");
			jQuery.post(
                            "http://www.tidalwalk.com/manage_favorites.php",
			    {user:map.user, lot:delete_lot, action: 'delete'},
			    function(data)
			    {
                                jQuery("#manageFavorites").dialog("close");
                                jQuery("#mf_last_action").html(data);
                                map.getManager();
			    },
			    "html"
			);
                    });
		},
		"html"
	    );    
        },
        
        login: function($msg)
        {
            jQuery("#registrationForm").dialog("close");
            jQuery("#offerLogin").dialog("close");
            jQuery("#l_message").html($msg);
            jQuery("#loginForm").dialog({title:'Login'});    
        },
        
        register: function()
        {
            jQuery("#loginForm").dialog("close");
            jQuery("#offerLogin").dialog("close");
            jQuery("#registrationForm").dialog({title:'Register'});
        },
        
        validateLogin: function()
        {
            if(!emailReg.test(jQuery("#l_email").val()))
            {
                jQuery("#l_errorAlert").html('Please enter a valid email address.');
                jQuery("#l_errorAlert").css("display","inline");
                return false;
            }
            else {  return true;    }
        },
        
        validatePassRet: function()
        {
            if(!emailReg.test(jQuery("#p_email").val()))
            {
                jQuery("#p_errorAlert").html('Please enter a valid email address.');
                jQuery("#p_errorAlert").css("display","inline");
                return false;
            }
            else {  return true;    }
        },
        
        actionSuccessful: function($data)
        {
            var actionSuccessReg = /(Action Successful)/;
            if(actionSuccessReg.test($data))
            {   return true;    }
            else
            {   return false;   }
        },
        
        validateRegistration: function()
        {
            var hasErrors = false;
            jQuery('#r_first,#r_last,#r_phone,#r_email,#r_pass').each(function()
            {
                if(this.value=='')
                {
                    hasErrors = true;
                    jQuery("#r_errorAlert").html('Please provide values for all fields.');
                }
                else if( jQuery(this).attr('id')=="r_email")
                {
                    if(!emailReg.test(this.value))
                    {
                        hasErrors = true;
                        jQuery("#r_errorAlert").html('Please enter a valid email address.');
                    }
                }
            });
            if(hasErrors){
                jQuery("#r_errorAlert").css("display","inline");
                return false;
            }
            else {  return true;    }
        },
        
        retrievePassword: function()
        {
            jQuery("#loginForm").dialog("close");
            jQuery("#passwordRetrieval").dialog({title:'Retrieve Password'});  
        }
    };

    jQuery("#loginNow2").click(function(event){
        event.preventDefault();
        jQuery("#loginNow").trigger('click');
    });

    jQuery("#sitemapNew > a").click(function(event){
     
        console.log('pin clicked');
     
        map.continueTo = jQuery(this).attr("href");
        console.log('continue:'+map.continueTo);
        console.log('user:'+map.getUser());
        if(map.continueTo=='')
        {   event.preventDefault();   }
        else if(map.getUser()==0)
        {
            event.preventDefault();
            jQuery("#continue").attr('href',map.continueTo);
            jQuery("#offerLogin").dialog({title:'Login or Register'});
        }
        
    });

    if(map.getUser()!=0){
        jQuery("#viewFavorites2").css('display','inline');
    }

    jQuery("#viewFavorites2").click(function(event){
        event.preventDefault();
        jQuery("#viewFavorites").trigger('click');      
    });
    
    jQuery("#viewFavorites").click(function(event){     
    
        jQuery("#loginForm").dialog("close");
        jQuery("#registrationForm").dialog("close");
	event.preventDefault();        
        if(map.getUser()==0)
        {   map.login('You must be logged in to View Favorites.');   }
        else
        {   map.getManager();   }
        
    });
    
    jQuery("#registerNow").click(function(event){
    
	event.preventDefault();
	map.register();
    });
   
    jQuery("#loginNow").click(function(event){
    
	event.preventDefault();
	map.login();
    });
    
    jQuery("#submitLogin").click(function(event){
	event.preventDefault();
	if(map.validateLogin())
	{
	    jQuery.post(
                "http://www.tidalwalk.com/manage_favorites.php",
		jQuery("#userLogin").serialize(),
		function(data)
		{
		    if(map.actionSuccessful(data))
                    {
                        if(map.continueTo=='')
                        {   jQuery("#l_text").html(data);   }
                        else
                        {   window.location.href=map.continueTo;    }
                    }
		    else
                    {
                        jQuery("#l_errorAlert").html(data);
                        jQuery("#l_errorAlert").css("display","inline");
                    }
		},
		"html"
	    );   
	}
    });

    jQuery("#submitRegistration").click(function(event){
        event.preventDefault();
        if(map.validateRegistration())
        {
            jQuery.post(
                "http://www.tidalwalk.com/manage_favorites.php",
		jQuery("#userRegister").serialize(),
		function(data)
		{
                    if(map.actionSuccessful(data))
                    {
                        jQuery("#r_text").html(data);
                    }
                    else
                    {
                        jQuery("#r_errorAlert").html(data);
                        jQuery("#r_errorAlert").css("display","inline");
                    }
		},
		"html"
	    );   
        }
        
    });

    jQuery("#favButton").click(function(event){
        event.preventDefault();     
        if(map.getUser()==0)
        {   map.login('You must be logged in to add a Favorite.');  }
        else
        {
            map.addFavorite();
        }
        
    });
    
    jQuery("#rPass").click(function(event){
        event.preventDefault();
        map.retrievePassword();
    });
    
    jQuery("#getPassword").click(function(event){
        event.preventDefault();
        if(map.validatePassRet())
        {
            jQuery.post(
                "http://www.tidalwalk.com/manage_favorites.php",
                jQuery("#pwdRet").serialize(),
                function(data)
                {
                    if(map.actionSuccessful(data))
                    {
                        jQuery("#p_text").html(data);
                    }
                    else
                    {
                        jQuery("#p_errorAlert").html(data);
                        jQuery("#p_errorAlert").css("display","inline");
                    }
                },
                "html"
            );
        }
        
    });

});
