var calcPath = 'http://www.tripbase.com/flight-CO2-calculator/';
//var calcPath = '';

var calculator = '<div id="carbonWidget" style="text-align: center;background: url('+calcPath+'images/bg.jpg) no-repeat; height:428px; width:170px; ">';
calculator += '<form action="'+calcPath+'query.php" method="post" style="margin:0px; padding:0px;">';
calculator += '<fieldset style="text-align: left; border: 0px; padding:10px; margin: 0px; padding-top: 60px; padding-bottom: 5px;">';
calculator += '<label style="font-family: Trebuchet MS; color: #000; font-weight: bold; font-size: 16px; margin-top:5px; margin-bottom:2px; display:block;" for="class">Class:</label>';
calculator += '<select style="width:149px; color: #000; height:22px; padding:2px; border: 1px solid #cfcfcf; font-size: 12px;" name="class" id="class">';
calculator += '<option value="-">-- Please Select --</option>';
calculator += '<option value="0">Domestic   - All</option>';
calculator += '<option value="1">Short Haul - Economy</option>';
calculator += '<option value="2">Short Haul - Bus./First</option>';
calculator += '<option value="3">Long Haul  - Economy</option>';
calculator += '<option value="4">Long Haul  - Economy+</option>';
calculator += '<option value="5">Long Haul  - Business</option>';
calculator += '<option value="6">Long Haul  - First</option>';
calculator += '</select>';
calculator += '<input type="hidden" name="fromCode" id="fromCode" />';
calculator += '<label style="font-family: Trebuchet MS; color: #000; font-weight: bold; font-size: 16px; margin-top:5px; margin-bottom:2px; display:block;" for="fromDesc">Departure City:</label>';
calculator += '<input style="width:150px; color: #000; height:22px; padding:2px; border: 1px solid #cfcfcf; font-size: 12px;" type="text" name="fromDesc" id="fromDesc"/>';
calculator += '<input type="hidden" name="toCode" id="toCode" />';
calculator += '<label style="font-family: Trebuchet MS; color: #000; font-weight: bold; font-size: 16px; margin-top:5px; margin-bottom:2px; display:block;" for="toDesc">Destination City:</label>';
calculator += '<input style="width:150px; color: #000; height:22px; padding:2px; border: 1px solid #cfcfcf; font-size: 12px;" type="text" name="toDesc" id="toDesc" />';
calculator += '</fieldset>';
calculator += '</form>';
calculator += '<p class="info" style="font-family: Trebuchet MS !important;  position:relative; z-index: 2; color: #000; margin:0 10px; font-weight:bold; text-align:center; font-size: 14px;">APPROX CO2 EMISSIONS Per Person (in tonnes)</p>';
calculator += '<div id="Co2" style="color:#FF0000; font-family:Trebuchet MS; font-size:21px; font-weight:bold; height:40px; margin-top:6px; text-align:center;">';
calculator += '<img id="loading" src="'+calcPath+'images/loading.gif" style="display:none;" alt="loading data..."/>';
calculator += '</div>';
calculator += '<div id="info" style="border: 1px solid #c0c13d; color: #000; background: #fdfe98; font-size: 0.6em; width:141px; margin:0px auto 0; padding:2px 2px; text-align:center;">';
calculator += '<p style="color: #000; font-family: Trebuchet MS; margin: 0px; padding:0px;">Calculation based on <a href="http://www.defra.gov.uk/environment/business/reporting/pdf/passenger-transport.pdf" title="DEFRA" rel="nofollow" style="color:blue;">DEFRA</a> "Seating Class Based CO2 Emission Factors for Passenger Flights", calculated using the <a href="http://en.wikipedia.org/wiki/Great-circle_distance" rel="nofollow" title="Wikipedia - Great Circle Distance" style="color:blue;">Great Circle Distance</a> based on Geolocated IATA Codes.</p>';
calculator += '</div>';
calculator += '<div class="suggestionsBox" id="suggestions" style="float:left; display: none; position: relative; z-index:5; background: #fff; left: 12px; top: -200px; margin: 0px 0px 0px 0px; width: 144px; border: 1px solid #000; color: #000;">';
calculator += '<div class="suggestionList" id="autoSuggestionsList" style="margin: 0px; padding: 0px;">';
calculator += '</div>';
calculator += '</div>';
calculator += '</div>';

var jQueryScriptOutputted = false;
function initJQuery() {
    
    //if the jQuery object isn't available
    if (typeof(jQuery) == 'undefined') {
    
    
        if (! jQueryScriptOutputted) {
            //only output the script once..
            jQueryScriptOutputted = true;
            
            //output the script (load it from google api)
            document.write("<scr" + "ipt type=\"text/javascript\" src=\""+calcPath+"js/jquery.js\"></scr" + "ipt>");
        }
        setTimeout("initJQuery()", 50);
    } else {
        //do anything that needs to be done on document.ready
        $(function() {  
            function geoReturn(data){
                
                $('#loading').hide();
                if ( data.co2 != '' ) {
                    $('#Co2').html('<span style="width:132px; background:#fff; text-align:center; padding:4px 37px; ">'+data.co2+'</span>');
                } else {
                    $('#Co2').html('<span style="width:132px; background:#fff; text-align:center; padding:4px 37px; ">?</span>');
                }
            }

            function bindLis(fromTo) {
                $('#autoSuggestionsList ul li').each(
                    function( intIndex ){
                        $( this ).bind (
                        "click",
                        function(){ fill($(this).attr('id'), $(this).html(),fromTo); }
                    );
                });    
            }

            function checkCall() {
                if ( $('#class').val() != "-" && $('#fromCode').val() != "" && $('#toCode').val() != "" ) {
                    $('#loading').show();
                    $.getJSON( 
                      calcPath+"query.php?jsoncallback=?", 
                      {codeString: ""+$('#fromCode').val()+"|"+$('#toCode').val()+"|"+$('#class').val()+""}, 
                      function(data) { geoReturn(data); $('#loading').hide(); } 
                    );
                }
            }

            function lookup(inputString,fromTo) {
                if ( fromTo == '') { fromTo='from'; }
                if(inputString.length == 0) {
                    $('#loading').hide();
                    // Hide the suggestion box.
                    $('#suggestions').hide();
                } else {
                    $('#loading').show();
                    try {
                        $.getJSON(calcPath+"query.php?jsoncallback=?", {queryString: ""+inputString+""}, function(data,status){
                            if(data.results.result.length > 0 ) {
                                $('#suggestions').show();
                                var content = '';
                                $.each(data.results.result, function(i,item){
                                    try {
                                        if ( item.key && item.desc ){
                                            content = content+'<li style="margin: 0px 0px 3px 0px; width:120px; cursor: pointer; list-style-type:none; font-size: 11px; font-family: Trebuchet MS;" id="'+item.key+'">'+item.desc+'</li>';
                                        }
                                        
                                    } catch (err) {
                                        //alert('problem:'+err);
                                    }
                                    
                                  });
    
                                $('#autoSuggestionsList').html('<ul style="margin: 0px; padding: 4px 0px 0px 4px; text-align:left;">'+content+'</ul>');
                                $('#autoSuggestionsList ul li').hover(function() {
                                    $(this).css('background-color','#659CD8');
                                }, function() { 
                                    $(this).css('background-color','');
                                });
                                bindLis(fromTo);
                            }
                        });
                    } catch(err) {
//                        alert('problem:'+err);
                    }
                }
            } // lookup

            function fill(thisId, thisValue, fromTo) {
               $('#'+fromTo+'Code').val(thisId);
               $('#'+fromTo+'Desc').val(thisValue);
               $('#suggestions').hide();
               $('#loading').hide();
               checkCall();
            }

            
            $('#carbonCalcContainer').prepend(calculator);
            $('#fromDesc').bind( "keyup", function(){ if ($('#fromDesc').val().length >= 2 ){ lookup($('#fromDesc').val(),'from'); } else { $('#suggestions').hide(); $('#loading').hide(); } });
            $('#toDesc').bind( "keyup", function(){ if ($('#toDesc').val().length >= 2 ){ lookup($('#toDesc').val(),'to'); } });
            
            $('#class').bind("change",function(){
                checkCall();
                return false;
            });
        });
    }
            
}

initJQuery();

