
//######################### map related functions ############################
function loadMap()
{
	   var mt = map.getMapTypes();
	// Overwriting the getMinimumResolution() and getMaximumResolution() methods

	   for (var i=0; i<mt.length; i++) {
	          mt[i].getMinimumResolution = function() {return 2;}
	          mt[i].getMaximumResolution = function() {return 5;}
      }
     
      //map.addControl(new GMapTypeControl());
        var largeMapControl = new GLargeMapControl();
        var mapTypeControl = new GMapTypeControl();
        var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5,30));
        var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5,30));
        map.addControl(mapTypeControl, topRight);
        map.addControl(largeMapControl,topLeft); 
       
        if(drpCountry.value==0 || drpRegion.value==0)
            map.setCenter(new GLatLng(30.145127,20.742188), 2); 
        ajustStayOnOneCountryLabel();

        assignSelectedCountryId();         
        callLoadMarkerFnc();     
}

//tooltip
  function showTooltip(marker) {

	tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height));
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
	
  }
      
// A function to create the marker and set up the event window

function createMarker(point,html,icontype, index, country, countryId) 
{
    var icon = gicons[icontype];
    var marker = new GMarker(point, icon);
    
    marker.dvCountryId = countryId;
    marker.dvMarkerIndex = index;  
    //tool tips
   /*   
    marker.tooltip = '<div class="tooltip">'+country+'</div>';
    tooltip.style.filter="alpha(opacity=60)";
    tooltip.style.opacity=".60";
   */
    map.addOverlay(marker);

    //tool tips
   /*   
    //  ======  The new marker "mouseover" and "mouseout" listeners  ======
    GEvent.addListener(marker,"mouseover", function() {
      showTooltip(marker);
    });
    GEvent.addListener(marker,"mouseout", function() {
	    tooltip.style.visibility="hidden"
    });
*/     
    GEvent.addListener(marker, "click", function() {        
        htxtSelectedCountryId.value = marker.dvCountryId;  
        drpCountry.selectedIndex = marker.dvMarkerIndex+1; 
        document.getElementById('dv_linktothismap').style.visibility='hidden';  
        marker.openInfoWindowHtml(html);
    });

    gmarkers[index] = marker;
    htmls[index] = html;       
    return marker;
}


function callAlert()
{        
     alert('callAlert');                              
}

// business logic functions for bp...

function requestCountryInfo()
{        
   //  alert('I am in requestCountryInfo');                              

    if (drpTopic.value >0 )
    {
    
        var qstr="?tid="+drpTopic.value;
            qstr+="&pid="+document.getElementById("ctl00_htxtSelectedTabId").value;
            url = "requestInfoFromTemp.aspx"+qstr;
     //   alert(url);
    	//make request to database ...       
        makeRequest(url);
    }
}


function makeRequest(url)
{

	try
	{
	    request = (window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject("MSXML2.XMLHTTP");   
	    sendRequest(url);

	}	
	catch (e)
	{
	    alert('Your browser does not support Business Planet web application. Please upgrade your browser to latest version. Recommended browsers are Internet Explorer, Firefox & Safari');
	}
}


function sendRequest(url)
{
    request.onreadystatechange = onResponse;
    request.open("GET", url, true);
    request.send(null);
}


function onResponse()
  {
  
  IsRequestInProgress = 1;
                           
  if(request.readyState==4)
    {
    	IsRequestInProgress = 0;
    	
    	//alert(request.responseText);
        
        if (request.responseText!='')
        {   
         //   alert('request.responseText is not null');                                       
         xmlDoc = GXml.parse(request.responseText);    
                                 
         loadMarker(); 
         //document.getElementById("htxtResponseText").value=request.responseText;                   
        }       
    }
}


function loadMarker()
{    
      
    if (document.getElementById("htxtBtnClickStatus").value==1 && IsRequestInProgress == 0)
    {
    
     if (xmlDoc!=null)
      { 
                                         
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");
              
          if(drpRegion.value >0 )
           {
            var filterIndex = 0;      
            for (var i = 0; i < markers.length; i++) 
                {
                                  
                  if (markers[i].getAttribute("regionId")==drpRegion.value)
                  {                      
                        var lat = parseFloat(markers[i].getAttribute("lat"));
                        var lng = parseFloat(markers[i].getAttribute("lng"));
                        var point = new GLatLng(lat,lng);
                        var html = GXml.value(markers[i].getElementsByTagName("popupinfo")[0]);
                                 
                        var icontype = markers[i].getAttribute("icon");
                        var country = markers[i].getAttribute("country");
                        var countryId = markers[i].getAttribute("countryId");
                        var marker = createMarker(point,html,icontype, filterIndex, country, countryId);   

                        filterIndex++;   
                          
                   }                  
                    arrCountryId[i+1] = parseInt(markers[i].getAttribute("countryId"));
                    arrCountryName[i+1] =markers[i].getAttribute("country");
                    arrRegionId[i+1] = parseInt(markers[i].getAttribute("regionId"));                                
		                         
                }                 
           } 
           else
           {
            // alert('countries');
            // alert(markers.length);
		        for (var i = 0; i < markers.length; i++) 
			    {
                    var lat = parseFloat(markers[i].getAttribute("lat"));
                    var lng = parseFloat(markers[i].getAttribute("lng"));
                    var point = new GLatLng(lat,lng);	      			      
                    var icontype = markers[i].getAttribute("icon");
                    var html = GXml.value(markers[i].getElementsByTagName("popupinfo")[0]);
                    var country =  markers[i].getAttribute("country");
                    var countryId = markers[i].getAttribute("countryId");   
                    
                 //   alert(countryId);
                        
                    marker = createMarker(point, html, icontype, i, country, countryId);    		     			                                   

                    arrCountryId[i+1] = parseInt(countryId);
                    arrCountryName[i+1] =markers[i].getAttribute("country");
                    arrRegionId[i+1] = parseInt(markers[i].getAttribute("regionId"));
			    }     
	              
           }
        //topic and legend icons loads only after icons on the map is loaded ..   
        
        changeTopic();
           
        document.getElementById("htxtBtnClickStatus").value = "";

        bptimeoff = setTimeout("setLoadingTimerOff()",1);

        markers = null;  

        loadCountries(1);  
	    //flag as markers are loaded, it should display popup for that country when apply button is clicked 
        IsMarkerLoaded = 1; 
                
        }
     } 
    
}


/*
### Topic Change from Dropdown

1. changeTopic(); 
2. requestCountryInfo()

## Region Dropdown change
1. loadCountries(0)

# Country Dropdown change
1. EnableDisablechkStayOnOneCountry()

*** Apply button click
1. callLoadMarkerFnc();

** checkbox change
1. setFlagForStayAtOneCountry()

*/

//*** Apply button click

function callLoadMarkerFnc()
{        
    //alert(htxtAppliedRegionId.value +','+drpRegion.value)
    if (drpCountry.value > 0 && IsMarkerLoaded == 1 && htxtAppliedRegionId.value == drpRegion.value)
        dispPopup();
    else
    {	   
        centerMapOnRegion();
	    map.clearOverlays();    	    
	    setLoadingTimerOn();   
	    document.getElementById("htxtBtnClickStatus").value= 1; 
	    bptimeoff = setTimeout("loadMarker()", 1); 	   
	    
    }
}

function centerMapOnRegion()
{      
     
    if (drpRegion.value>0)
    {
	    var selRegionId = drpRegion.value
	    var lat = regionLat[selRegionId];
	    var lng = regionLng[selRegionId];
	    map.setCenter(new GLatLng(lat,lng),2); 
	   
     } 
     htxtAppliedRegionId.value = drpRegion.value;
}

function setLoadingTimerOn()
{
    var mapFade = document.getElementById("map_fade");
    mapFade.style.visibility = "visible";
    var dvmsg = document.getElementById("dv_dataLoadingInfo");    
    dvmsg.style.visibility = "visible";
    
}

function setLoadingTimerOff()
{
    var mapFade = document.getElementById("map_fade");
    mapFade.style.visibility = "hidden";
    var msg = document.getElementById("dv_dataLoadingInfo");
    msg.style.visibility="hidden";

}

function dispPopup()
{  
   if (drpCountry.value > 0)
   {            
         htxtSelectedCountryId=0;
         GEvent.trigger(gmarkers[drpCountry.selectedIndex-1],"click");                                          
   }	
}


function changeTopic()
{        
    if (drpTopic.value >0 )
    {
        var strQuestion = "htxtQuestion"+drpTopic.value;
        var strLegend = "htxtLegend"+drpTopic.value;
        
        if (strQuestion!=null)
        {
            var htxtQuestion = document.getElementById(strQuestion);
            document.getElementById("dv_question").innerHTML= htxtQuestion.value;
            
           if (drpTopic.value==23 || drpTopic.value==25)    
           {
            document.getElementById("dv_legend").innerHTML= "";
           }    
           else
           { 
            var htxtLegend = document.getElementById(strLegend);
            document.getElementById("dv_legend").innerHTML= htxtLegend.value;
           }
           
            IsMarkerLoaded = 0;
            loadCountries(0);
                        
        }
        
    }
    
}    

function loadCountries(dispPopupFlag)
 {
    
    var j=1;
    
   	// clears country drpdown
   	   
       for (var k=drpCountry.length;0<=k; k--)
       {
         drpCountry.options[k]=null;
       }
       
       //loads new country list
       
       drpCountry.options[0] = new Option('--- All countries ---','0');

       if (drpRegion.value > 0)
         {         
          for (i = 1; i < arrCountryId.length; i++)
           {              
              if ( drpRegion.value == arrRegionId[i] )
               {
                 drpCountry.options[j] = new Option(arrCountryName[i], arrCountryId[i]);      
                  
                   
		            if ( (parseInt(dispPopupFlag) == 1) && (parseInt(htxtStayOnOneCountry.value)==arrCountryId[i] || parseInt(htxtSelectedCountryId.value)==arrCountryId[i]) )
			        { 				        			        	        			        
			          drpCountry.selectedIndex = j;			          			        		          
			        }
		        
                  j += 1;
                }
           }
         }
       else
        {
         for (i = 1; i < arrCountryId.length; i++)
           {
            drpCountry.options[i] = new Option(arrCountryName[i], arrCountryId[i]);
            
             if ( (parseInt(dispPopupFlag) == 1) && (parseInt(htxtStayOnOneCountry.value)==arrCountryId[i] || parseInt(htxtSelectedCountryId.value)==arrCountryId[i]) )
                { 
                  drpCountry.selectedIndex = i;
                }
              
           }
        }                   
         dispPopup();
 }

function setFlagToStayAtOneCountry()
{ 
    if (chkCtayOnOneCountry.checked==true)
    {             
        var qstr="?StayOnOneCountry="+drpCountry.value;
      
        makeRequest1("SetFlagToStayOnOneCountry.aspx"+qstr);                                
    }
    else
       {
        drpCountry.selectedIndex = 0;
        htxtStayOnOneCountry.value = "0";
        htxtSelectedCountryId.value ="0";
        var qstr="?StayOnOneCountry=0";              
        makeRequest1("SetFlagToStayOnOneCountry.aspx"+qstr);                                
       }
}

function assignSelectedCountryId()
{ 
    if(drpCountry.value>0)
    {             
       htxtSelectedCountryId.value = drpCountry.value; 
       document.getElementById('dv_linktothismap').style.visibility='hidden';
    }
                 
   if(parseInt(htxtStayOnOneCountry.value)>0)
   	{
         chkCtayOnOneCountry.checked=true;
         htxtSelectedCountryId.value = htxtStayOnOneCountry.value;
    }
   else
   	{
         chkCtayOnOneCountry.checked=false;
    }
                           
}

function getUrl()
{
    if (htxtAppliedRegionId.value=='')
        htxtAppliedRegionId.value = '0';
    if (htxtSelectedCountryId.value==0)
        htxtSelectedCountryId.value = drpCountry.value;
            
     var qstr = "p="+document.getElementById("ctl00_htxtSelectedTabId").value;
        qstr += "*t="+drpTopic.value;
        qstr +="*r="+htxtAppliedRegionId.value;
        qstr +="*c="+drpCountry.value;
        
    var url = " ";
    
    url = eval("'"+ window.location +"'");
    url = url.replace("#","");
    if(url.indexOf("?")>0)
        {
        var index = url.indexOf("?");
        url = url.substring(0, index+1);
        url +=qstr; 
        }
    else
        {
           url +="?"+qstr;            
        }
    var txt_link = document.getElementById("txt_link")
    txt_link.value = url;
}

function openClientMail()
{
    getUrl();
    var emailHref  = document.getElementById("emailHref");
    var linkUrl = "mailto:?body="+document.getElementById("txt_link").value+"&subject=Check%20out%20this%20map%20from%20World%20Bank's%20Business%20Planet";   
    location.href=linkUrl;
}

//################## Layout related functions ######################

function autoAdjustWindowsResolutions()
{
 if(navigator.userAgent.indexOf("Firefox")!=-1)
    {
    	adjustTabWidthWithSideBar = 202;
        adjustTabWidthWithoutSideBar = 4 ;  
        
        if(screen.width==1024)
        {
  	    adjustTabWidthWithSideBar = 205;
            adjustTabWidthWithoutSideBar = 7 ;         
        }
        else if(screen.width==1152)
        {
		adjustTabWidthWithSideBar = 204;
		adjustTabWidthWithoutSideBar = 6 ;  

        }
        adjustWidthWithoutSideBar = 10;
	adjustWidthWithSideBar = 206;


	adjustWidth =  "18px";

	document.getElementById("dv_main_content_inner").style.width= eval(clientWidth-adjustWidthWithSideBar)+"px";

	document.getElementById("dv_main_content_inner").style.height = eval(clientHeight-170)+"px";

	document.getElementById("map").style.height= eval(clientHeight-170)+"px";
	document.getElementById("map_fade").style.height= eval(clientHeight-195)+"px";
        document.getElementById("dv_question_section").style.height = "21px";
        document.getElementById("dv_tab_filter_section").style.width = eval(clientWidth-adjustTabWidthWithSideBar)+"px";
        
        adjustOverviewMapWidth = 120;
        adjustOverviewMapWidthWithout=120;

	document.getElementsByTagName("ul")[0].style.position = "relative";
	document.getElementsByTagName("ul")[0].style.left = "-42px";
	document.getElementsByTagName("ul")[0].style.top = "0px";        
	document.getElementsByTagName("ul")[0].style.width = "100%"; 
 
    }
    else
    {
    	adjustWidthWithoutSideBar = 23;
		adjustWidthWithSideBar = 221;
        adjustTabWidthWithSideBar = 221;
        adjustTabWidthWithoutSideBar = 21;		
        
        if(screen.width==1024)
        {
    	adjustWidthWithoutSideBar = 22;
		adjustWidthWithSideBar = 220;
        }
		else if(screen.width==1152)
        {
        adjustTabWidthWithSideBar = 220;
        adjustTabWidthWithoutSideBar = 20;		  
        }
              	        
        adjustOverviewMapWidth = 122;		
        adjustOverviewMapWidthWithout=122;
        
	adjustWidth =  "16px";
	document.getElementById("dv_main_content_inner").style.width=eval(clientWidth-adjustWidthWithSideBar)+"px";

	document.getElementById("dv_main_content_inner").style.height = eval(clientHeight-170)+"px";

	document.getElementById("map").style.height= eval(clientHeight-171)+"px";
	document.getElementById("map_fade").style.height= eval(clientHeight-191)+"px";
        document.getElementById("dv_tab_filter_section").style.width= eval(clientWidth-adjustTabWidthWithSideBar)+"px";
        

    }
   
}

function hideShowBar()
{
    var img_HideShow_Arrow = document.getElementById("img_HideShow_Arrow");
    
	if (document.getElementById("dv_side").style.visibility=="hidden")
	{
		//restoring side bar on the left ...
		
	    	img_HideShow_Arrow.src="icons/hide_arrow.png";
	    	img_HideShow_Arrow.alt ="View in full screen";

		document.getElementById("dv_side").style.visibility="visible";
		document.getElementById("dv_vertical_bar").style.left="200px";

		document.getElementById("dv_main_content_inner").style.left="214px";
		document.getElementById("dv_main_content_inner").style.width= eval(clientWidth-adjustWidthWithSideBar)+"px";

		document.getElementById("dv_tab_filter_section").style.width = eval(clientWidth-adjustTabWidthWithSideBar)+"px";
		document.getElementById("map_overview").style.left = eval(clientWidth-(adjustWidthWithSideBar+adjustOverviewMapWidth))+"px";
	}
	else
	{

		//hiding side bar and moving verticle arrow bar to left most position ...

	        img_HideShow_Arrow.src="icons/show_arrow.png";
	        img_HideShow_Arrow.alt ="View in original size";

		document.getElementById("dv_side").style.visibility="hidden";
		document.getElementById("dv_vertical_bar").style.left="0px";
		
		document.getElementById("dv_main_content_inner").style.left=adjustWidth;
    	        document.getElementById("dv_main_content_inner").style.width=eval(clientWidth-adjustWidthWithoutSideBar)+"px";
        
		document.getElementById("dv_tab_filter_section").style.width = eval(clientWidth-adjustTabWidthWithoutSideBar)+"px";

		document.getElementById("map_overview").style.left= eval(clientWidth-(adjustWidthWithoutSideBar+adjustOverviewMapWidthWithout))+"px";
        
                map.setCenter(new GLatLng(33.13755119234614,5.625), 2); 
	}

}

function adjustMapSize()
{
    if(navigator.userAgent.indexOf("Firefox")!=-1)
    {      
    	
 	 var qstring="?os=1";
        qstring+="amp;pid="+document.getElementById("ctl00_htxtSelectedTabId").value; 	 
 	    qstring+="amp;tid="+drpTopic.value; 	 
        qstring+="amp;rid="+drpRegion.value;
        qstring+="amp;cid="+drpCountry.value;        
        
        
    	location.href="default.aspx"+qstring;
    }
    else
    {
    	location.reload();
    }
}


function makeRequest1(url)
{
    request1 = (window.XMLHttpRequest)? new XMLHttpRequest(): new ActiveXObject("MSXML2.XMLHTTP");   
    sendRequest1(url);
}

function sendRequest1(url)
{
    request1.onreadystatechange = onResponse1;
    request1.open("GET", url, true);
    request1.send(null);
}
function onResponse1()
  {
  
  if(request1.readyState==4)
    {
        if (request1.responseText!='')
        {
         htxtStayOnOneCountry.value = request1.responseText;
        }       
    }
}


function popup()
{
     var w = 780;
     var h = 600;
     var winl = (screen.width-w)/2;
     var wint = (screen.height-h)/2;
   if (winl < 0) winl = 0;
   if (wint < 0) wint = 0;

   windowprops = "height="+h+",width="+w+",top="+ wint +",left="+ winl +",location=no,scrollbars=yes,menubars=no,toolbars=no,resizable=no,status=no";

	newwindow=window.open('printMap.aspx','printWin', windowprops);
	if (window.focus) {newwindow.focus()}
}



function setSelectedCountryToFirst()
{
    drpCountry.selectedIndex = 0;
     if(htxtStayOnOneCountry.value==0)
    	htxtSelectedCountryId.value = 0;
}

function ajustStayOnOneCountryLabel()
{ 
 
 if(navigator.userAgent.indexOf("Firefox")!=-1)
    {
   
        if (document.getElementById("ctl00_htxtSelectedTabId").value==5)
        {
         
          if(screen.width==1024)
            {
	            document.getElementById("dv_stayOnOneCountry").style.width="110px";
	            document.getElementById("dv_chk").style.width="15px";
	            document.getElementById("dv_chkLabel").style.width="100px";
            }
          else
            {
	            document.getElementById("dv_stayOnOneCountry").style.width="165px";
	            document.getElementById("dv_chk").style.width="15px";
	            document.getElementById("dv_chkLabel").style.width="150px";
	            document.getElementById("dv_chkLabel").style.top="3px";
	            document.getElementById("dv_chkLabel").style.left="22px";
         
            }

        }
        else 
        {
           
	            document.getElementById("dv_stayOnOneCountry").style.width="165px";
	            document.getElementById("dv_chk").style.width="15px";
	            document.getElementById("dv_chkLabel").style.width="150px";
	            document.getElementById("dv_chkLabel").style.top="3px";
	            document.getElementById("dv_chkLabel").style.left="22px";
 

        }

    }
 else
    {        
        if (document.getElementById("ctl00_htxtSelectedTabId").value==5)
        {
           
          if(screen.width==1024)
            {
	            document.getElementById("dv_stayOnOneCountry").style.width="110px";
	            document.getElementById("dv_chk").style.width="18px";
	            document.getElementById("dv_chk").style.top="2px";
	            document.getElementById("dv_chkLabel").style.top="1px";
	            document.getElementById("dv_chkLabel").style.left="22px";
            }
          else
            {
	            document.getElementById("dv_stayOnOneCountry").style.width="165px";
	            document.getElementById("dv_chk").style.width="15px";
	            document.getElementById("dv_chk").style.top="1px";
	            document.getElementById("dv_chkLabel").style.width="150px";
	            document.getElementById("dv_chkLabel").style.top="4px";
	            document.getElementById("dv_chkLabel").style.left="22px";   
            }

        }

        else
        {
         
	            document.getElementById("dv_stayOnOneCountry").style.width="165px";
	            document.getElementById("dv_chk").style.width="15px";
	            document.getElementById("dv_chk").style.top="1px";
	            document.getElementById("dv_chkLabel").style.width="150px";
	            document.getElementById("dv_chkLabel").style.top="4px";
	            document.getElementById("dv_chkLabel").style.left="22px";

        }
    }
}

function showHideAbout()
{
    var dvAbout = document.getElementById('dv_About');
    if (dvAbout.style.visibility=='visible')
        dvAbout.style.visibility='hidden';
    else
        dvAbout.style.visibility='visible';
}

function showHideLinktoMap()
{  
   
    var dvLink = document.getElementById('dv_linktothismap');
    
    if(dvLink.style.visibility == 'visible')
    {
        dvLink.style.visibility='hidden';
    }
    else
    {
        getUrl(); 
        dvLink.style.visibility='visible';
    }     
  
   
}
