/**
 * @author Michael
 * Think about providing an optional result target
 *   if this is supplied, then hide/don't render our version and populate it's innerHTML instead.
 */
var pct;
//var lastrequest = null;

var serveraddress = "http://services.beacon-dodsworth.co.uk/TimeTravel/TimeTravel.ashx";

function timetravel_init(params)
{
    this.params = eval(params);
    this.containerdiv = document.getElementById(params.container);
    loadpct();

    //Build the DOM for the Timetravel example
    BuildTTFramework();
    //Cache data used in populating the drop downs
    //Once this is available, then populate source and target area drop-downs
}

function loadpct()
{
    //Load the Postcodetree script
    var headtag = document.getElementsByTagName("head").item(0);
    var scripttag = document.createElement("script");
    scripttag.src = serveraddress + "?callback=pctloaded";
    headtag.appendChild(scripttag); 
}

function pctloaded(postcodetree)
{
    pct = postcodetree;
    //Populate Area level dropdowns (source and target)
    populateSelect('ddareasource');
    populateSelect('ddareatarget');
}

function populateSelect(selectid)
{
    var area = "";
    var district = "";
    var dd = document.getElementById(selectid);
    //Clear this dropdown
    if(dd)
    {
        dd.innerHTML = "";
        switch(selectid)
        {
            case 'ddareasource':
                for(var area in pct)
                {dd.appendChild(makeoption(area.toString(),area.toString()));}   
                populateSelect('dddistrictsource');
                break;
            case 'ddareatarget':
                for(var area in pct)
                {dd.appendChild(makeoption(area.toString(),area.toString()));}
                populateSelect('dddistricttarget');
                break;
            case 'dddistrictsource':
                area = document.getElementById('ddareasource').value;
                for(district in pct[area])
                {dd.appendChild(makeoption(district.toString(),district.toString()));}
                populateSelect('ddsectorsource');
                break;
            case 'dddistricttarget':
                area = document.getElementById('ddareatarget').value;
                for(district in pct[area])
                {dd.appendChild(makeoption(district.toString(),district.toString()));}
                populateSelect('ddsectortarget');
                break;
            case 'ddsectorsource':
                area = document.getElementById('ddareasource').value;
                district = document.getElementById('dddistrictsource').value;
                for(sector in pct[area][district])
                {dd.appendChild(makeoption(sector.toString(),pct[area][district][sector]));}
                break;
            case 'ddsectortarget':
            {
                area = document.getElementById('ddareatarget').value;
                district = document.getElementById('dddistricttarget').value;
                for(sector in pct[area][district])
                {dd.appendChild(makeoption(sector.toString(),pct[area][district][sector]));}
                break;
            }
        }
        dd.selectedIndex = 0;
    }
}

function makeoption(text,value)
{
    var o = document.createElement('option');
    o.text = text;
    o.value = value;
    o.innerHTML = text;
    return o;
}

function BuildTTFramework()
{
    //As innerHTML is so much faster than DOM building, this is what we would like to do.  *Investigate*
    //Works well in FF, but IE seems to convert the set innerHTML into an incomplete DOM, yet throws
    //no errors.  By building the DOM ourself, at least errors can be caught and debugged as they occur.
    
    //TODO, add events later, so that this stage can be missed/overloaded etc.
    //A seperate call will populate it with data and add events
    //So that we can miss this stage out to allow greater customisation.
    
    this.containerdiv.innerHTML = "";
    var ttform = document.createElement("form");
    ttform.setAttribute("onsubmit","return false;");        // Added 5/11/07 by Richard (Semlyen IT) to suppress form submission now image buttons are being used.

    ttform.appendChild(makelabeldiv("arealabel","Area"));
    ttform.appendChild(makelabeldiv("districtlabel","District"));
    ttform.appendChild(makelabeldiv("sectorlabel","Sector"));
    ttform.appendChild(makelabeldiv("postcodelabel","Postcode"));
    ttform.appendChild(rowenddiv());
    
    //From and to labels needed infront of the selection
    var fromlabel = document.createElement('label');
    fromlabel.setAttribute("for","ddareasource");
    fromlabel.innerHTML = "Source (from):";
    ttform.appendChild(fromlabel);
    
    ttform.appendChild(makedd("areasource","ddareasource",function(){populateSelect('dddistrictsource');}));
    ttform.appendChild(makedd("districtsource","dddistrictsource",function(){populateSelect('ddsectorsource');}));
    ttform.appendChild(makedd("sectorsource","ddsectorsource",function(){populateSelect('postcodesource');}));
    //Put in '<div id="postcodesource"></div>';
    ttform.appendChild(rowenddiv());
    
    var tolabel = document.createElement('label');
    tolabel.setAttribute("for","ddareatarget");
    tolabel.innerHTML = "Destination (to):";
    ttform.appendChild(tolabel);
    
    ttform.appendChild(makedd("areatarget","ddareatarget",function(){populateSelect('dddistricttarget');}));
    ttform.appendChild(makedd("districttarget","dddistricttarget",function(){populateSelect('ddsectortarget');}));
    ttform.appendChild(makedd("sectortarget","ddsectortarget",function(){populateSelect('postcodetarget');}));
    //Put in '<div id="postcodetarget"></div>';
    ttform.appendChild(rowenddiv());
    
    var submit = document.createElement("input");
    submit.id = "ttsubmit";
    submit.setAttribute("value","Go");
    submit.setAttribute("src","/images/go-button-purple.gif");                  // changed 11/5/07 by Richard (Semlyen IT) to use rollover image buttons (requires input to be type="image"
//    submit.setAttribute("onmouseover","this.src='/images/go-button-purple-hover.gif';");
    submit.onmouseover= function() { this.src = '/images/go-button-purple-hover.gif'; }
//    submit.setAttribute("onmouseout","this.src='/images/go-button-purple.gif';");
    submit.onmouseout= function() { this.src = '/images/go-button-purple.gif'; }
    submit.setAttribute("id", "ttsubmitbtn");
    submit.setAttribute("type","image");

    submit.onclick = function(){getDriveTime(); return false;};
    ttform.appendChild(submit);
    
    var processing = document.createElement("div");
    processing.id = "ttprocessing";
    processing.innerHTML = "processing";
    ttform.appendChild(processing);
    
    var result = document.createElement("div");
    result.id = "driveresult";
    result.innerHTML = "&nbsp;";
    ttform.appendChild(result);
    
    this.containerdiv.appendChild(ttform);
    
}

function makelabeldiv(id,innerHTML)
{
    var lbl = document.createElement("div");
    lbl.id = id;
    lbl.setAttribute("class","tttitle");
    lbl.className = "tttitle";
    lbl.innerHTML = innerHTML;
    return lbl;
}
function rowenddiv()
{
    var mydiv = document.createElement("div");
    mydiv.setAttribute("class","rowend");
    return mydiv;
}
function makedd(divid,selectid,selectchange)
{
    //var ddcontainer = document.createElement("div");
    //ddcontainer.id = divid;
    var ddselect = document.createElement("select");
    ddselect.id = selectid;
    ddselect.onchange = selectchange;
    //ddcontainer.appendChild(ddselect);
    //return ddcontainer;
    return ddselect;
}
function getDriveTime()
{
    var sourceid = document.getElementById('ddsectorsource').value;
    var targetid = document.getElementById('ddsectortarget').value;
    var d = new Date();
    //var scriptid = "tag" + sourceid + targetid + d.getTime();
    var scriptid = "dscript";
    var headtag = document.getElementsByTagName("head").item(0);
    var scripttag = document.getElementById(scriptid);
    if(scripttag)
        headtag.removeChild(scripttag);
    
    scripttag = document.createElement("script");
    scripttag.id = scriptid;
    scripttag.src = serveraddress + "?function=drive&callback=ShowResult&id=" + d.getTime() +"&source=" + sourceid + "&target=" + targetid;
    headtag.appendChild(scripttag); 
    //Show processing and store last request
    var processing = document.getElementById("ttprocessing");
    processing.style.display = "block";
    var resultdiv = document.getElementById('driveresult');
    resultdiv.style.display = "none";
    //lastrequest = scriptid;
}

function ShowResult(result,scriptid)
{
    //Check that this is the result that we are waiting for.
    //if(lastrequest == scriptid)
    //{
        //Hide processing
        var processing = document.getElementById("ttprocessing");
        processing.style.display = 'none';
        //Source and target are built as they might be written (not BD format)
        //and "trimmed" so that they look the same in IE and FF
        var source = document.getElementById('ddareasource').value.replace(/^\s+|\s+$/g,'') + document.getElementById('dddistrictsource').value.replace(/^\s+|\s+$/g,'') + " " + document.getElementById('ddsectorsource')[document.getElementById('ddsectorsource').selectedIndex].innerHTML.replace(/^\s+|\s+$/g,'');
        var target = document.getElementById('ddareatarget').value.replace(/^\s+|\s+$/g,'') + document.getElementById('dddistricttarget').value.replace(/^\s+|\s+$/g,'') + " " + document.getElementById('ddsectortarget')[document.getElementById('ddsectortarget').selectedIndex].innerHTML.replace(/^\s+|\s+$/g,'');
        //Insert the result into script;
        var resultdiv = document.getElementById('driveresult');
        var drivemessage = "<p>";
        if(result == "-1")
            drivemessage += "It may not be possible to drive from " + source + " to " + target;
        else if(result == "-60")
            drivemessage += "It takes longer than an hour to drive from " + source + " to " + target;
        else{
            var mtime = Math.round(result/60);
            if (mtime == 1)
                drivemessage += "It takes " + mtime + " minute to drive from " + source + " to " + target;
            else
                drivemessage += "It takes " + mtime + " minutes to drive from " + source + " to " + target;
        }
        resultdiv.innerHTML = drivemessage + "</p>";
        resultdiv.style.display = "block";
    //}
    //Delete the script tag
    //var headtag = document.getElementsByTagName("head").item(0);
    //var scripttag = document.getElementById(scriptid);
    //headtag.removeChild(scripttag);
}
