/**
* Javascript for Store Locator.
*/
var storeLayer = new VEShapeLayer();
var map = null;
var dtype = "M";
var radius = "100";
var market = "ALL";
var numOfStores = 0;
var nextPage = 0;
var tableData1 = "";
var level1 = "";
var storeData = "";
var locationStart = 0;
var token = "";

if (document.cookie != "")
{
	thisCookie = document.cookie.split("; ");
	for (i=0; i<thisCookie.length; i++)
	{
		if (thisCookie[i].split("=")[0] == "clientToken")
		{
			token = thisCookie[i].split("=")[1];
		}
	}
}

window.onload = function () { GetMap(); }

// Retrieve initial map.
function GetMap()
{
	map = new VEMap('myMap');
        map.SetClientToken(token);
	map.LoadMap(null,null,null,null,null,false,null,null);
	map.AddShapeLayer(storeLayer);
	var options = new VEPrintOptions(true);
        map.SetPrintOptions(options);
}   

// Runs when Find button is clicked.
function Find()
{
    if (storeLayer.GetShapeCount()>0)
    {
        storeLayer.DeleteAllShapes();
    }
    map.SetMapStyle(VEMapStyle.Road);
    document.getElementById('lblTable1').innerHTML = "";
	map.Find(null,document.getElementById('txtStart').value,null,null,null,null,null,null,null,null,FindCallback);
}

// Retrieve store locations by passing parameteres to web service:
// @place.LatLong.Latitude  = Latitude of starting point.
// @place.LatLong.Longitude = Longitude of starting point.
// radius                   = area to search in.
// market                   = what store types to retrieve.
// dtype                    = "M" is miles, "K" is kilometers.
function FindCallback(layer,resultsArray,places,hasMore,veErrorMessage)
{
	
	var place = places[0];
	radius = document.getElementById('selRadius1').value;
	getStoreData(place.LatLong.Latitude,place.LatLong.Longitude,radius,market,dtype);
}

// Disable Enter key on aspx page to stop refresh.
function stopRKey(evt)
{ 
	var evt = (evt) ? evt : ((event) ? event : null); 
  	var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
  	if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
} 

document.onkeypress = stopRKey; 

// AJAX section
// Used to connect to the StoreLocatorWS webservice

var xmlhttp=false;

function InitXmlHttp() 
{
   // Attempt to initialize xmlhttp object
   try
   {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   }
   catch (e)
   {
      // Try to use different activex object
      try
      {
         xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (E)
      {
         xmlhttp = false;
      }
   }
   // If not initialized, create XMLHttpRequest object
   if (!xmlhttp)
   {
      xmlhttp = new XMLHttpRequest();
   }

   xmlhttp.onreadystatechange=dataHandler;
}

// Function used to call the AJAX code to get the store data from the web service
function getStoreData(lat,lon,radius,markets,dtype)
{
   InitXmlHttp();
   var msg = "http://"+ window.location.host +"/storelocatorws/locatorhandler.ashx?lat="+lat+"&long="+lon+"&radius="+radius+"&markets="+markets+"&dtype="+dtype;
   xmlhttp.open("GET", msg, true);
   xmlhttp.send(null);
}

// Handles data that is loaded from the webservice
function dataHandler()
{
   if (xmlhttp.readyState==4&& xmlhttp.status==200)   
   {
        if(xmlhttp.responseText)
        {             
            var response = xmlhttp.responseText;
            level1 = response.split(';');
            numOfStores = level1.length-1;
            tableData1 = "";
            storeData = "";
   
   	    var multiLevel = new Array(numOfStores, 15);
            var locations = new Array();
            
            for(var i=0;i<numOfStores;i++)
            {
                var level2 = level1[i].split('^');
                
                multiLevel[i] = level2;
                
		var customerNbr = multiLevel[i][0];
		var businessName = multiLevel[i][1];
		var streetAddress = multiLevel[i][2];
		var streetAddress2 = multiLevel[i][3];
		var city = multiLevel[i][4];
		var state = multiLevel[i][5];
		var zipCode = multiLevel[i][6];
		var phoneNumber = multiLevel[i][7];
		var latitude = parseFloat(multiLevel[i][8]);
		var longitude = parseFloat(multiLevel[i][9]);
		var webAddress = multiLevel[i][10];
		var marketsrvId = multiLevel[i][11];
		var marketSrvDes = multiLevel[i][12];
		var marketGrpDes = multiLevel[i][13];
		var distance = parseFloat(multiLevel[i][14]);
               
                var loc = new VELatLong(latitude,longitude);
                locations[i] = loc;
               
                var description = "";
                
                if (streetAddress != ""){
		      	description += streetAddress+"<br>";
		}

                if (streetAddress2 != ""){
                	description += streetAddress2+"<br>";
                }
                
                if (city != ""){
		       	description += city+", ";
		}
                
                if (state != ""){
		      	description += state+" ";
		}
		
		if (zipCode != ""){
		      	description += zipCode+"<br>";
		}
               
                if (phoneNumber != ""){
                	description += "("+phoneNumber.substring(0,3)+") "+phoneNumber.substring(3,6)+"-"+phoneNumber.substring(6,10);
                }
                
                var shape = new VEShape(VEShapeType.Pushpin,new VELatLong(latitude,longitude));
                var newIcon = new VECustomIconSpecification();
                var icon = "<div style='position:relative;left:-5px;top:-14px'><img src='http://"+ window.location.host +"/sylvania/images/storeicon.gif'/></div><div STYLE='position:absolute; top:-14px; left:-5px; width:25px; height:25px; font-size:12; fontWeight:bold; fontFamily:Aerial; color:blue; text-align:center;'>"+(i+1)+"</div>";
                
                newIcon.CustomHTML= icon;
                //newIcon.ImageOffset = new VEPixel(50,50);
                //newIcon.TextContent = " ";
                
                shape.SetCustomIcon(newIcon);
                shape.SetTitle(businessName);
                shape.SetDescription(description);
                storeLayer.AddShape(shape);

            }
            map.SetMapView(locations);
            storeData = multiLevel;
            buildTable(0);
        }
    }
}

// Set distance type selected.
function DistanceClicked(obj)
{
 dtype = obj.value;
}

// Set market type selected.
function MarketClicked(obj)
{
 if (obj.name == "ddCategory")
  {
    document.getElementById('ddReseller').value = "";
    if (obj.value == ""){
    	market = "ALL";
    }else{
    	market = document.getElementById('ddCategory').value;
    }
  }
  else
  {
    document.getElementById('ddCategory').value = "";
    if (obj.value == ""){
      	market = "ALL";
    }else{
      	market = document.getElementById('ddReseller').value;
    }
  }
}

// Clears initial text box value when text box is clicked in.
function clearText()
{
    if (document.getElementById('txtStart').value == "Enter zipcode or city, state")
    {
    	document.getElementById('txtStart').value = "";
    }
}

// Builds table of store data displayed to left of map.  Displays 5 stores per page.
function buildTable(index)
{
            var limit = 0;
            
            tableData1 = "<table id='tblStoreData' width='250px' style='background: #dcdcdc;'>";
            tableData1 += "<tr><td><b><u>Store</u></b></td><td align='right'><b><u>Distance</u></b></td></tr>";
            
            if ((numOfStores - index) <= 5)
            { 
            	limit = numOfStores - index;
            }
            else
            {
            	limit = 5;
            }
            
            for(var i=index;i<index+limit;i++)
            {
		
		tableData1 += "<tr><td><b><font color='blue'>" + (i+1) + "</font> <a href='javascript:void(0);' onClick='goToLocation(" + i + ");'>" + storeData[i][1] + "</a></b>";

		tableData1 += "</td><td align='right'>" + storeData[i][14] + "</td></tr>";
		
		tableData1 += "<tr><td>";

		if (storeData[i][2] != ""){
			tableData1 += storeData[i][2]+"<br>";
		}

		if (storeData[i][3] != ""){
			tableData1 += storeData[i][3]+"<br>";
		}

		if (storeData[i][4] != ""){
			tableData1 += storeData[i][4]+", ";
		}

		if (storeData[i][5] != ""){
			tableData1 += storeData[i][5]+" ";
		}

		if (storeData[i][6] != ""){
			tableData1 += storeData[i][6]+"<br>";
		}

		if (storeData[i][7] != ""){
			tableData1 += "("+storeData[i][7].substring(0,3)+") "+storeData[i][7].substring(3,6)+"-"+storeData[i][7].substring(6,10);
		}
		else
		{
			tableData1 += "(000) 000-0000";
		}

		if (storeData[i][10] != ""){
			tableData1 += "&nbsp;&nbsp;&nbsp;<a href='http://"+storeData[i][10]+"' target='_blank'>Web Site</a>";
		}

		//tableData1 += "</td></tr>";
		// MWS Comment out driving direction functionality for go-live?
		tableData1 += "</td><td align='right'><a href='javascript:void(0);' onClick='openDirections(" + i + ");'>Directions</a></td></tr>";
            }
            
            tableData1 += "</table>";
            tableData1 += "<table id='tblPaging' width='250px' style='background: #dcdcdc;'>";
            tableData1 += "<tr><td align='right' width='210px'>";
		
            if (index != 0)
            {
            	tableData1 += "<a href='javascript:void(0);' onClick='buildTable("+ (index-5) + ",storeData);'>PREV</a>";
            }
            tableData1 += "</td><td align='center' width='4px'>";
		
	    if ((index != 0) || (numOfStores > (index+limit)))
	    {
	    	tableData1 += " | ";
	    }
	    tableData1 += "</td><td align='left' width='36px'>";

	    if (numOfStores > (index+limit))
	    {
	    	tableData1 += "<a href='javascript:void(0);' onClick='buildTable(" + (index+5) + ",storeData);'>NEXT</a>";
	    }
            tableData1 += "</td></tr>";
            
            tableData1 += "</table>";
            document.getElementById('lblTable1').innerHTML = tableData1;
}

// Move view over particular store location.
function goToLocation(index)
{
	var storePoint = storeLayer.GetShapeByIndex(index);
	var storeLocation = storePoint.GetPoints()[0];
	
    	map.SetMapStyle(VEMapStyle.Road);
	map.SetCenter(storeLocation);
	setTimeout("displayInfoBox("+index+")",500);
}

function displayInfoBox(index)
{
	var storePoint = storeLayer.GetShapeByIndex(index);
	map.ShowInfoBox(storePoint);
}

function openDirections(index)
{
	var directionsURL = "http://"+ window.location.host +"/sylvania/SLdirections.aspx";
	locationStart = index;
	window.open(directionsURL,'directionsWindow','width=800px,height=600px');

}
