Core.module("router");

(function(lib){
  var loc,
      api = {},
      dupe = function(obj){
        var newObject = {};
        
        for( arg in obj){
          newObject[arg] = obj[arg];
        }

        return newObject;
      },
      
      matcher = function(attr,regex,fcn){
        // build new location for this context
        var thisLoc = dupe(loc);

        // append match result to the appropriate loc attribute
        thisLoc[attr] = thisLoc[attr].match(regex);
        
        if(thisLoc[attr]){ 
          // facilitate the routing api.
          fcn(api,thisLoc); 
        }

        return thisLoc;
      };
  
  // single attribute curry
  function build(arg){
    return function(regex,fcn){
      return matcher(arg,regex,fcn);
    };
  }

  // define the routing api.
  api.path     = build('pathname');
  api.pathname = build('pathname');
  api.hash     = build('hash');
  api.hostname = build('hostname');
  api.href     = build('href');
  api.port     = build('post');
  api.protocol = build('protocol');
  api.search   = build('search');
  
  // combines all of the macros into one, allowing users to combine
  // more then one condition in a match,
  api.matches  = function(conditions,fcn){

    var result = {}, match = [];
    
    for(var condition in conditions){ 
      if(condition.hasOwnProperty(condition)){
        match = api[condition](api[condition]);

        if(match){
          result[condition] = match;
        }else{
          return null;
        }
      } 
    }

    if(result){
      fcn(api,result);
    }

    return result;
  };

  // append the router lib to the encapsulating library
  lib.router = function(routes){
    routes.draw = function(hash){
      loc = hash || document.location;
      // handle new location 
      routes(api);
    };

    return routes;
  };
})(Core);

