/**
 * Request javascript style class
 */

sgRequest =
{
    getURI : function(url)
    {
        if(!url)
        {
            var url = document.location.href;
        }
        return "/" + url.split(/[\/]+/).slice(2).join("/");
    },
    getPath : function(url)
    {
        return  document.location.pathname;
    },
    redirect : function(url)
    {
        document.location.href = url;
    },
    getAnchor : function()
    {
        try
        {
            var B =/#([0-9a-z_\/-]+)/;
            var A = B.exec(sgRequest.getURI());
            if(A)
            {
                return A[1];
            }
            else
            {
                return false;
            }
        }
        catch(C)
        {
            return false;
        }
    },
    ajaxifyLink : function()
    {
        $('a.ajaxify').unbind('click').bind('click',function(event)
        {
            event.preventDefault();

            var actionRegex = new RegExp('action:(replace|append|remove|change-class)');
            var actionClass = $(this).attr('class').match(actionRegex);
            var actionToPerform = actionClass[1];

            var destinationClass = $(this).attr('class').match(new RegExp('action:'+ actionToPerform + ':([^ ]+)'));
            var destination = destinationClass[1];

            var hasAnchor = $(this).hasClass('anchor');
            var link = $(this).attr('href');
            $(this).addClass('loading');

            anchor = $(this);

            $.post(this.href,{},function(response)
            {
                switch(actionToPerform)
                {
                    case 'replace':
                        $(destination).html(response);
                        break;
                    case 'append':
                        var parent = $(destination).parent();
                        $(destination).remove();
                        parent.append(response);
                        break;
                    case 'remove':
                        if(response != 'KO')
                        {
                            $(destination).remove();
                        }
                        break;
                    case 'change-class':
                        $(destination).toggleClass(response);
                        break;
                // Add rest of action here
                }

                anchor.removeClass('loading');
                $(destination).removeClass('loading');
                $(this).removeClass('loading');

                sgRequest.ajaxifyLink();

                if(hasAnchor)
                {
                    sgRequest.redirect('#' + link);
                }

            });
        });

        $('form.ajaxify').unbind('submit').bind('submit',function(event)
        {
            event.preventDefault();

            var options = {
                success : sgRequest.parseAjaxifiedResponse,
                beforeSubmit : sgRequest.prepAjaxifiedRequest
            };

            // this used to be all in one but needed a bit of refactoring due to all hardcore rebinding for forms
            // old stuff will work as before but new things can define standard ajaxForm() options
            // allowing easy overriding of callbacks.
            // parseAjaxifiedResponse() supports the action:dostuff#here format. jsut pass it as a string
            // in last parameter. or not, it will pick it up normally from class
            $(this).closest("form").ajaxSubmit(options);

            return false;
        });
    },
    prepAjaxifiedRequest : function(formData, jqForm, options) {
        var form = $(jqForm[0]);
        form.addClass('loading');

        return true;
    },
    parseAjaxifiedResponse : function(response, statusText, xhr, $form, action) {
        // check first to see if the response contains a link to prompt for user-login 
        var responseDomObj = $(response);
        var redirectInstruction = responseDomObj.find("a.lightboxredirect");
        if (redirectInstruction.length != 0)
        {
            sgOpenInLightbox(redirectInstruction);
        }
        
        var form = $($form[0]);
        var actionRegex = new RegExp('action:(replace|insert-after|append|insert-before|fade|hide|redirect|change-class)');

        if (action == null) {
            action = form.attr('class');
        }

        var actionClass = action.match(actionRegex);
        var actionToPerform = actionClass[1];

        var destinationClass = action.match(new RegExp('action:'+ actionToPerform + ':([^ ]+)'));
        var destination = destinationClass[1];

        var hasAnchor = form.hasClass('anchor');
        var link = form.attr('action');

        // Response may contain notice div and content div;
        // insert them into two places on the page
        var responseDomObj = $(response);
        var notice = responseDomObj.find("div.notice");
        var content = responseDomObj.find("div.content");
        var currentNotice = $("div.notice");

        // Clear current notice div
        if (currentNotice.length) {
            currentNotice.empty();
        }

        // Add new notice div above the form
        if (notice.length) {
            // Replace and display current notice div
            currentNotice.html(notice.html());
            currentNotice.show();
            // Replace response with content; it may be empty
            response = content.html();
        }
        
        // Display response content on success
        if (response && response.length) {
            switch(actionToPerform)
            {
                case 'append':
                    $(destination).append(response);
		 	// @todo - test this!
                    form.hide();
                    break;
                case 'replace':
                    $(destination).html(response);
                    break;
                case 'insert-after':
                    response.prepend($(destination));
                    break;
                case 'insert-before':
                    $(destination).prepend(response);
                    break;
                case 'change-class':
                    $(destination).toggleClass(response);
                    break;
            // Add rest of action here
            }
        }
        form.removeClass('loading');
        // why is it here?
        sgRequest.ajaxifyLink();
        if(hasAnchor) {
            sgRequest.redirect('#' + link);
        }

    },
    ajaxLoad : function()
    {
        $(window).load(function(event)
        {
            var divs = $('div.ajaxload');
            var len = divs.length;
            for (var i = 0; i < len; i++)
            {
                component = $(divs[i]).attr('id').split("-");
                url = '/sgco/' + component[1] + '/' + component[2];
                if(component[3])
                {
                    url += '/' + component[3];
                }

                $(divs[i]).load(url, {
                    'params': {
                        'request_uri': location.pathname
                        }
                    }, function() {
                    $(this).removeClass('loading');
                    sgRequest.ajaxifyLink();

                });
            }
        });
}
};

/*
 * Check if URL has an anchor on load and redirect to it.
 */
if(sgRequest.getAnchor())
{
    var ar = sgRequest.getAnchor().split('/');
    if(!ar[0])
    {
        sgRequest.redirect(sgRequest.getAnchor());
    }
}

/*
 * Load when dom is ready.
 */
$(document).ready(function()
{
    sgRequest.ajaxLoad();
    sgRequest.ajaxifyLink();
});

