//   /preferredguest/manageFavorites.do?id=propertyId&op=[add|remove]

(function(){
    var yuiDom = YAHOO.util.Dom;
    var yuiEvent = YAHOO.util.Event;
    var yuiConnect = YAHOO.util.Connect;
    var yuiJson = YAHOO.lang.JSON;
    var Url = SW.tools.Url;

    var SYSTEM_ERROR = "system_error";
    var USER_NOT_LOGGED_IN = "not_signed_in";

    var configs = [];
    function handleError(config,error){
        config.isError = true;
        yuiDom.removeClass(config.anchor,"removeFavorite");
        yuiDom.removeClass(config.anchor,"addFavorite");
        var errorClassName = "favoriteError";
        if(error == USER_NOT_LOGGED_IN){
            errorClassName = "favoriteTimeout";
        }
        yuiDom.addClass(config.anchor,errorClassName);
    }
    function setLoading(config,isLoading){
        config.isLoading = isLoading;
        yuiDom.setStyle(config.anchor,"opacity",(isLoading ? .5:1));
    }

    SW.domWidget.add({
        id:"favorites",
        initialize:function() {
            // standard function name - manually called - SW.domWidget.WidgetId.initialize(params...);
        },
        load:function() {
            this.setup();
        },
        update:function(root) {
            this.setup(root);
        },
        setup:function(root) {
            var self = this;

            yuiDom.getElementsByClassName("favoriteLink", "a", root).forEach(function(favLink) {
                self.setupLink(favLink);
            });
        },                                        
        setupLink:function(favLink) {
            if (!this.getConfig(favLink)) {
                var config = {
                    isLoading:false,
                    anchor:favLink,
                    propertyId:Url.getParameter(favLink.href,"id"),
                    baseUrl:favLink.href
                };
                configs.push(config);
                this.setConfig(favLink, config);
                this.setConfig(Array.Copy(favLink.getElementsByTagName("span")), config);
                yuiEvent.addListener(favLink, "click", this.clickHandler,this,true);
            }
        },
        makeRequest:function(config,action){
            var url = Url.setParameter(config.baseUrl, "op", action);
            yuiDom.setStyle(config.anchor,"opacity",0.5);
            var callback = {
                timeout:10000,
                success:function(response){
                    var oldClassName = (response.argument.action == "add") ? "addFavorite" : "removeFavorite";
                    var newClassName = (response.argument.action == "add") ? "removeFavorite" : "addFavorite";
                    try{
                        var result = yuiJson.parse(response.responseText);
                    }catch(e){
                        handleError(response.argument.config,SYSTEM_ERROR);
                        setLoading(response.argument.config,false);
                        return;
                    }
                    if(!result || result.status != "success"){
                        if(result.status == "not_signed_in"){
                            handleError(response.argument.config,USER_NOT_LOGGED_IN);
                        }else{
                            handleError(response.argument.config,SYSTEM_ERROR);
                        }
                        setLoading(response.argument.config,false);
                        return;
                    }
                    configs.forEach(function(checkConfig) {
                        if (checkConfig.baseUrl == response.argument.config.baseUrl) {
                            yuiDom.replaceClass(checkConfig.anchor,oldClassName,newClassName)
                        }
                    });
                    setLoading(response.argument.config,false);
                    if(response.argument.action == "add"){
                        SW.customEvent.Favorite.onAddFavorite.fire(response.argument.config.propertyId);
                    }else{
                        SW.customEvent.Favorite.onRemoveFavorite.fire(response.argument.config.propertyId);
                    }
                },
                failure:function(response){
                    handleError(response.argument.config,SYSTEM_ERROR);
                    setLoading(response.argument.config,false);
                },
                argument:{
                    config:config,
                    action:action
                }
            }
            yuiConnect.asyncRequest("GET",url,callback,null);
        },
        add:function(config) {
            this.makeRequest(config,"add");
            s.events="event7";
            setOmniVars(s.charSet, s.server, s.channel, s.prop2, s.prop3, s.prop1, "", s.prop10, "AddFavourite");
            s.t();
        },
        remove:function(config){
            this.makeRequest(config,"remove");
            s.events="event7";
            setOmniVars(s.charSet, s.server, s.channel, s.prop2, s.prop3, s.prop1, "", s.prop10, "RemoveFavourite");
            s.t();
        },
        clickHandler:function(e) {
            yuiEvent.preventDefault(e);
            var self = SW.domWidget.favorites;
            var config = self.getConfig(yuiEvent.getTarget(e));
            if(config.isLoading || config.isError){
                return;
            }
            setLoading(config,true);
            if (yuiDom.hasClass(config.anchor, "addFavorite")) {
                self.add(config);
            }else{
                self.remove(config);
            }
        }
    });

    // custom event model. Each method will be passed property id. Only called if ajax was successful.
    SW.customEvent.Favorite = {
        onAddFavorite:new yuiCustomEvent("addFavorite", this, false, YAHOO.util.CustomEvent.FLAT),
        onRemoveFavorite:new yuiCustomEvent("removeFavorite", this, false, YAHOO.util.CustomEvent.FLAT)
    };

    SW.domWidget.favorites.setEnabled(true);
})();