/*
*  Port of some request specific Catalyst functionallity
*  to JavaScrip
*/

// Catalyst uri_for
//
// uri_for('edit/')
// uri_for('edit/', [5,6,7]) // edit/5/6/7
// uri_for('edit/', { a: 5, b: 6} ) // edit?a=5&b=6
// uri_for('edit/', [5,6,7], { a: 5, b: 6}) // edit/5/6/7?a=5&b=6



Catalyst            = {};
Catalyst.base       = '';
Catalyst.namespace  = '';


/*
*  Port of $c->uri_for to JavaScript
*  param: String - path
*  param: Array  - url additions
*  param: Object - query qrguments
*
*  example: uri_for('edit/')  -> /base/current/edit/
*  example: uri_for('/edit/') -> /base/edit/
*  example: uri_for('/edit/', [1,'some', 3]) -> /base/edit/1/some/3
*  example: uri_for('/edit/', {a: 5, b: 6}) -> /base/edit/?a=5&b=6
*  example: uri_for('/edit/', [1,2,3], {a: 5, b: 6}) -> /base/edit/1/2/3/?a=5&b=6
*/
Catalyst.uri_for = function() {
    var url         = arguments[0];
    var ctrl_param  = arguments[1] || null;
    var get_param   = arguments[2] || null;

    var res_url = Catalyst.base;

    // we got relative url; append namespace
    if(!url.match(/^\//))
        res_url += Catalyst.namespace + '/';

    if(url.match(/^\//))
        res_url += url.replace(/^\//, '');
    else
        res_url += url;

    // we got array as second argument
    if(ctrl_param && ctrl_param.length) {
        res_url = res_url.replace(/\/$/, '');

        for(var i=0; i<ctrl_param.length; i++) {
            var arg = ctrl_param[i];
            res_url += '/' + arg;
        }
    }

    // we got key -> value pairs as second argument
    else if(ctrl_param) {
        res_url += '?';
        for(var k in ctrl_param) {
            var v = ctrl_param[k];
            res_url += k + '=' + v + '&';
        }
    }

    // we got third parameter key -> value pairs
    if(get_param) {
        res_url += '?';
        for(var k in get_param) {
            var v = get_param[k];
            res_url += k + '=' + v + '&';
        }
    }


    return res_url;
}


/*
*   redirect function
*/
function go( url, args, query ){
    window.location = Catalyst.uri_for( url, args, query );
}