System.Gadget.onUndock = WhenUndocked;
System.Gadget.onDock = WhenDocked;
System.Gadget.Flyout.onShow = WhenShowFlyOut;
System.Gadget.Flyout.onHide = WhenHideFlyOut;
System.Gadget.onSettingsClosed  = WhenSettingsClosed ;
var baseUrl = "http://www.mappy.com/BtoB/mappy/";
var mapAction = "map?";
var itiAction = "iti?";
var labelColor = "#7dc622";
var inputColor = "black";
var flyOutHTML = "";
var flyOutStyle = "";
var mode = 0;
var imagebgheight = 150;
var imagebgurl = "url('../images/mappy_s_bg.png')";
var ab = null;
var infoHTML = "";
var infoStyle = "";
var updateAvailableShown = false;
var updateCheckFreq = 360000;

function init()
{
	setTimeout("loadab();", 500);
	ac0 = new ac(tWay, '');    
	ac1 = new ac(tWay1, '1');    
	ac2 = new ac(tWay2, '2');    
    System.Gadget.settingsUI = "settings.html";
	System.Gadget.Flyout.file = "messageFlyout.html";
	System.Gadget.Flyout.show = false;
    tWay.title = WAY_TITLE;
    tTown.title = TOWN_TITLE;
    tPC.title = POSTALCODE_TITLE;
    tWay1.title = WAY_TITLE;
    tTown1.title = TOWN_TITLE;
    tPC1.title = POSTALCODE_TITLE;
    tWay2.title = WAY_TITLE;
    tTown2.title = TOWN_TITLE;
    tPC2.title = POSTALCODE_TITLE;
    sStart.innerHTML = ITISTART;
    sEnd.innerHTML  = ITIEND;
    setDefault();
    setTimeout("checkWidgetInfo('"+updateUrl+"');", 500);
}

function setDefault()
{
    defTown = System.Gadget.Settings.read("defaultTown");
    if (defTown != null && defTown.length > 0)
    {
        tTown.value = defTown;
        tTown1.value = defTown;
        tTown2.value = defTown;
    }    
    buildCountryList(sCountry,'');
    buildCountryList(sCountry1,'iti');
    buildCountryList(sCountry2,'iti');
    getDefaultMode(); 
    showDefault();           
    showMode();
}

function showDefault()
{
    defaultWay(tWay);
    defaultWay(tWay1);
    defaultWay(tWay2);
    defaultPC(tPC);
    defaultPC(tPC1);
    defaultPC(tPC2);
    defaultTown(tTown);
    defaultTown(tTown1);
    defaultTown(tTown2);
    showStates(sState, mState, sCountry);    
    showStates(sState1, mState1, sCountry1);    
    showStates(sState2, mState2, sCountry1);    
}

function getDefaultMode()
{
    defaultMode = System.Gadget.Settings.read("defaultMode");
    if (defaultMode == "0")
        mode = 0;
    if (defaultMode == "1")
        mode = 1;
}

function switchMode()
{
	System.Gadget.beginTransition();
    mode= 1 - mode;
    showMode();
	System.Gadget.endTransition(System.Gadget.TransitionType.none,0);
}

function showMode()
{
    if (mode == 0)
    {
        imagebgheight = 150;
        imagebgurl = "url('../images/mappy_s_bg.png')";
        sTitle.innerHTML = m_Plan;
        mMap.style.display="block";
        mIti.style.display="none";
    }
    else
    {
        imagebgheight = 280;
        imagebgurl = "url('../images/mappy_m_bg.png')";    
        sTitle.innerHTML = m_iti_mode_iti;
        mMap.style.display="none";
        mIti.style.display="block";
    }
    if (System.Gadget.docked)
    {
        WhenDocked();
    }
    else
    {
        WhenUndocked();
	}    
}

function showStates(control, div, countrycontrol)
{
    var countrycode = countrycontrol.options[countrycontrol.selectedIndex].value;
    control.options.length=0;
    for(i = 0;i < states.length; i ++)
    {
        if (states[i].c == countrycode)
        {
            var opt = document.createElement("option");
            opt.text = states[i].l;
            opt.value = states[i].i;
            control.options.add(opt);
        }
    }    
    if (control.options.length>0)
    {
        var opt = document.createElement("option");
        opt.text = "----------";
        opt.value = "";
        opt.selected=true;
        control.options.add(opt,0);
        div.style.display = "block";
    }
    else    
    {
        div.style.display = "none";
    }
}

function buildCountryList(control, filter)
{
    defaultCountryCode = System.Gadget.Settings.read("defaultCountryCode");
    if (defaultCountryCode == "")
        defaultCountryCode = defaultdefaultCountryCode;
    control.options.length=0;
    for(i = 0;i < countries.length; i ++)
    {
        if ((filter.length == 0) || (countries[i].f==filter))
        {
            var opt = document.createElement("option");
            opt.text = countries[i].l;
            opt.value = countries[i].c;
            if (defaultCountryCode == opt.value) 
                opt.selected=true;
            control.options.add(opt);
        }
    }
}

function GetCountryCode(countryname)
{
    defaultCountryCode = System.Gadget.Settings.read("defaultCountryCode");
    if (defaultCountryCode == "")
        defaultCountryCode = defaultdefaultCountryCode;
    var cc = "";
    for(i = 0;i < countries.length; i ++)
    {
        if (countryname.toLowerCase()  == countries[i].l.toLowerCase())
        {
            cc = countries[i].c;
        }
    }
    if (cc == "") cc = defaultCountryCode;
    return cc;
}

function GetStateCode(statename, countrycode)
{
    var sc = "";
    for(i = 0;i < states.length; i ++)
    {
        if (states[i].c == countrycode && (states[i].l.toLowerCase() == statename.toLowerCase()))
        {
            sc= states[i].i;
        }
    }  
    return sc;
}

function addressbook(oac)
{
    if (ab == null)
	{
		setTimeout(function(){addressbook(elt, postfix)},100);
		return;
	}
    oac.popUp();
} 

function defaultWay(ctl)
{
    if ((ctl.value == "") || (ctl.value == WAY))
    {
        ctl.value = WAY;
        ctl.style.color = labelColor;
    }
    else
        ctl.style.color = inputColor;
}

function defaultTown(ctl)
{
    if ((ctl.value == "") || (ctl.value == TOWN))
    {
        ctl.value = TOWN;
        ctl.style.color = labelColor;
    }
    else
        ctl.style.color = inputColor;
}

function defaultPC(ctl)
{
    if ((ctl.value == "") || (ctl.value == POSTALCODE))
    {
        ctl.value = POSTALCODE;
        ctl.style.color = labelColor;
    }
    else
        ctl.style.color = inputColor;    
}

function enterWay(ctl)
{
    if (ctl.value == WAY)
        ctl.value = "";
    ctl.style.color = inputColor;
}

function enterTown(ctl)
{
    if (ctl.value == TOWN)
        ctl.value = "";
    ctl.style.color = inputColor;
}

function enterPC(ctl)
{
    if (ctl.value == POSTALCODE)
        ctl.value = "";
    ctl.style.color = inputColor;
}

function WhenSettingsClosed() {
    setDefault();
}

function searchmap()
{
    var vway = "";
    if (tWay.value != WAY)
        vway = tWay.value;
    var vState = "";
    if (sState.selectedIndex != -1)
        vState = sState.options[sState.selectedIndex].value;
    var vCountry = "";
    if (sCountry.selectedIndex != -1)
        vCountry = sCountry.options[sCountry.selectedIndex].value
    var vTown = "";
    if (tTown.value != TOWN)
        vTown = tTown.value;   
    var vPC = "";
    if (tPC.value != POSTALCODE)
        vPC = tPC.value;
    if (vTown.length > 0 || vPC.length > 0)
    {            
        var url = baseUrl+mapAction;
        url += "map.country_code="+vCountry;
        url += ";map.state_code="+vState;
        url += ";map.town="+vTown;
        url += ";map.way="+vway;
        url += ";map.postal_code="+vPC;
        window.open(url,'window');
    }
    else
    {
        flyOutHTML = '<body><div id="gadgetContent" style="font-family: Verdana; font-size: 8pt;"><label id="message">'+m_fill_town_alert+'</label><BR></div></body>';
		flyOutStyle = "background-color: #f1fbd3";
		ShowFlyOut(3000);        
    }
}

function searchiti()
{
    var vway1 = "";
    if (tWay1.value != WAY)
        vway1 = tWay1.value;
    var vState1 = "";
    if (sState1.selectedIndex != -1)
        vState1 = sState1.options[sState1.selectedIndex].value;
    var vCountry1 = "";
    if (sCountry1.selectedIndex != -1)
        vCountry1 = sCountry1.options[sCountry1.selectedIndex].value
    var vTown1 = "";
    if (tTown1.value != TOWN)
        vTown1 = tTown1.value;   
    var vPC1 = "";
    if (tPC1.value != POSTALCODE)
        vPC1 = tPC1.value;

    var vway2 = "";
    if (tWay2.value != WAY)
        vway2 = tWay2.value;
    var vState2 = "";
    if (sState2.selectedIndex != -1)
        vState2 = sState2.options[sState2.selectedIndex].value;
    var vCountry2 = "";
    if (sCountry2.selectedIndex != -1)
        vCountry2 = sCountry2.options[sCountry2.selectedIndex].value
    var vTown2 = "";
    if (tTown2.value != TOWN)
        vTown2 = tTown2.value;   
    var vPC2 = "";
    if (tPC2.value != POSTALCODE)
        vPC2 = tPC2.value;
        
    if ((vTown1.length > 0 || vPC1.length > 0)&&(vTown2.length > 0 || vPC2.length > 0))
    {            
        var url = baseUrl+itiAction;
        url += "iti.start.country_code="+vCountry1;
        url += ";iti.start.state_code="+vState1;
        url += ";iti.start.town="+vTown1;
        url += ";iti.start.way="+vway1;
        url += ";iti.start.postal_code="+vPC1;
        url += ";iti.end.country_code="+vCountry2;
        url += ";iti.end.state_code="+vState2;
        url += ";iti.end.town="+vTown2;
        url += ";iti.end.way="+vway2;
        url += ";iti.end.postal_code="+vPC2;
        window.open(url,'window');
    }
    else
    {
        flyOutHTML = '<body><div id="gadgetContent" style="font-family: Verdana; font-size: 8pt;"><label id="message">'+m_fill_town_alert+'</label><BR></div></body>';
		flyOutStyle = "background-color: #f1fbd3";
		ShowFlyOut(3000);        
    }
}

var thfo = null;
var reloadFlyOut = false;
var reloadTimeout = -1;
function ShowFlyOut(timeout)
{
    if (thfo != null)
    {
        clearTimeout(thfo);
        thfo = null;
        reloadFlyOut = true;
    	System.Gadget.Flyout.show = false;
    	reloadTimeout = timeout;
    }
    else
    {
	    System.Gadget.Flyout.show = true;
        thfo = setTimeout("HideFlyOut();", timeout);  
    }
}

function HideFlyOut() {
    thfo = null;
    reloadFlyOut = false;
    reloadTimeout = -1;
	System.Gadget.Flyout.show = false;
}

function WhenShowFlyOut() {
	System.Gadget.Flyout.document.body.innerHTML= flyOutHTML;
	System.Gadget.Flyout.document.body.style.cssText = flyOutStyle;
	System.Gadget.Flyout.document.body.style.width='250px';
	System.Gadget.Flyout.document.body.style.height='250px';
}

function WhenHideFlyOut()
{
    if (reloadFlyOut && reloadTimeout != -1)
        setTimeout("ShowFlyOut("+reloadTimeout+");", 50);  
}

function WhenUndocked()
{
    WhenDocked();  
}

function WhenDocked()
{
	System.Gadget.beginTransition();
	with(document.body.style)
	{
		width="129px";
        height=imagebgheight;
		backgroundImage=imagebgurl;
		marginTop="46px";
		marginLeft="5px";
	}
	System.Gadget.endTransition(System.Gadget.TransitionType.none,0);
}

function loadab()
{
    var nab = new Array();
    var contacts = System.ContactManager.Contacts;
	for (i=0, j=0;i < contacts.count;i++){
		var ct = contacts.item(i);
		var ctCity = ct.city;
		var ctName = ct.name;
		if(ctCity != null && ctCity != '' && ctName != null && ctName != '') {
		    nab[j] = ct;
			j++;
		}
    }
    ab = nab;
	setTimeout("loadab();", 300000);   
}

function ac(elt, postfix) {
	var show=false;
	var pos = -1;
	var match = new Array();
	var mouse_on = 0;
	var ac_cm = 0;
	var i;
	var slot = postfix;
	var oP = elt.offsetParent;
	this.popUp = function(){ if(show) ac_hide(true); else { ac_dblclick(); 
	mouse_on = 1; } }
	
	document.body.onclick = ac_hide;	

	function ac_dblclick(){
		ac_tomake = false;
		ac_generate(true);
	}	
	
	function ac_generate(all)
	{		
		a = document.getElementById('ac_t');
		_in = document.getElementById('ac_in');
		tb = document.getElementById('ac_tb');
		div = document.getElementById('ac_d');
		iframe = document.getElementById('ac_i');
		
		var x = eval(curTop(elt, null) + elt.offsetHeight);
		
		var y = eval(curLeft(elt, null) + 2);
		
		div.style.top = x + "px";			
		div.style.left = y + "px";
		
		iframe.style.top = (x + 4) + "px";
		iframe.style.left = (y + 4) + "px";
	
		var i;
		var nbGen = 0;
		if (ab != null)
		{
		    for (i=0;i < ab.length;i++){
			    if(document.getElementById('ac_td'+i)) tb.removeChild(document.getElementById('ac_tr'+i));
			    var ct = ab[i];
			    var ctCity = ct.city;
			    var ctName = ct.name;
			    nbGen++;
			    r = document.createElement("tr");
			    tb.appendChild(r);
			    r.id = 'ac_tr'+(i);
			    c = document.createElement("td");
			    r.appendChild(c);
			    c.innerHTML = ctName;
			    c.id = 'ac_td'+(i);
			    c.setAttribute('pos',i);
			    c.onclick = ac_onclick;
			    c.onmouseover = ac_onmouseover;
		    }
		}
		if(nbGen > 0) {
			show = true;
			pos = -1;
			div.style.display = 'block';
			if(a.offsetHeight < 60) {
				_in.style.height = (a.offsetHeight) + "px";
			} else {
				_in.style.height = "60px";
			}
		} else {
			mouse_on = 0;
			ac_hide();
		}
	}		

	
	function ac_onclick(evt){		
		if(!show) return;
		mouse_on = 0;
		pos = this.getAttribute('pos');
		ac_paint();
	}
	function ac_onmouseover(){
		mouse_on = 1;
		if(document.getElementById('ac_tr'+pos)) document.getElementById('ac_tr'+pos).className = '';
		pos = this.getAttribute('pos');
		if(document.getElementById('ac_tr'+pos)) document.getElementById('ac_tr'+pos).className = 's';
	}
	
	function ac_set(index){		
		if(document.getElementById("tWay" + slot)) {
		    document.getElementById("tWay" + slot).value =  ab[index].street;
            defaultWay(document.getElementById("tWay" + slot));
		}
		if(document.getElementById("tTown" + slot)) {
		    document.getElementById("tTown" + slot).value = ab[index].city;
            defaultTown(document.getElementById("tTown" + slot));          		    
		}
		if(document.getElementById("tPC" + slot)) {
		    document.getElementById("tPC" + slot).value = ab[index].postalCode;
		    defaultPC(document.getElementById("tPC" + slot));
		}
		if(document.getElementById("sCountry" + slot)) 
		{
 		    var cc = GetCountryCode(ab[index].country);
		    var cs = document.getElementById("sCountry" + slot);
            for (var i = 0; i < cs.options.length; ++i){  if (cs.options[i].value == cc)  {   cs.selectedIndex = i;   break;  }}
            showDefault();
		    if(document.getElementById("sState" + slot)) 
		    {
		        var sc = GetStateCode(ab[index].state, cc);
		        var ss = document.getElementById("sState" + slot);
                for (var i = 0; i < ss.options.length; ++i){  if (ss.options[i].value == sc)  {   ss.selectedIndex = i;   break;  }}
		    }		
		}		
		mouse_on = 0;
	}
	
	function ac_paint(){
		if(!show) return;
		show = false;

		if(document.getElementById('ac_tr'+pos)) ac_set(document.getElementById('ac_tr'+pos).cells[0].getAttribute('pos'));
		if(document.getElementById('ac_i')) {document.getElementById('ac_i').style.display = 'none';}
	}
	function ac_hide(force){
		if(mouse_on==0 || force){
			show = false;
			if(document.getElementById('ac_d')) {document.getElementById('ac_d').style.display = 'none';}
			if(document.getElementById('ac_i')) {document.getElementById('ac_i').style.display = 'none';}
		}
	}
}
function curTop(obj, ref){
	toreturn = 0;
	while(obj && ref!=obj){
		toreturn += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return toreturn;
}
function curLeft(obj, ref){
	toreturn = 0;
	while(obj && ref!=obj){
		toreturn += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	return toreturn;
}

function checkWidgetInfo(url)
{
    var oRequest = new XMLHttpRequest();
	oRequest.onreadystatechange = function() {
        setTimeout("checkWidgetInfo('"+url+"');", updateCheckFreq);	
		if (oRequest.readyState == 4) {
			if (oRequest.status == 200) {			    
				xml = oRequest.responseXML;
				showWidgetInfo(xml);
			}
		}
	}
	var t = new Date();
	// We add a parm to the url to avoid cache effect
	oRequest.open( "GET",url+'?t='+t.getTime(),true);
	oRequest.send(null);
}

function showWidgetInfo(xml)
{
    var lastVersion = xml.getElementsByTagName('Version')[0].attributes.getNamedItem('lastVersion').value;
    infoHTML = "";
    var oAddNode = null;
    var oAdvertisementsNode = xml.getElementsByTagName('Advertisements')[0];
    if (oAdvertisementsNode != null)
    {
        var oAddNodes = oAdvertisementsNode.getElementsByTagName('Ad');
        if (oAddNodes != null && oAddNodes.length != 0)
        {
            oAddNode = oAddNodes[0];
            var att = oAddNode.attributes.getNamedItem('active')
            if (att == null || att.value!="1")
                oAddNode = null;
        }
    }
            
    if (lastVersion != System.Gadget.version && (oAddNode == null || !updateAvailableShown))
    {
        var oNode = xml.getElementsByTagName('Version')[0];
        setInfo(oNode);
        updateAvailableShown = true;
    }
    else if (oAddNode != null)
    {
        setInfo(oAddNode);
        updateAvailableShown = false;
    }
}

function setInfo(oNode)
{
    infoImg.src = oNode.selectSingleNode('ImageUrl').text;
    infoImg.alt = oNode.selectSingleNode('AlternateText').text;
    infoImg.title = oNode.selectSingleNode('AlternateText').text;
    infoHTML = oNode.selectSingleNode('HtmlContent').firstChild.xml;
    infoStyle = oNode.selectSingleNode('HtmlContent').getElementsByTagName('body')[0].attributes.getNamedItem('style').value;
}

function showInfo()
{
    if (infoHTML != "")
    {
        flyOutHTML = infoHTML;
        flyOutStyle = infoStyle;
	    ShowFlyOut(10000);        
	}
}