//javascript

// Django CSRF framework
$(document).ajaxSend(function(event, xhr, settings) {
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});


		function lookup()
		{
			var cust_id = $('#customer_id').val();
			
			$.ajax('/json/?act=lookup', {type: 'POST', data: {
				customer_id: cust_id
			}, dataType: 'json'})
			.done(function(data) {
				//alert(data);
				if (data.success) {
					$('input[name=customer_name]').val(data.customer_name);
					$('input[name=customer_address]').val(data.address);
					$('input[name=customer_city]').val(data.city);
					$('input[name=customer_state]').val(data.state);
					$('input[name=customer_zip]').val(data.zip);
					$('input[name=customer_contact_name]').val(data.contact_name);
				}
			})
			.fail(function() { console.log("lookup error"); });
		}
		
//template	
//When the user leaves the field containing a lookup value it is looked up in database and fills other form fields automatically

<div class="customer_information">
    <span>Customer Information</span>
    <div class="formrow"> 
        <div class="formbox"> 
            <label>Customer Name</label> 
            <input type="text" name="customer_name" maxlength="255" />
        </div> 
    </div> 
    <div class="formrow"> 
        <div class="formbox"> 
            <label>Address</label> 
            <input type="text" name="customer_address" maxlength="255" /> 
        </div> 
    </div> 
    <div class="formrow"> 
        <div class="formbox formboxcity"> 
            <label>City</label> 
            <input type="text" name="customer_city" maxlength="255" /> 
        </div> 
        <div class="formbox formboxstate"> 
            <label>State</label> 
            <input type="text" name="customer_state" maxlength="255" />
        </div> 
        <div class="formbox formboxzip"> 
            <label>ZIP</label> 
            <input type="text" name="customer_zip" maxlength="255" /> 
        </div>
    </div> 
    <div class="formrow">
        <div class="formbox formboxhalf">
            <label>Customer ID#</label>
            <input onblur="Lookup()" type="text" id="customer_id" name="customer_id" maxlength="255" />
        </div>
        <div class="formbox formboxhalf">
            <label>Contact Name</label>
            <input type="text" name="customer_contact_name" maxlength="255" />
        </div>
    </div>
</div>

//urls.py

(r'^json/$', json)

//views.py

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.context import RequestContext

from myapp.models import customer

from django.core.serializers import serialize
from django.utils.simplejson import dumps, loads, JSONEncoder
from django.db.models.query import QuerySet

#extend simplejson to allow serializing django queryset objects directly
class DjangoJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, QuerySet):
            return loads(serialize('json', obj))
        return JSONEncoder.default(self, obj)

def json(request):

    if 'act' in request.GET:
        act = request.GET['act']

        if act == 'lookup':

            if 'customer_id' in request.POST:

                customer_id = request.POST['customer_id']
                customer_id = int(customer_id)
                
                try:
                    BP = customer.objects.get(cust_id_number=customer_id)
                    
                    success = 'record found'
            
                    cust_id_number = BP.cust_id_number
                    cust_customer_name = BP.cust_customer_name
                    cust_address = BP.cust_address
                    cust_city = BP.cust_city
                    cust_state = BP.cust_state
                    cust_zip = BP.cust_zip
                    cust_contact_name = BP.cust_contact_name
        
                    json_dict = {
                                 'success': success,
                                 'id_number': cust_id_number,
                                 'customer_name': cust_customer_name,
                                 'address': cust_address,
                                 'city': cust_city,
                                 'state': cust_state,
                                 'zip': cust_zip,
                                 'contact_name': cust_contact_name
                                 }
                    
                    json = dumps(json_dict, cls=DjangoJSONEncoder) #cls = helper
        
                    return HttpResponse(json)