 angular.module("restOrm", [
 ]).factory("Resource", ($http, $q) ->
+
+  startsWith = (s, sub) -> s.slice(0, sub.length) == sub
+  endsWith   = (s, sub) -> sub == '' or s.slice(-sub.length) == sub
+
+  # based on http://stackoverflow.com/a/2676231
+  _urljoin = (components...) ->
+    normalize = (str) ->
+      str.replace(/[\/]+/g, "/").replace(/\/\?/g, "?").replace(/\/\#/g, "#").replace /\:\//g, "://"
+    url_result = []
+
+    if components and (components.length > 0)
+      skip = 0
+      while (skip < components.length)
+        if components[skip]
+          break
+        ++skip
+      components = components[skip..] if skip
+
+    last_comp = null
+    for component in components
+      continue if not (component? and component)
+      last_comp = component
+      c_url = "#{component}".split("/")
+      for i in [0...c_url.length]
+        if c_url[i] is ".."
+          url_result.pop()
+        else if (c_url[i] is ".") or (c_url[i] is "")
+          continue
+        else
+          url_result.push c_url[i]
+
+    r = normalize url_result.join("/")
+    if components and (components.length >= 1)
+      component = "#{components[0]}"
+      if startsWith(component, "//")
+        r = "//" + r
+      else if startsWith(component, "/")
+        r = "/" + r
+
+      last_comp = "#{last_comp}"
+      if endsWith(last_comp, "/") and (not endsWith(r, "/"))
+        r = r + "/"
+    r
+
+  urljoin = ->
+    encodeURI _urljoin arguments...
+
   class Resource
     @urlPrefix: ''
     @urlEndpoint: ''

      collection

    @Search: (field, value) ->
      e_field = encodeURIComponent(field)
      e_value = encodeURIComponent(value)
      url = "#{@GetUrlBase()}search/#{e_field}/#{e_value}"
      $http(
        method: "GET"
        url: url


    @All: () ->
      collection = @_MakeCollection()
      url = urljoin @_GetURLBase()
      $http(
        method: "GET"
        url: url
