var stype="";
var tinput="";

/* ===================================================
-  TODO
-  1. Old school element references need to be jQ'd
-  2.
-  3.
====================================================== */

/* ---------------------------------------------------------------
-   function getWholeSalersByStore
-
-   purpose - call out to get a list of wholeSalers for a given store
-             in xml and passes it parseWholeSalers
-
-
-   created date  2/26/2009
-   written by  Mike Kucharski
-----------------------------------------------------------------*/
function getWholeSalersByStore(storeId)
{
    var xmlHttp;
    var sUrl = "externalStoreFrontServices/rest/v1/getWholesalersByStore/" + storeId;
    $.get(sUrl, function(data) { parseWholeSalers(data); },"xml");
}


/* ---------------------------------------------------------------
-   function getWholeSalersByState
-
-   purpose - call out to service that returns a list of wholesalers
-             for a specific state in xml format and calse
-             parseWholeSalerList
-
-
-   created date  2/26/2009
-   written by  Mike Kucharski
-----------------------------------------------------------------*/
function getWholeSalerByState(stateAbbr)
{
    var xmlHttp;
    var store= getStoreIdFromUrl();
    var sUrl = "externalStoreFrontServices/rest/v1/getWholesalersByState/" + store + "/" +  stateAbbr + "/100";
    tinput = stateAbbr;
    $.get(sUrl, function(data) { parseWholeSalerList(data); }, "xml");
}


/* ---------------------------------------------------------------
-   function getWholeSalerByZip
-
-   purpose - call out to service that returns a list of wholesalers
-             for a specific zip in xml format and calse
-             parseWholeSalerList
-
-
-   created date  2/26/2009
-   written by  Mike Kucharski
-----------------------------------------------------------------*/
function getWholeSalerByZip(zipCode)
{
    var xmlHttp;
    stype = "byZip";
    tinput = zipCode;
    var store= getStoreIdFromUrl();
    var re = /^\d{5}$|[A-Z]\d[A-Z]\d[A-Z]\d$/;
    if (!re.test(zipCode)) {
	alert('Please enter a valid US ZIP or Canadian postal code.');
	return;
    }


    // Display ajax indicator
    $("div#wholesaleResult").html("<ul><li><h4>Loading ... " + zipCode + "</h4></li></ul>");

    var sUrl = "externalStoreFrontServices/rest/v1/getWholesalersByZipCode/" + store + "/" +  zipCode;
    $.get(sUrl, function(data) { parseWholeSalerList(data); }, "xml");
}




/* ---------------------------------------------------------------
-   function getWholeSalerById
-
-   purpose - call out to service that returns a wholesaler Details
-             for a specific wholesaler Id, calls parseWholeSalerInfo
-
-
-   created date  2/26/2009
-   written by  Mike Kucharski
-----------------------------------------------------------------*/
function  getWholeSalerById(wholeSalerId, wholeSalerName)
{
   var xmlHttp;
   if (wholeSalerId != -100)
   {
     $("div#mapWrap").css("display","none");
     $("div#queryResult").css("display","block");
     $("a#openIcon").css("display","none");
     $("a#closedIcon").css("display","block");
     $("div#queryResult").html("<ul><li><h4>Loading ... " + wholeSalerName + "</h4></li></ul>");
     var store= getStoreIdFromUrl();
     var sUrl = "externalStoreFrontServices/rest/v1/getWholesaler/" + store + "/" + wholeSalerId;
     $.get(sUrl, function(data) { parseWholeSalerInfo(data); },"xml");
   }
   else
   {
     alert("Please Select a WholeSaler.");
   }
}


/* ---------------------------------------------------------------
-   function parseWholeSalerList
-
-   purpose - To transform the xml wholesaler list object, into
-             the list rendered on the page.
-
-
-
-   created date  2/26/2009
-   written by  Mike Kucharski
-----------------------------------------------------------------*/
function parseWholeSalerList(wholesalers)
{
    var wholeSalerList;
    var wscount=0;
    var myaction = "";
    $('#wholesaleResult').html('');

    $(wholesalers).find('WholeSaler').each(function() {
      var wholeSalerName = $(this).children("name").text().replace("'", "");
      wscount++;
      var mapLink = ($(this).children("addressLine1").text() +  ' ' + $(this).children("addressLine2").text() +' '+ $(this).children("city").text() + ' ' + $(this).children("state").text() + ' ' + $(this).children("zipCode").text() );
      mapLink =formUrl(mapLink);
      var dist = $(this).children("distance").text();
      dist =  dist.substring(0, dist.indexOf("."));

	var result = '<ul>'
               +  '<li><h4><a href="javascript:getWholeSalerById(' + $(this).children("id").text() + ' ,\'' + wholeSalerName  + '\')">' + $(this).children("name").text();
        if (stype == 'byZip')
        {
          result = result + ' (' + dist + ' miles)';
        }
        if ($(this).children("actionUrl").text() == "")
        {
              myaction = $(this).children("webSite").text();
        }
        else
        {
             myaction = $(this).children("actionUrl").text();
        }

        result = result  +  ' </a></h4></li><li>' + $(this).children("addressLine1").text() + '</li>'
	       +  '<li>' + $(this).children("city").text() + ', ' + $(this).children("state").text() + ' ' + $(this).children("zipCode").text() + '</li>'
               +  '<li><a href="http://maps.google.com/maps?f=q&hl=en&q=' + mapLink + '">Map</a>'
	       +  '<li> <b>Phone:</b>' + $(this).children("phoneNumber").text() + '</li>'
	       +  '<li> <b>Fax:</b>' + $(this).children("faxNumber").text() + '</li>';
        if  ($(this).children("webSite").text() != '')
        {
 	    result = result   +  '<li> <b>Web:</b><a target="_blank" href="http://' + myaction + '">' + $(this).children("webSite").text() + '</a></li>';
        }
        if ($(this).children("emailAddress").text() != '')
        {
            result =result + '<li> <b>Email:</b><a href="mailto:' + $(this).children("emailAddress").text() + '" >' + $(this).children("emailAddress").text() + '</a></li>'
        }
        result = result +  '</ul>';
 	$('#wholesaleResult').append(result);

    });
    if (wscount == 0)
    {
       if (tinput == "-100")
       {
          alert("Please select a state, province, or territory.");
       }
       else
       {
		 var result1 = '<ul><li><h4>No results found for ' + tinput + '.</h4></li></ul>'
          $('#wholesaleResult').append(result1);
       }
    }
    stype = '';


}




/* ---------------------------------------------------------------
-   function parseWholeSaleInfo
-
-   purpose - to take an xml object and break it down to display
-             wholesaler details, along with inventory items at
-             that location.
-
-
-
-   created date  2/26/2009
-   written by  Mike Kucharski
-----------------------------------------------------------------*/
function parseWholeSalerInfo(wholesalers) {

   //var ws = $(wholesalers).find('wholeSaler');

   var mapLink =  ($(wholesalers).find("addressLine1").text() +  ' ' + $(wholesalers).find("addressLine2").text() +' '+ $(wholesalers).find("city").text() + ' ' + $(wholesalers).find("state").text() + ' ' + $(wholesalers).find("zipCode").text() );

   $('div#mapWrap').hide();
    var myaction = "";
    if ($(wholesalers).find("actionUrl").text() == "" )
    {
       myaction = $(wholesalers).find("webSite").text();
    }
    else
    {
       myaction = $(wholesalers).find("actionUrl").text();
    }

    var header = '<div id="wHeader">' +
		'<ul>' +
		'<li><h2>' + $(wholesalers).find("name").text() +'</h2></li>' +
                '<li>' + $(wholesalers).find("addressLine1").text() + '</li>' +
		    '<li>' + $(wholesalers).find("city").text() + ", " +
                $(wholesalers).find("state").text()  + " " + $(wholesalers).find("zipCode").text() + '</li>' +
   		    '<li>' + '<a href="http://maps.google.com/maps?f=q&hl=en&q=' + formUrl(mapLink) + '">Map</a>' +
                '<li><b>Phone:&nbsp;</b> ' + $(wholesalers).find("phoneNumber").text() + '</li>' +
                '<li><b>Fax:&nbsp;</b> ' + $(wholesalers).find("faxNumber").text() + '</li>';
     if ($(wholesalers).find("webSite").text() != '')
     {
               header = header +  '<li><b>Web:&nbsp;</b> <a target="_blank" href="http://' + myaction + '">' + $(wholesalers).find("webSite").text() + '</a></li>';
     }
     if ($(wholesalers).find("emailAddress").text() != '')
     {
            header = header + '<li> <b>Email:&nbsp;</b><a href="mailto:' + $(wholesalers).find("emailAddress").text() + '" >' + $(wholesalers).find("emailAddress").text() + '</a></li>'
     }
     header = header +
                '</ul>' +
                '</div>' +
                '<div id="wInventory">' +
		'<h2>PRODUCTS</h2>' +
                '<h4>Specification:</h4>' +
	'</div>';
   $('div#queryResult').html(header);

   var result = '<div id="wInventory">' +
		'<h2>PRODUCTS</h2>' +
                '<h4>Specification:</h4>';
   var pcount = 0;
   $(wholesalers).find("itemNumber").each(function() {
      var prodDesc = "";
      for (var prodCount=1; prodCount < products.length; prodCount++)
      {
         if ($(this).text() == products[prodCount].itemnumber)
         {
             prodDesc = products[prodCount].description;
         }
      }
      if (prodDesc != '')
      {
         //result = result + '<ul><li>' + '<b><a href="' + formProductUrl($(this).text())+ '">' + prodDesc + '</a></b><span><a href="' + $(this).text() + '.shtml">' + $(this).text() + '</a></span></li></ul>';
         result = result + '<ul><li>' + '<a href="' + $(this).text() + '.shtml"><b>' + prodDesc + '</b><span>' + $(this).text() + '</span></a></li></ul>';
         pcount++;
      }
   });
   result = result + '<h4>' + pcount + ' Products Offered </h4>';
   result = result + '</div>';
   document.getElementById("wInventory").innerHTML = result;

   $('div#queryResult').show();
}



/* ---------------------------------------------------------------
-   function parseWholeSalers
-
-   purpose - to transform an xml list of wholesalers and build a
-             wholesaler dropdown.
-
-
-
-
-   created date  2/26/2009
-   written by  Mike Kucharski
-----------------------------------------------------------------*/
function parseWholeSalers(wholesalers)
{
   var wholeSalerDropDown = document.getElementById("wholeSalerId");
   wholeSalerDropDown.options.length = 0;
   wholeSalerDropDown.options[wholeSalerDropDown.length] = new Option("Select Wholesaler", -100);
   $(wholesalers).find('WholeSaler').each(function() {
	$('#wholeSalerId').append('<option value="' + $(this).find('id').text() + '">' + $(this).find('name').text() + ' (' + $(this).find('state').text() + ')</option>');
   });


}






function mixedCase(inStr)
{
   return inStr.substring(0,1)+inStr.substring(1).toLowerCase();
}

function formProductUrl(inProduct)
{
   var thisCat = "";
   for (var cat=1; cat < categories.length; cat++)
   {
      for (var st=1; st < categories[cat].styles.length; st++)
      {
         if (categories[cat].styles[st] ==  inProduct)
         {
            thisCat = categories[cat].name;
         }
      }
   }
   var tCat = thisCat.replace(" ", "_");
   var tCat = tCat.replace(" ", "_");
   var tCat = tCat.replace("®", "");
   var tCat = tCat.replace("™", "");
   return inProduct + ".shtml?menu=" + tCat;
}


function formUrl(inStr)
{
   return(inStr.replace(/" "/g, "%20"));
}


function getStoreIdFromUrl()
{
   var store = "";
   var idx = document.URL.indexOf('?');
   var params = new Array();
   if (idx != -1)
   {
      var pairs = document.URL.substring(idx+1, document.URL.length).split('&');

      for (var i=0; i<pairs.length; i++)
      {
         nameVal = pairs[i].split('=');
         if (nameVal[0] == 'store')
         {
            store = nameVal[1].substring(0,1);
         }
      }
   }
   return store;
}




/* ---------------------------------------------------------------
-   function create XML
-
-   purpose - take the xml text data and change it into an xml
-             dom object. IE 6.X didnt support the jQuery way
-             $(x,'xml) to convert, so I am using the activex
-             control for IE
-
-
-   created date  2/26/2009
-   written by  Mike Kucharski
-----------------------------------------------------------------*/
/* XML object is now being passed, no need to createXML
function createXML(x)
{
   var xmlDoc;
   try //Internet Explorer
   {
      xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
      xmlDoc.async="false";
      xmlDoc.loadXML(x);
      myBrowser= "IE";
   }
   catch(e)
   {
      try //Firefox, Mozilla, Opera, etc.
      {
          parser=new DOMParser();
          xmlDoc=parser.parseFromString(x,"text/xml");
      }
      catch(e)
      {
         alert(e.message);
         return;
      }
   }
   return xmlDoc;
}
*/
