//###############################
//# Declarations                #
//###############################
var mblnRefreshedBaskets = false;
var mintProductBasketId  = 0;

//###############################
//# Functions                   #
//###############################
function _icb_RefreshBasketSummaryBlocks()
{
  var strHTML     = document.body.innerHTML;
  var intStartPos = 0;
  var intEndPos   = 0;
  var intBreaker  = 0;
  
  while (intStartPos > -1 && intBreaker < 1000)
  {
    intBreaker++;
    intStartPos = strHTML.indexOf('_icb_LoadBasketSummary(', intEndPos);
    if (intStartPos > -1)
    {
      intEndPos = strHTML.indexOf(')', intStartPos);
      if (intEndPos > -1)
      {      
        strBasketSummaryName = strHTML.substring(intStartPos + 24, intEndPos - 1);
        mblnRefreshedBaskets = false;
        _icb_LoadBasketSummary(strBasketSummaryName);
      }
      else
        intStartPos = -1;
    }
  }   
}
function _icb_RefreshAllBasketSummaryComponents()
{
  var arrLayers      = document.getElementsByTagName('div');
  var intLoop        = 0;
  var strId          = '';

  for (intLoop = 0; intLoop < arrLayers.length; intLoop ++)
  {
    if (arrLayers[intLoop].id.toLowerCase() == 'divbasketsummarydetails')
    {
      strId = arrLayers[intLoop].parentNode.id;
      if (strId != '' && strId != undefined && strId != null)
      {        
        mblnRefreshedBaskets = false;
        _icb_LoadBasketSummary(strId);
      }
    }
  }
}


function _icb_DelayLoadBasketSummary(pstrComponentName)
{
  if (navigator.appName.toLowerCase() == 'microsoft internet explorer')
  {
    if (  document.readyState=='complete')
      _icb_LoadBasketSummary(pstrComponentName)
    else
      setTimeout('_icb_DelayLoadBasketSummary("'+pstrComponentName+'")', 100) 
  }
  else
    _icb_LoadBasketSummary(pstrComponentName)
}

function _icb_LoadBasketSummary(pstrComponentName)
{

  var strSummaryData  = '';
  var strParams       = '';
  var objHTTPRequest  = ICB_CreateHTTPRequestObject();  //Create an ajax request object
  var strCookie       = document.cookie + ';';
  var strBasketId     = '';
  var Today     = new Date();

  //if we do not have a productbasket it then call another function which will get it from the server before we continue and then call this function with it
  if (!objHTTPRequest)
  {
    //The Ajax control could not be created so show an error in the Basket component
    _icb_LoadBasketSummaryResponse('<errorhtml>Ajax Disabled!<br /><br />Your browser settings currently have a feature called Ajax disabled.  Please enable this feature to allow this shopping basket to operate correctly.<br /><br />- <a href="">Tell me how</a> -</errorhtml>')
  }
  else
  {
    if (mintProductBasketId == 0)
      _icb_GetProductBasketId(pstrComponentName)
    else
    {    
    
      //If we have not yet gathered the basket summary do it now
      if (! mblnRefreshedBaskets)
      {
        mblnRefreshedBaskets = true;
                     
        //Send an ajax request to get the basket summary data from the server
        strParams = '_icb_BasketId=' + mintProductBasketId + '&' +
                    '_icb_ComponentName=' + pstrComponentName;                                    

        objHTTPRequest.open("GET", '/Modules/ICB/eCommerce/Scripts/BasketSummary.aspx?CS=' + Today.getSeconds() * Today.getMilliseconds() + '&' + strParams, true);
        objHTTPRequest.onreadystatechange = function(){if (objHTTPRequest.readyState==4) _icb_LoadBasketSummaryResponse (objHTTPRequest.responseText);};
        objHTTPRequest.send(null)  	
      }
    }
  }
}
function _icb_LoadBasketSummaryResponse(pstrResponse)
{

  //Declarations
  var arrLayers      = document.getElementsByTagName('div');
  var intLoop        = 0;
  var strItemsHTML   = pstrResponse;
  var strTotalHTML   = pstrResponse;
  var strErrorHTML   = pstrResponse;
  var intStartPos    = 0;
  var intEndPos      = 0;
  
  //Extract the Basket Items HTML from the Ajax Response
  if (strItemsHTML.toLowerCase().indexOf('<itemhtml>') != -1 && strItemsHTML.toLowerCase().indexOf('</itemhtml>') != -1)
  {    
    intStartPos  = strItemsHTML.toLowerCase().indexOf('<itemhtml>') + 10;
    intEndPos    = strItemsHTML.toLowerCase().indexOf('</itemhtml>');    
    strItemsHTML = strItemsHTML.substring(intStartPos, intEndPos);
  }
  else
    strItemsHTML = "";
  
  //Extract the Basket Total HTML from Ajax response
  if (strTotalHTML.toLowerCase().indexOf('<totalhtml>') != -1 && strTotalHTML.toLowerCase().indexOf('</totalhtml>') != -1)
  {
    intStartPos  = strTotalHTML.toLowerCase().indexOf('<totalhtml>') + 11;
    intEndPos    = strTotalHTML.toLowerCase().indexOf('</totalhtml>');    
    strTotalHTML = strTotalHTML.substring(intStartPos, intEndPos);
  }
  else
    strTotalHTML = "";

  //Extract any errors from Ajax response
  if (strErrorHTML.toLowerCase().indexOf('<errorhtml>') != -1 && strErrorHTML.toLowerCase().indexOf('</errorhtml>') != -1)
  {
    intStartPos  = strErrorHTML.toLowerCase().indexOf('<errorhtml>') + 11;
    intEndPos    = strErrorHTML.toLowerCase().indexOf('</errorhtml>');    
    strErrorHTML = strErrorHTML.substring(intStartPos, intEndPos);
  }
  else
    strErrorHTML = '';
    
  if (strItemsHTML == '' && strErrorHTML == '')
  {
    strItemsHTML = '<center>Your shopping basket is currently empty!</center>';
    strTotalHTML = '';
    
  }
  else if (strErrorHTML != '')
  {
    strItemsHTML = '<center>' + strErrorHTML + '</center>';
  }
    
  //Loop through all of the layers on this page and populate any that have an id of 
  //divbasketsummarydetails or divbasketsummarytotal
  for (intLoop = 0; intLoop < arrLayers.length; intLoop ++)
  {
    if (arrLayers[intLoop].id.toLowerCase() == 'divbasketsummarydetails')
    {
      //if this layer is a details layer for a basket summary component populate its content
      arrLayers[intLoop].innerHTML = strItemsHTML;
    }
    else if (arrLayers[intLoop].id.toLowerCase() == 'divbasketsummarytotal')
    {
      //if this layer is a totals layer for a basket summary component populate its content            
      arrLayers[intLoop].innerHTML = strTotalHTML;
      arrLayers[intLoop].style.display = '';
    }
  }
}
function _icb_GetProductBasketId(pstrComponentName)
{
  var strParams       = '';
  var objHTTPRequest  = ICB_CreateHTTPRequestObject();  //Create an ajax request object
  var strCookie       = document.cookie + ';';
  var strBasketId     = '';
  var Today     = new Date();
  
  //Send an ajax request to get the basket summary data from the server
  strParams = '_icb_ComponentName=' + pstrComponentName;

  objHTTPRequest.open("GET", '/Modules/ICB/eCommerce/Scripts/GetProductBasketId.aspx?CS=' + Today.getSeconds() * Today.getMilliseconds() + '&' + strParams, true);
  objHTTPRequest.onreadystatechange = function(){if (objHTTPRequest.readyState==4) _icb_GetProductBasketIdResponse (objHTTPRequest.responseText);};
  objHTTPRequest.send(null)  	

}
function _icb_GetProductBasketIdResponse(pstrResponse)
{

  //Declarations
  var strComponentName   = '';
  var intProductBasketId = 0;
  var intLoop            = 0;
  var arrLayers          = document.getElementsByTagName('div');

  if (pstrResponse.indexOf('|') != -1)
  {
    intProductBasketId = pstrResponse.substring(0, pstrResponse.indexOf('|'));
    strComponentName   = pstrResponse.substring(pstrResponse.indexOf('|') + 1);
    
    if ((! isNaN(intProductBasketId)) && (intProductBasketId > 0))
    {    
      mintProductBasketId = intProductBasketId;
      _icb_LoadBasketSummary(strComponentName);
    }
    else if (intProductBasketId == 0)
    {
      for (intLoop = 0; intLoop < arrLayers.length; intLoop ++)
      {
        if (arrLayers[intLoop].id.toLowerCase() == 'divbasketsummarydetails')
        {
          //if this layer is a details layer for a basket summary component populate its content
          arrLayers[intLoop].innerHTML = "<center>Your basket is currently empty</center>";
        }        
      }
    }
  }  
}

function _icb_RemoveBasketItems(pintBasketId, pintProductId, pintProductBasketItemId, pstrProductName)
{
  var strParams       = '';
  var objHTTPRequest  = ICB_CreateHTTPRequestObject();  //Create an ajax request object    
  var Today           = new Date();

  
  //If we have not yet gathered the basket summary do it now
  if (confirm('You are about to remove the following products from your shopping basket:\n\n' + pstrProductName + '\n\nAre you sure?'))
  {        
    //Send an ajax request to remove the selected items from the basket 
    strParams = '_icb_BasketId=' + pintBasketId + '&' +
                '_icb_ProductId=' + pintProductId + '&' +
                '_icb_ProductBasketItemId=' + pintProductBasketItemId;                                    
    //objHTTPRequest.open("POST", '/Modules/ICB/eCommerce/Scripts/RemoveFromBasket.aspx', true);
    //objHTTPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //objHTTPRequest.setRequestHeader("Content-length", strParams.length);
    //objHTTPRequest.setRequestHeader("Connection", "close");
    //objHTTPRequest.onreadystatechange = function(){if (objHTTPRequest.readyState==4) _icb_RemoveBasketItemsResponse (objHTTPRequest.responseText);};
    //objHTTPRequest.send(strParams)                            

    objHTTPRequest.open("GET", '/Modules/ICB/eCommerce/Scripts/RemoveFromBasket.aspx?CS=' + Today.getSeconds() * Today.getMilliseconds() + '&' + strParams, true);
    objHTTPRequest.onreadystatechange = function(){if (objHTTPRequest.readyState==4) _icb_RemoveBasketItemsResponse (objHTTPRequest.responseText);};
    objHTTPRequest.send(null)  	

  }
}
function _icb_RemoveBasketItemsResponse(pstrResponse)
{
  //Check to make sure that the items have been removed ok
  if (! isNaN(pstrResponse))
  {

    if (parseInt(pstrResponse) > 0)
    {
      //Reset the Refreshed flag and call a function to refresh all basket components on this page
      mblnRefreshedBaskets = false;
      _icb_RefreshAllBasketSummaryComponents();
    }
    else
      alert('We encountered a problem while trying to remove the selected items from your basket.\n\nPlease try again.')
  }
  else
    alert('We encountered a problem while trying to remove the selected items from your basket.\n\nPlease try again.')
}

function _icb_CreateHTTPRequestObject()
{
  var xmlhttp=false;
 
  /*@cc_on @*/
  /*@if (@_jscript_version >= 5)
  // JScript gives us Conditional compilation, we can cope with old IE versions.
  // and security blocked creation of the objects.
   try {
    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
   } catch (e) {
    try {
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (E) {
     xmlhttp = false;
    }
   }
  @end @*/
  
  if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	  try {
		  xmlhttp = new XMLHttpRequest();		 
		  //xmlhttp.overrideMimeType('text/xml');
	  } catch (e) {
		  xmlhttp=false;
	  }
  }
  if (!xmlhttp && window.createRequest) {
	  try {
		  xmlhttp = window.createRequest();
	  } catch (e) {
		  xmlhttp=false;
	  }
  }
  return xmlhttp;
}   

function _icb_ChangeBasketSummaryCountry(pobjList)
{
  //Declarations  
  var intCountryId    = pobjList.options[pobjList.selectedIndex].value;
  var strURL          = window.location.href;
  var strSepChar      = '?';

  strURL = strURL.replace('CountryId=', 'OldId=');
  if (strURL.indexOf('?') != -1)
    strSepChar = '&';

  if (document.getElementById('divbasketsummarycountry') != null)
    document.getElementById('divbasketsummarycountry').innerHTML = '<center>Updating Country Information<br />Please wait...</center>';

  window.location.href=strURL + strSepChar + 'CountryId=' + intCountryId;
}
