function call_api(fn, callback, vars) {
    var s = document.createElement('script');
    var url = 'http://www.theyworkforyou.com/api/'
        + fn + '?key=BD5xRaDfPCRgEPcxAyEfAgWc&callback=' + callback;
    for (var i in vars) {
        url += '&' + i + '=' + encodeURIComponent(vars[i]);
    }
    s.setAttribute('src', url);
    s.setAttribute('type', 'text/javascript');
    document.getElementsByTagName('head')[0].appendChild(s);
}

function lookup(pc) {
    call_api('getConstituency', 'const_received', { postcode: pc } );
}

function const_received(r) {
    if (r.error) {
        display('<i>Error:</i> ' + r.error, 'white', 'red');
        return;
    }
    name = r.name;
    call_api('getMP', 'mp_received', { constituency: name } );
}

function mp_received(r) {
    if (r.error) {
        display('<i>Error:</i> ' + r.error, 'white', 'red');
        return;
    }
	
    var text = '<form action="step2.php" method="post"><p>Your constituency: <input type="text" name="constituency" value="' + name + '"/><input name="Go to step 2 to find your MP" type="submit" value="Find your MP"  /></p></form>';
    {
        display(text, 'white', 'black');
    }
}

function display(text, bg, border) {
    var d = document.getElementById('result');
    d.innerHTML = text;
    d.style.backgroundColor = bg;
    d.style.borderColor = border;        
    d.style.display = 'block';
}
