// declare a global  XMLHTTP Request object
var XmlHttpObj;
var currentListname;
var selectedIndexOfCurrentList;
var discountRate = 0.05;
var browser;
var IEResponse;
var IESuccessfullyReceived;
var xmlDoc;

var listoflists=new Array();
listoflists[0]="cpuList";
listoflists[1]="mbList";
listoflists[2]="memoryList";
listoflists[3]="harddriveList";
listoflists[4]="videoList";
listoflists[5]="monitorList";
listoflists[6]="osList";
listoflists[7]="caseList";
listoflists[8]="speakersList";
listoflists[9]="opticalDriveList";
listoflists[10]="floppyList";
listoflists[11]="keyboardList";
listoflists[12]="mouseList";
listoflists[13]="networkCardList";

// create an instance of XMLHTTPRequest Object, varies with browser type, try for IE first then Mozilla
function CreateXmlHttpObj()
{
	// try creating for IE (note: we don't know the user's browser type here, just attempting IE first.)
	try
	{
		XmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
                browser =  "IE";
	}
	catch(e)
	{
		try
		{
		        XmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
                        browser="IE";
		} 
		catch(oc)
		{
			XmlHttpObj = null;
                        browser="NotIE";
		}
	}
	// if unable to create using IE specific code then try creating for Mozilla (FireFox) 
	if(!XmlHttpObj && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttpObj = new XMLHttpRequest();
	}
}

// make 2 methods.... one when the page loads, it should load all the lists, the other when one list changes, it should reload that list 

// called from onChange or onClick event of the continent dropdown list
function loadLists() 
{
            currentListname = 'alllists';
            var requestUrl = "xml_data_provider.php?category=" +encodeURIComponent('all') + "&dummy="+Math.random();
	    CreateXmlHttpObj();
	    if(XmlHttpObj)
	    {
         	     XmlHttpObj.onreadystatechange = StateChangeHandler;
                     XmlHttpObj.open("GET", requestUrl,  true);                    
		     XmlHttpObj.send(null);
	    }
}

// called from onChange or onClick event of the continent dropdown list
function ListOnChange(e)
{
      var itemList = document.getElementById(e.id);
      currentListname = e.id;
      selectedIndexOfCurrentList = itemList.selectedIndex;    
      if ( e.id == "cpuList" )
      {              
              RemoveAppropriateItemsFromMotherboardList ( true );
              var mblist = document.getElementById("mbList");   
              mblist.selectedIndex =  0; //tempcode      
              SetPriceChangeForThisList ( mblist );
      } 
      GetTotalPriceOfAllSelectedItems ( );
      UpdateAddToCartButton ( );  
      SetPriceChangeForThisList ( itemList );
}

function ReloadMotherboardList ( )
{
	var list = document.getElementById('mbList');	 
	for (var count = list.options.length-1; count >-1; count--)
	{
		list.options[count] = null;
	}
	var nodes = XmlHttpObj.responseXML.documentElement.getElementsByTagName('product');
	var priceValue;
	var textValue; 
	var optionItem;
        var categoryValue = "motherboard";
	for (var count = 0; count < nodes.length; count++)
	{
		var category = nodes[count].getAttribute("category");
                var subcategory = nodes[count].getAttribute("subcategory");               

		if ( category == "motherboard" && subcategory != "special" )
                {
			textValue = GetInnerText(nodes[count]);
			priceValue = nodes[count].getAttribute("price"); 
			weightValue = nodes[count].getAttribute("weight");
			optionItem = new Option( textValue, weightValue,  false, false);
                	if ( priceValue > 0 )
        		       	list.options[list.length] = optionItem;			
                }
        }
        SortThisListAccordingToPrice ( list ); 
	list.selectedIndex = 0;      
        GetTotalPriceOfAllSelectedItems ( );
        UpdateAddToCartButton ( ); 
        SetPriceChangeForThisList ( list );
}


// this function called when state of  XmlHttpObj changes
// we're interested in the state that indicates data has been
// received from the server
function StateChangeHandler()
{
	// state ==4 indicates receiving response data from server is completed
	if(XmlHttpObj.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttpObj.status == 200)
		{                      
                       PopulateAllLists ( XmlHttpObj.responseXML.documentElement );
		}
		else
		{
			alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
		}
	}
}

function GetWeightAllSelectedParts ( )
{
       var totalWeight = 0;
       for ( var i = 0 ; i < listoflists.length ; i++ )
       {
               var list = document.getElementById(listoflists[i]);
               if ( list.selectedIndex >= 0 )
               {
                      var optionItem = list.options[list.selectedIndex];
                      totalWeight = totalWeight + parseInt(optionItem.value);
               }
       } 
       return totalWeight;
}

function GetStringOfAllSelectedParts ( )
{
       var allParts = "";
       for ( var i = 1 ; i < listoflists.length ; i++ )
       {
               var list = document.getElementById(listoflists[i]);
               if ( list.selectedIndex >= 0 )
               {
                      var optionItem = list.options[list.selectedIndex];
                      allParts = allParts + RemovePriceFromString (optionItem.text ) + ", ";
               }
       } 
       return allParts;
}

function GetTotalPriceOfAllSelectedItems ( )
{
       var totalPrice = 0;
       for ( var i = 0 ; i < listoflists.length ; i++ )
       {
               var list = document.getElementById(listoflists[i]);
               if ( list.selectedIndex >= 0 )
               {
                      var optionItem = list.options[list.selectedIndex];
                      totalPrice = totalPrice + parseFloat( GetPriceFromItemString (optionItem.text));
               }
       } 
       totalPrice = totalPrice - (totalPrice * discountRate);
       var totalTextField = document.getElementById("total"); 
       totalTextField.value = formatCurrency(totalPrice);
       var amountfield = document.getElementById("amount");
       amountfield.value = formatCurrency(totalPrice);
}

function SetPriceChangeForAllLists ( )
{
       for ( var i = 0 ; i < listoflists.length ; i++ )
       {
               var list = document.getElementById(listoflists[i]);
               if ( list.selectedIndex >= 0 )
               { 
                         var optionItem = list.options[list.selectedIndex];
                         var selectedPrice = parseFloat( GetPriceFromItemString (optionItem.text));
                     for (var count = list.options.length-1; count >-1; count--)
	              {
                            if ( count != list.selectedIndex )
                            {                          
                                  var priceValue = parseFloat( GetPriceFromItemString (list.options[count].text));
                                   optionItem = new Option( list.options[count].text + PreparePriceChangeString ( selectedPrice , priceValue ), list.options[count].value,  false, false);
		                  list.options[count] = optionItem;                                 
                            }
                            else
                            {
                                  optionItem = list.options[list.selectedIndex];                                  
                                  optionItem = new Option( optionItem.text , optionItem.value,  false, false);
		                  list.options[list.selectedIndex] = optionItem;	              
                            }
	              }                     
               }
       }
}

function SetPriceChangeForThisList ( list )
{
               if ( list.selectedIndex >= 0 )
               { 
                         var optionItem = list.options[list.selectedIndex];
                         var selectedPrice = parseFloat( GetPriceFromItemString (optionItem.text));
                         var theSelectedIndex = list.selectedIndex;
                     for (var count = list.options.length-1; count >-1; count--)
	              {
                            if ( count != theSelectedIndex )
                            {                          
                                  var priceValue = parseFloat( GetPriceFromItemString (list.options[count].text));
                                  optionItem = new Option( RemovePriceChangePartFromString ( list.options[count].text ) + PreparePriceChangeString ( selectedPrice , priceValue ), list.options[count].value,  false, false);
		                  list.options[count] = optionItem;   
                            }
                            else
                            {                                  
                                  optionItem = new Option( RemovePriceChangePartFromString ( list.options[count].text ) , list.options[count].value,  false, false);
		                  list.options[count] = optionItem;   
                            }
	              }    
                      list.selectedIndex = theSelectedIndex;                 
               } 
}

function RemovePriceChangeFromAllSelectedItems ( )
{
      for ( var i = 0 ; i < listoflists.length ; i++ )
       {
               var list = document.getElementById(listoflists[i]);
               if ( list.selectedIndex >= 0 )
               {
                     list.options[list.selectedIndex].text = RemovePriceChangePartFromString ( list.options[list.selectedIndex].text );
               }
       }
}

function formatCurrency(num) 
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
         num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
          cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
          num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function PopulateAllLists ( node )
{
       for ( var i = 0 ; i < listoflists.length ; i++ )
       {
               var list = document.getElementById(listoflists[i]);
	       for (var count = list.options.length-1; count >-1; count--)
	       {
		       list.options[count] = null;
	       }
       }

        var nodes = node.getElementsByTagName('product');
	var idValue;
	var textValue;
	var optionItem;

	for (var count = 0; count < nodes.length; count++)
	{
		var categoryValue = nodes[count].getAttribute("category");
		var subcategoryValue = nodes[count].getAttribute("subcategory");
//alert ( categoryValue + " " + subcategoryValue + " " + count );
                var list;
                var listIsReadyToFill = false;

                if ( categoryValue == "cpu" )
                {
                      list = document.getElementById('cpuList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "motherboard" && subcategoryValue != "special" )
                {
                      list = document.getElementById('mbList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "memory" )
                {
                      list = document.getElementById('memoryList');
                      listIsReadyToFill = true;
                }
                else if ( ( categoryValue == "storage" && subcategoryValue == "IDE HD" ) || ( categoryValue == "storage" && subcategoryValue == "SATA HD" ) )
                {
                      list = document.getElementById('harddriveList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "multimedia" && subcategoryValue == "video"  )
                {
                      list = document.getElementById('videoList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "multimedia" && subcategoryValue == "monitor" )
                {
                      list = document.getElementById('monitorList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "software" && subcategoryValue == "microsoft" )
                {
                      list = document.getElementById('osList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "Other Parts" && subcategoryValue == "case" )
                {
                      list = document.getElementById('caseList');
                      listIsReadyToFill = true;
                }               
                else if ( categoryValue == "multimedia" && subcategoryValue == "audio" )
                {
                      list = document.getElementById('speakersList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "storage" && subcategoryValue == "optical" )
                {
                      list = document.getElementById('opticalDriveList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "storage" && subcategoryValue == "floppy" )
                {
                      list = document.getElementById('floppyList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "Other Parts" && subcategoryValue == "Keyboards" )
                {
                      list = document.getElementById('keyboardList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "Other Parts" && subcategoryValue == "Mice" )
                {
                      list = document.getElementById('mouseList');
                      listIsReadyToFill = true;
                }
                else if ( categoryValue == "network" && subcategoryValue == "device" )
                {
                      list = document.getElementById('networkCardList');
                      listIsReadyToFill = true;
                }
//alert ( "name: " + list.id );
                if ( listIsReadyToFill )
                {
   		        textValue = GetInnerText(nodes[count]);
		        priceValue = nodes[count].getAttribute("price");
		        weightValue = nodes[count].getAttribute("weight");
		        optionItem = new Option( textValue, weightValue,  false, false);
                        if ( priceValue > 0 )
        		        list.options[list.length] = optionItem;
                }
	}

       SortAllLists ( );
       RemoveAppropriateItemsFromMotherboardList ( false );
       GetTotalPriceOfAllSelectedItems ( );
       UpdateAddToCartButton ( );
       SetPriceChangeForAllLists ( );  
var mblist = document.getElementById("mbList");    
if (mblist.selectedIndex > 0 )
SelectFirstItemForAllLists ( );     
}

function SelectFirstItemForAllLists ( )
{
       for ( var i = 0 ; i < listoflists.length ; i++ )
       {
               var list = document.getElementById(listoflists[i]);
               list.selectedIndex = 0;              
       } 
}

function RemoveAppropriateItemsFromMotherboardList ( reloadList )
{
         if ( reloadList )
                 ReloadMotherboardList ( );
         var cpulist = document.getElementById("cpuList");
         var mblist = document.getElementById("mbList");
         var locationOfBrandText = cpulist.options[cpulist.selectedIndex].text.indexOf ( "Intel" );
         if ( locationOfBrandText == -1 )
         {
                 locationOfBrandText = cpulist.options[cpulist.selectedIndex].text.indexOf ( "AMD" );
                 if ( locationOfBrandText != -1 )
                 {
                        for (var count = mblist.options.length-1; count >-1; count--)
	                {
                              locationOfBrandText = mblist.options[count].text.indexOf ( "775" );
                              if ( locationOfBrandText == -1 )
                                     locationOfBrandText = mblist.options[count].text.indexOf ( "Duo" );		                   
                              if ( locationOfBrandText != -1 )
                                     mblist.remove(count);
	                }
                 }
         }
         else
         {
                        for (var count = mblist.options.length-1; count >-1; count--)
	                {
                              locationOfBrandText = mblist.options[count].text.indexOf ( "Sempron" );
                              if ( locationOfBrandText != -1 )
		                     mblist.remove(count);
	                }
         }       
}

function SortAllLists ( )
{
       for ( var i = 0 ; i < listoflists.length ; i++ )
       {
               var list = document.getElementById(listoflists[i]);
               SortThisListAccordingToPrice ( list );
       }        
}

function UpdateAddToCartButton ( )
{
       var namefield = document.getElementById("item_name");
       var cpulist = document.getElementById("cpuList");
       namefield.value = "ABI Computers " + RemovePriceFromString ( cpulist.options[cpulist.selectedIndex].text ) + " PC";
       var weightfield = document.getElementById("weight");
       weightfield.value = GetWeightAllSelectedParts ( );
       PlaceDetailsOfPCToOptionFields ();
}

function PlaceDetailsOfPCToOptionFields ()
{
       var addToGartButton = document.getElementById("addToGartButton");
       var stringOfSelectedParts = GetStringOfAllSelectedParts ( );       
       addToGartButton.on0.value = stringOfSelectedParts.substring ( 0, 64 );
       addToGartButton.os0.value =  stringOfSelectedParts.substring ( 64, 264 );
       addToGartButton.on1.value =  stringOfSelectedParts.substring ( 264, 331 );
       addToGartButton.os1.value =  stringOfSelectedParts.substring ( 330, 530 );
}

function PreparePriceChangeString ( selectedItemPrice , currentItemPrice )
{
        var priceChangeString = "";
        if ( selectedItemPrice <= currentItemPrice )
	        priceChangeString = " - add " + formatCurrency ( currentItemPrice - selectedItemPrice );
        else
		priceChangeString = " - substract " + formatCurrency ( selectedItemPrice - currentItemPrice );
        return priceChangeString;   
}


// populate the contents of the country dropdown list
function PopulateList(listname)
{
    	var list = document.getElementById(listname);	 
	for (var count = list.options.length-1; count >-1; count--)
	{
		list.options[count] = null;
	}
	var nodes = XmlHttpObj.responseXML.documentElement.getElementsByTagName('product');
	var priceValue;
	var textValue; 
	var optionItem;
        var categoryValue = "";
	var subcategoryValue = "";

	if ( listname == "cpuList" )
	{
		categoryValue="cpu";
	}
        else if ( listname == "mbList" )
	{
		categoryValue="motherboard";
	}
	else if ( listname == "memoryList" )
	{
		categoryValue="memory";
	}
	else if ( listname == "harddriveList" )
	{
		categoryValue="storage";
		subcategoryValue = "IDE HD";
	}
	else if ( listname == "videoList" )
	{
		categoryValue="multimedia";
		subcategoryValue = "video";
	}
	else if ( listname == "monitorList" )
	{
		categoryValue="multimedia";
		subcategoryValue = "monitor";
	}
	else if ( listname == "osList" )
	{
		categoryValue="software";
		subcategoryValue = "microsoft";
	}
	else if ( listname == "caseList" )
	{
		categoryValue="Other Parts";
		subcategoryValue = "case";
	}
	else if ( listname == "speakersList" )
	{
		categoryValue="multimedia";
		subcategoryValue = "audio";
	}
	else if ( listname == "opticalDriveList" )
	{
		categoryValue="storage";
		subcategoryValue = "optical";
	}
	else if ( listname == "floppyList" )
	{
		categoryValue="storage";
		subcategoryValue = "floppy";
	}
	else if ( listname == "keyboardList" )
	{
		categoryValue="Other Parts";
		subcategoryValue = "Keyboards";
	}
	else if ( listname == "mouseList" )
	{
		categoryValue="Other Parts";
		subcategoryValue = "Mice";
	}
	else if ( listname == "networkCardList" )
	{
		categoryValue="network";
		subcategoryValue = "device";
	}
	
	for (var count = 0; count < nodes.length; count++)
	{
		var category = nodes[count].getAttribute("category");
		var subcategory = nodes[count].getAttribute("subcategory");
                
                if ( category == categoryValue )
                {
                        if ( ( subcategoryValue == "" ) || ( subcategoryValue != "" && subcategory == subcategoryValue ) || ( subcategory == "SATA HD" && category == "storage" )  )
			{
				if ( ( category != "motherboard" )  || ( category == "motherboard" && subcategory != "special" ) )
                		{
					textValue = GetInnerText(nodes[count]);
		        		priceValue = nodes[count].getAttribute("price"); 
		        		weightValue = nodes[count].getAttribute("weight");
		        		optionItem = new Option( textValue, weightValue,  false, false);
                        		if ( priceValue > 0 )
        			        	list.options[list.length] = optionItem;
				}
			}
                }
        }
        list.selectedIndex =  selectedIndexOfCurrentList;
        SortThisListAccordingToPrice ( list );     
        if ( listname == "cpuList" )
        {              
              RemoveAppropriateItemsFromMotherboardList ( true );
              var mblist = document.getElementById("mbList");   
              mblist.selectedIndex =  0; //tempcode      
              SetPriceChangeForThisList ( mblist );
        }
        GetTotalPriceOfAllSelectedItems ( );
        UpdateAddToCartButton ( ); 
        SetPriceChangeForThisList ( list );
}

function SortThisListAccordingToPrice ( listToSort )
{
        var selectedItem;

        if ( listToSort.selectedIndex >= 0 )
               selectedItem = listToSort.options[listToSort.selectedIndex];
        var listOfTexts = new Array();
        var listOfWeights = new Array();
        for (var count = listToSort.options.length-1; count >-1; count--)
	{
                listOfTexts[listOfTexts.length] =  listToSort.options[count].text;
        }
        listOfTexts.sort( SortOptionItem );
        for (var count = 0; count < listOfTexts.length; count++)
	{
	     for (var count2 = listToSort.options.length-1; count2 >-1; count2--)
	     {
                     if ( listToSort.options[count2].text ==  listOfTexts[count] )
                     {
                            listOfWeights[listOfWeights.length] = listToSort.options[count2].value;
                     }
             }
        }

	for (var count = listToSort.options.length-1; count >-1; count--)
	{
		listToSort.options[count] = null;
	}
	for (var count = 0; count <listOfTexts.length; count++)
	{
                 var textValue = listOfTexts[count];
                 var weightValue = listOfWeights[count];
                 listToSort.options[count] =  new Option( textValue, weightValue,  false, false);
	}
        if ( selectedItem != null && currentListname != "alllists" )
        {
	     for (var count = listToSort.options.length-1; count >-1; count--)
	     {
		    if ( listToSort.options[count].text == selectedItem )
                          listToSort.selectedIndex = count;
	     }
        }
}

function SortOptionItem ( a , b )
{
      var priceOfFirst = GetPriceFromItemString ( a );
      var priceOfSecond = GetPriceFromItemString ( b );
      return priceOfFirst - priceOfSecond;
}

function GetPriceFromItemString ( itemString )
{
       var locationOfPrice = itemString.indexOf ( " ($" ) + 3;
       var endlocationOfPrice = itemString.indexOf ( ")" , locationOfPrice );  
       return itemString.substring ( locationOfPrice, endlocationOfPrice );
}

function RemovePriceChangePartFromString ( priceString )
{
        var locationOfPriceChange = priceString.indexOf ( " - add $" );
        if ( locationOfPriceChange == -1 )
             locationOfPriceChange = priceString.indexOf ( " - substract $" );
        if ( locationOfPriceChange != -1 )
             return priceString.substring ( 0, locationOfPriceChange + 1 );
        else
             return priceString;
}

function RemovePriceFromString ( text )
{
        var locationOfPrice = text.indexOf ( " ($" );
        return text.substring ( 0, locationOfPrice );
}

// returns the node text value 
function GetInnerText (node)
{
	 return (node.textContent || node.innerText || node.text) ;
}
