function BookessService()
{
	this.prototype = BookessBase.call(this);
	
	this.SERVICE_GET_URL_TOKEN = '';
	
	this.messages =
    {
        loading: 'Aguarde, você está sendo redirecionado...',
        status:
        {
			connected: 'Conectado',
			disconnected: 'Desconectado'
        }

    };
	
	this.urlTokens = [];
    this.urlToken = null;
    this.windows = {interval: 0, services: []};
    
    var self = this;
    
    this.openWindow = function(service)
    {
        var urlToken = self.urlTokens[service] ? self.urlTokens[service] : "";

        var popAuth = popup(urlToken, 'service' + service, {width: 800, height: 400, top: 'center', left: 'center'});
        self.setWindow(service, popAuth);
        
        if(!urlToken)
        {
            popAuth.document.write('<htm><head><title>' + self.messages.loading + '</title></head><body><span style="font-size:12px; font-family: Arial, Tahoma;">' + self.messages.loading + '</span></body></html>');

            self.httpRequest(self.SERVICE_GET_URL_TOKEN + service + '/', {}, function(response)
        	{
            	self.urlTokens[service] = response;
                popAuth.location.href = response;		
        	}
            , null, 'text');
        }
        
    };
    
    this.checkWindows = function()
    {
        if(self.windows.interval)
        {
            return false;
        }

        self.windows.interval =
        setInterval(function()
        {
            if(self.util.size(self.windows.services) == 0)
            {
                clearInterval(self.windows.interval);
                self.windows.interval = null;
                
                return false;
            }
            
            var winServices = self.windows.services;
            
            for(var name in winServices)
            {
                if(winServices[name] && (!winServices[name].win || winServices[name].win.closed))
                {
                    self.onWindowClose.apply(null, [name]);
                    self.removeWindow(name);
                }
            }

        }, 100);
    };
    
    this.setWindow = function(service, win)
    {
        self.windows.services[service] = {win: win};        
        self.checkWindows();
    };
    
    this.removeWindow = function(service)
    {
    	delete self.windows.services[service];
    };

    this.onWindowClose = function(name){};    
    this.onComplete = function(name){};
}





function BookessServices()
{
    this.SERVICE_STATUS_ON = 1;
    this.SERVICE_STATUS_OFF = 0;

    this.SERVICE_GET_URL_TOKEN = '';
    this.SERVICE_URL_REMOVE_SERVICE = '';
    
    this.messages =
    {
        confirm: 'Deseja realmente desconectar sua conta?',
        ok: 'Sim',
        cancel: '<strong>Cancelar</strong>',
        separator: ' / ',
        loading: 'Aguarde, você está sendo redirecionado...',
        removed: 'Sua conta foi desconectada deste serviço com sucesso!',
        actived: 'Sua conta foi conectada ao serviço com sucesso!'
    };

    // Serviços disponíveis
    this.services = {};
    this.windows = {};

    this.urlTokens = [];

    this.urlToken = null;

    var self = this;

    /**
     * Show Confirm
     *
     * Exibe botões de confirmação.
     *
     * @author Marcos Passos
     * @method showConfirm
     * @param Object elm - elemento relacionado
     * @param Function onOk - evento disparado ao clicar em OK
     * @param Function onCancel - evento disparado ao clicar em Cancel
     * @return void
     */
    this.showConfirm = function(elm, onOk, onCancel)
    {
        var $container = $('<div />').addClass('confirm');

        var $ok = $('<a href="#" />').html(self.messages.ok);
        var $cancel = $('<a href="#" />').html(self.messages.cancel);

        var onRemove = function()
        {
            $(this).fadeOut('fast', function(){ $(this).remove() });
        };

        $ok.click(function()
        {
            onOk.apply(elm);
            onRemove.apply($container);

            return false;
        });

        $cancel.click(function()
        {
            onCancel.apply(elm);
            onRemove.apply($container);

            return false;
        });

        $container.append(self.messages.confirm)
                  .append( "&nbsp;" )
                  .append( $ok )
                  .append( self.messages.separator )
                  .append( $cancel);

        $container.insertAfter( $(elm).parent() );
    }
    
    /**
     * Open Window
     *
     * Abre uma janela de autenticação de um serviço.
     *
     * @author Marcos Passos
     * @method openWindow
     * @param Object service - elemento relacionado
     * @return void
     */
    this.openWindow = function(service)
    {
        /*if(hasPopupBlock())
        {
            showMessage('Parece que você tem um bloqueador de popups. Por favor, desabilite-o e tente novamente. (<a href="{base_dir}infos/help/#disable-popup">saiba como</a>)', 'error', 8000, '#bookess-connect');
            return false;
        }*/

        var urlToken = self.urlTokens[service.value] ? self.urlTokens[service.value] : "";

        var popAuth = popup(urlToken, 'service' + service.value, {width: 800, height: 400, top: 'center', left: 'center'});

        if(!urlToken)
        {
            popAuth.document.write('<htm><head><title>' + self.messages.loading + '</title></head><body><span style="font-size:12px; font-family: Arial, Tahoma;">' + self.messages.loading + '</span></body></html>');
            self.setWindow(service, popAuth);

            var callback = function(response)
            {
                self.urlTokens[service.value] = response;
                popAuth.location.href = response;
            };

            self.httpRequest(self.SERVICE_GET_URL_TOKEN, service, callback);
        }
        
    };


    /**
     * Check Windows
     *
     * Verficia se uma janela foi fechada
     *
     * @author Marcos Passos
     * @method checkWindows
     * @return void
     */
    this.checkWindows = function()
    {
        if(self.windows.interval)
        {
            return false;
        }

        self.windows.interval =
        setInterval(function()
        {
            if(self.getSize(self.windows) == 0)
            {
                clearInterval(self.windows.interval);
                return false;
            }

            for(var name in self.services)
            {
                if(self.windows[name] && (!self.windows[name].win || self.windows[name].win.closed))
                {
                    self.onWindowClose.apply(self.windows[name].elm, [name]);
                    self.removeWindow(name);
                }
            }

        }, 100);
    }

    /**
     * On Window Close
     *
     * Evento disparado quando uma janela é fecada.
     *
     * @author Marcos Passos
     * @method checkWindows
     * @param String ServiceName - nome do serviço referente a janela
     * @return void
     */
    this.onWindowClose = function(serviceName)
    {
        var service = this;

        self.hideLoading(service);
        self.enable(service, false);
    };

    this.onComplete    = function() {};
    this.onChanged      = function() {};
    this.onChange      = function() {};
    this.onWindowClose = function() {};
    this.onRemoveService = function(){};
    this.changeStatus  = function() {};

    this.httpRequest = function(url, service, callback)
    {
        $.ajax
        ({
            type: 'GET',
            dataType: 'text',
            url: url + service.value + '/',
            success: callback
        });
    };

    this.getServiceObject = function(name)
    {
        return $('#service-' + name);
    }

    this.showLoading = function(elm)
    {
        $(elm).parent().addClass('loading');
    };

    this.hideLoading = function(elm)
    {
        $(elm).parent().removeClass('loading');
    };

    this.disable = function(elm, value)
    {
        $(elm).attr('disabled', true);

        if(typeof value != 'undefinied')
        {
            self.checked(elm, value);
        }
    };

    this.enable = function(elm, value)
    {
        $(elm).attr('disabled', false);

        if(typeof value != 'undefinied')
        {
            self.checked(elm, value);
        }

    };

    this.checked = function(elm, value)
    {
        $(elm).attr('checked', value);
    }

    this.removeWindow = function(name)
    {
        if(self.windows[name])
        {
            delete self.windows[name];
        }
    };

    this.getSize = function(obj)
    {
        var len = 0;
        for (var k in obj) len++;

        return len;
    }

    this.setWindow = function(service, win)
    {
        self.windows[service.value] = {win: win, elm: service};
        self.checkWindows();
    }

    this.getWindow = function(service)
    {
        return this.windows[service.value];
    }

    this.getStatus = function(elm)
    {
        var status = ['on', 'off', 'disabled'];

        for(var s in status)
        {
            if($(elm).parent().hasClass('service-' + status[s]))
            {
                return status[s];
            }
        }

    }
}

function BookessServicesMaintenance()
{
    this.prototype = BookessServices.call(this);

    var self = this;

    this.onComplete = function(name)
    {
        var service = self.getServiceObject(name);

        self.removeWindow(name);
        self.enable(service);
        self.hideLoading(service);
        
        if(self.getStatus(service) == 'off')
        {
            $(service).qtip('destroy');
        }

        $('.import-photo').show();
        $('#image-' + name).show();

        self.changeStatus(service, self.SERVICE_STATUS_ON);

        showMessage(self.messages.actived, null, 8000, '#bookess-connect');

    };

    this.onRemoveService = function(name)
    {
        $('#image-' + name).hide();
        showMessage(self.messages.removed, null, 8000, '#bookess-connect');
    };

    this.onChange = function()
    {
        var service = this;
        var checked = $(this).is(':checked');

        if(checked)
        {
            self.disable(service, false);
            self.showLoading(service);
            self.openWindow(service);
        }
        else
        {
            self.disable(service, true);

            var callback = function(response)
            {
                self.hideLoading(service);
                self.changeStatus(service);
                self.enable(service);

                self.urlToken = null;

                self.onRemoveService.apply(service, [service.value]);
            };

            self.showConfirm(service,
            function()
            {
                self.showLoading(service);
                self.httpRequest(self.SERVICE_URL_REMOVE_SERVICE, service, callback);
            },
            function()
            {
                self.enable(service, true);
            });
        }
    };

    this.onWindowClose = function(serviceName)
    {
        var service = this;

        self.hideLoading(service);
        self.enable(service, false);
    };

 
    this.changeStatus = function(elm, status)
    {
        var className = 'service-';
        var checked = true;

        $(elm).parent().removeClass('service-on service-off service-disabled');

        switch(status)
        {
            case self.SERVICE_STATUS_ON:
                {
                    checked = true;
                    className += 'on';
                    break;
                }

            case self.SERVICE_STATUS_OFF:
                {
                    checked = false;
                    className += 'off';
                    break;
                }

            default:
                {
                    checked = false;
                    className += 'disabled';
                    break;
                }
        }

        self.checked(elm, checked);
        $(elm).parent().addClass(className);
    }

    this.start = function()
    {
        $('input[name=services]')
        .each(function()
        {
            var name = $(this).val();

            self.changeStatus(this, self.services[name]);
        })
        .bind(($.browser.msie ? 'click' : 'change'), self.onChange);
    }

}


function BookessServicesSignup()
{
    this.prototype = BookessServices.call(this);

    var self = this;
    var completed = [];

    this.onComplete = function(name)
    {
        var service = self.getServiceObject(name);

        completed[name] = true;

        self.removeWindow(name);
        self.enable(service);
        self.hideLoading(service);
        self.changeStatus(service, self.SERVICE_STATUS_ON);

        showMessage(self.messages.complete, null, 8000, '.signup');

    };

    this.onChange = function()
    {
        var service = this;
        var checked = $(this).is(':checked');

        if(checked)
        {
            if(completed[this.value])
            {
                self.changeStatus(service, self.SERVICE_STATUS_ON);
            }
            else
            {
                self.disable(service, false);
                self.showLoading(service);
                self.openWindow(service);
            }

            $(this).parent().nextAll('.sub').show();            
        }
        else
        {
            $(this).parent().nextAll('.sub').hide();
            self.changeStatus(service);
        }

        self.onChanged.apply(service);
    };

    this.onWindowClose = function(serviceName)
    {
        var service = this;

        self.hideLoading(service);
        self.enable(service, false);
    };

    this.changeStatus = function(elm, status)
    {
        var className = 'service-';
        var checked = true;

        $(elm).parent().prevAll('.service-on, .service-off, .service-disabled').remove();

        switch(status)
        {
            case self.SERVICE_STATUS_ON:
                {
                    checked = true;
                    className += 'on';

                    $('<li />').addClass(className).insertBefore( $(elm).parent() );

                    break;
                }

            case self.SERVICE_STATUS_OFF:
                {
                    checked = false;
                    className += 'off';
                    break;
                }

            default:
                {
                    checked = false;
                    
                    break;
                }
        }

        self.checked(elm, checked);       
    }

    this.start = function()
    {
        $('input[name=services[]]')
        .bind(($.browser.msie ? 'click' : 'change'), self.onChange);
    }

    this.showLoading = function(elm)
    {
        $('<li />').addClass('loading').insertBefore( $(elm).parent() );
    };

    this.hideLoading = function(elm)
    {
       $(elm).parent().prevAll('.loading').remove();
    };

}

var Services = null;