from django.template import Context, loader
from django.http import HttpResponse, HttpResponseNotFound, Http404, HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404, get_list_or_404

from srsbrowser.models import SRS
from srsbrowser.forms import Upload

from osgeo import osr
import urllib

#from references.views.search import code_listing, count_results
#from references.views.render import output_proj

from django.conf import settings

from recaptcha import captcha
from graticules import render as gratrender

from django.utils import simplejson

FORMATS = {
  'text/xml': 'gml', 
  'text/proj4': 'proj4', 
  'application/proj4': 'proj4', 
  'application/x-proj4': 'proj4',
  'application/x-ogcwkt': 'ogcwkt',
}  

class FormatError(Exception): pass 


def JSONResponse(json, callback=None, mimetype="application/json", status_code = None):
    from django.http import HttpResponse
    
    if isinstance(json, basestring):
        json = simplejson.loads(json)
    
    response = HttpResponse()

    if callback:
        response.write('%s(%s);'%(callback, simplejson.dumps(json)))
        response['Content-Type'] = "application/javascript"
    else:
        response.write('%s'%simplejson.dumps(json))
    
    if mimetype:
        response['Content-Type'] = mimetype
    else:
        response['Content-Type'] = "application/json"
    
    if status_code:
        response.status_code = status_code
    
    response['Content-length'] = str(len(response.content))
    return response
