// Lead capture feature set javascript functions
// Dependancies: Prototype Javascript Library v1.6.0.2
//               Scriptaculous Effects Library v1.8.1
//
// Company: Photo Tours
// Project: Lead capture
// Author: Andrew Le
// Date: August 2008

//Error enums
var idxErrors = {
    SUCCESS:       0,
    FAILED:        1, 
    NOT_LOGGED_IN: 2,
    BAD_MLS_ID:    3
};

//
//Favorites related functions
//
var Favorites = {
    //observe for clicks on add to favorites links
    initialize: function() {
        $$('.add-fav').each(function(elem) {
            elem.observe('click', Favorites.addByLink);
        });
    },
    
    initializeRemove: function() {
        $$('.remove-fav').each(function(elem) {
            elem.observe('click', Favorites.removeByLink);
        });
    },
    
    initializeRestore: function() {
        $$('.restore-fav').each(function(elem) {
            elem.observe('click', Favorites.restore);
        });
    },
    
    //unregisters event handlers for each add to favorites links
    destroy: function() {
        $$('.add-fav').each(function(elem) {
            elem.stopObserving('click', Favorites.addByLink);
        });
    },
    
    destroyRemove: function() {
        $$('.remove-fav').each(function(elem) {
            elem.stopObserving('click', Favorites.removeByLink);
        });
    },
    
    //adds the listing as a favorite via ajax
    add: function(mlsid) {
        var url = document._config.WEB_ROOT + "myfavorites.php";
        
        new Ajax.Request(url, {
            method: 'post',
            parameters: {
                "param": "add",
                "mlsId": mlsid
            },
            onLoading: function() {
                $(mlsid + "_fav_add").hide();
                $(mlsid + "_fav_loader").show();
            },
            onSuccess: function(transport) {
                if (transport.responseText == idxErrors.NOT_LOGGED_IN) {
                    window.location = ((document._config.WEB_ROOT_CID) ? document._config.WEB_ROOT_CID : document._config.WEB_ROOT) + "&action=savefavorite&data=" + mlsid;
                } else if (transport.responseJSON) {
                    $(mlsid + "_fav_loader").hide();
                    $(mlsid + "_fav_remove").show();
                    $(mlsid + "_fav_remove").writeAttribute('rel', transport.responseJSON.favId);
                } else if (transport.responseText == idxErrors.BAD_MLS_ID) {
                    alert("Bad mls id given.");
                    $(mlsid + "_fav_loader").hide();
                    $(mlsid + "_fav_add").show();
                } else {
                    $(mlsid + "_fav_loader").hide();
                    $(mlsid + "_fav_add").show();
                }
            }
        });
    },
    
    //removes the listing from favorites via ajax
    remove: function(favId, target) {
        var url = document._config.WEB_ROOT + "myfavorites.php";
        
        new Ajax.Request(url, {
            method: 'post',
            parameters: {
                "param": "remove",
                "favId": favId
            },
            onLoading: function() {
            },
            onSuccess: function(transport) {
                if (transport.responseText == idxErrors.NOT_LOGGED_IN) {
                    window.location = (document._config.WEB_ROOT_CID) ? document._config.WEB_ROOT_CID : document._config.WEB_ROOT;
                } else if (transport.responseText == idxErrors.FAILED) {
                    alert("There was a problem trying to remove your favorite. Please try again.");
                } else if (transport.responseText == idxErrors.SUCCESS) {
                    new Effect.Highlight(target);
                    target.fade({duration: 0.5});
                } else {
                    alert("We're sorry, there was a problem performing your request. Please try again.");
                }
            }
        });
    },
    
    restore: function(event) {
        Event.stop(event);
        var favId = $(event.target).readAttribute('rel');
        var ancestors = $(event.target).ancestors();
        Favorites.remove(favId, ancestors[1]);
        var url = document._config.WEB_ROOT + "myfavorites.php";
        
        new Ajax.Request(url, {
            method: 'post',
            parameters: {
                "param": "restore",
                "favId": favId
            },
            onLoading: function() {
            },
            onSuccess: function(transport) {
                if (transport.responseText == idxErrors.NOT_LOGGED_IN) {
                    alert("Sorry, you must be logged in to use this feature.");
                } else if (transport.responseText == idxErrors.FAILED) {
                    alert("There was a problem trying to restore your favorite. Please try again.");
                } else if (transport.responseText == idxErrors.SUCCESS) {
                    new Effect.Highlight(target);
                    target.fade({duration: 0.5});
                } else {
                    alert("We're sorry, there was a problem performing your request. Please try again.");
                }
            }
        });
    },
    
    addByLink: function(event) {
        Event.stop(event);
        var mlsid = $(event.target).readAttribute('rel');
        Favorites.add(mlsid);
    },
    
    removeByLink: function(event) {
        Event.stop(event);
        var favId = $(event.target).readAttribute('rel');
        var ancestors = $(event.target).ancestors();
        Favorites.remove(favId, ancestors[1]);
    },
    
    removeOnResults: function(event) {
        Event.stop(event);
        var favId = $(event.target).readAttribute('rel');
        var mlsid = $(event.target).readAttribute('mlsid');
        var elem = event.element();
        var url = document._config.WEB_ROOT + "myfavorites.php";
        
        new Ajax.Request(url, {
            method: 'post',
            parameters: {
                "param": "remove",
                "favId": favId
            },
            onLoading: function() {
                $(elem).hide();
                $(mlsid + "_fav_loader").show();
            },
            onSuccess: function(transport) {
                if (transport.responseText == idxErrors.NOT_LOGGED_IN) {
                    window.location = (document._config.WEB_ROOT_CID) ? document._config.WEB_ROOT_CID : document._config.WEB_ROOT;
                } else if (transport.responseText == idxErrors.FAILED) {
                    alert("There was a problem trying to remove your favorite. Please try again.");
                } else if (transport.responseText == idxErrors.SUCCESS) {
                    $(mlsid + "_fav_loader").hide();
                    $(mlsid + "_fav_add").show();
                } else {
                    alert("We're sorry, there was a problem performing your request. Please try again.");
                    $(mlsid + "_fav_loader").hide();
                    elem.show();
                }
            }
        });
    },
    
    //Takes a list of mls ids provided by a form submittal and ADDS them as favorites
    addMany: function() {  
        //For every check box in the form submitted
            //get the mls id of the listing
            //Favorites.add(mlsid);
    },
    
    //Takes a list of mls ids provided by a form submittal and REMOVES them as favorites
    removeMany: function() {
    }
};

//
//Notes for favorites
//
var Notes = {
    initialize: function() {
        $$('a.show-notes').each(function(elem) {
            elem.observe('click', Notes.toggle);
        });
        
        $$('div.edit-notes form input.submit').each(function(elem) {
            elem.observe('click', Notes.save);
        });
        /*
        $$('div.edit-notes form').each(function(elem) {
            elem.observe('submit', Notes.save);
        }); */
    },
    
    toggle: function(event) {
        Event.stop(event);
        var favId = $(event.target).readAttribute('rel');
        var divId = 'edit-notes-' + favId;
        $(divId).toggle();
    },
    
    save: function(event) {
        Event.stop(event);
        var url = document._config.WEB_ROOT + "myfavorites.php";
        var theForm = $(event.target).up();

        new Ajax.Request(url, {
            method: 'post',
            parameters: theForm.serialize(true),
            onLoading: function() {
            },
            onSuccess: function(transport) {
                if (transport.responseText == idxErrors.NOT_LOGGED_IN) {
                    alert("Sorry, you must be logged in to use this feature.");
                } else if (transport.responseText == idxErrors.FAILED) {
                    alert("There was a problem trying to save your notes. Please try again.");
                } else if (transport.responseText == idxErrors.SUCCESS) {
                    theForm.up().toggle();
                    var favId = theForm.readAttribute('rel');
                    var divId = 'notes-' + favId;
                    var dd = '#' + divId + ' dd';
                    var elem = $$(dd);
                    
                    elem[0].update($F(theForm['notes']));
                    new Effect.Highlight(divId);
                } else {
                    alert(transport.responseText);
                }
            }
        });
    }
};

//
//MySearches related functions
//
var MySearches = {
    initialize: function() {
        var ajaxLinks = $$('a.discardRestoreSearch');
        
        ajaxLinks.each(function(elem) {
            elem.observe('click', MySearches.discardRestore);
        });
    },
    
    discardRestore: function(event) {
        Event.stop(event);
        var elem = $(event.target);
        var url = elem.readAttribute('href');
        
        new Ajax.Request(url, {
            method: 'get',
            onLoading: function() {
            },
            onSuccess: function(transport) {
                var json = transport.responseText.evalJSON(true);
                
                if (json.code == idxErrors.NOT_LOGGED_IN) {
                    MySearches.displayMessage('Sorry, you must be logged in to use this feature.',
                        'fail');
                } else if (json.code == idxErrors.FAILED) {
                    MySearches.displayMessage(json.message, 'fail');
                } else if (json.code == idxErrors.SUCCESS) {
                    var ancestors = elem.ancestors();
                    new Effect.Highlight(ancestors[1]);
                    ancestors[1].fade({duration: 0.5});
                    
                    MySearches.displayMessage(json.message, 'success');
                } else {
                    alert("Ghosts... aliens... I don't know.");
                }
            }
        });
    },
    
    //Displays a message at the top of the page and styles it according to whether it is a success
    //message or a fail message
    //  message: the string to display at the top of the page
    //  type: success|fail The way to style the message. Defaults to success.
    displayMessage: function(message, type) {
        
    }
};

Event.observe(window, 'load', function() {
    if ($('main') != null) {
        var theBox = new Element('div', {
           'id': 'access_tool_tip',
           'style': 'display:none' 
        });
        $('main').insert(theBox);

        $$('img.access_icon_on', 'img.access_icon_off').each(function(elem) {
            var theMessage;

            if (elem.hasClassName('access_icon_on')) {
                theMessage = 'User has given permission for agent to add searches and favorites for them';
            } else if (elem.hasClassName('access_icon_off')) {
                theMessage = 'User has <strong>not</strong> given permission for agent to add searches and favorites for them.';
            }

            elem.observe('mouseover', function(event) {            
                theBox._showfor = elem.identify();
                theBox.update(theMessage);
                var pos = elem.cumulativeOffset();

                theBox.setStyle({
                   top:     (pos[1] - theBox.getHeight() - 5) + 'px',
                   left:    (pos[0] - theBox.getWidth()/2 + 5) + 'px'
                });


                theBox.show();
            });

            elem.observe('mouseout', function(event) {
                if (theBox._showfor == elem.identify()) {
                    theBox._showfor = null;
                    theBox.hide();
                }
            });
        });
        /* END Access icon events */
    }
});