var req;
var isSubmitting = 0;

//////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//Checklista
//div med alla li's ("tabsdiv")
//alla li' mŒste ha 2 classer med suffix "Selected" och "Unselected" och innehŒlla en a-href med samma id
//som li'n fast utan suffix.
//
//fšr varje li som finns sŒ mŒste det finnas en tabell div med samma cssklassnamn som li't
//prefixet Šr tab och suffix _product
//ex. om det finns en li med klasserna kalleSelected och KalleUnSelected sŒ mŒste den ha en href med id kalle
//Tabellen fšr denna blir dŒ tabKalle_product
//////////////////////////////////////////////////////////////////////////////////////////////////////////



function activateLi(o, suffixCssSelected, suffixCssUnSelected)
{

    var oProductLayer = document.getElementById("tab" + o.id + "_product");
    ResetProductTable();
    ResetTabs(suffixCssUnSelected);
    o.parentNode.id =  o.id + suffixCssSelected;

    oProductLayer.style.display = 'block';
}

function ResetTabs(suffixCssUnSelected)
{
    var elem = document.getElementById('tabs').getElementsByTagName('li');
      for(var i = 0; i < elem.length; i++)
      {
    	  elem[i].id = elem[i].childNodes[0].id + suffixCssUnSelected;
      }
}

function ResetProductTable()
{
    var elem = document.getElementById('tabs').getElementsByTagName('li');
    
      for(var i = 0; i < elem.length; i++)
      {
            oProductLayer = document.getElementById("tab"+elem[i].childNodes[0].id + "_product");
            
            if (oProductLayer !== null)
            {
                oProductLayer.style.display = 'none';
            }else
            {
                alert(elem[i].id + "_product is no object");
            }
            
      }
}

////////////////////////////////////////////////////////////////////////////////////////////////
//
//Cookie Functions
//
//
////////////////////////////////////////////////////////////////////////////////////////////////

function SaveBasket()
{
   if (isSubmitting == 0)
   {
	   var tabs = document.getElementById("tabs");
	   var elems = tabs.getElementsByTagName("li");
	   
	
	   for (var i = 0; i < elems.length ; i++)
	   {
		  var sProduct = "tab"+elems[i].childNodes[0].id + '_product';
	      var oTable = document.getElementById(sProduct).getElementsByTagName('table')[0];
	      var oRows = oTable.getElementsByTagName('tr'); 
	
	      for (var j = 1; j < oRows.length ; j++)
	      {
	    	  var product = oRows[j].cells[1].childNodes[0].name;
	    	  var items = oRows[j].cells[1].childNodes[0].value;
	    	  
			  setTmpCookie(product, items);
	    	  
	      }
	   }
   }
}


function getCookie ( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
    return ( unescape ( results[2] ) );
  else
    return null;
}

function setTmpCookie(name, value)
{
   var expires = new Date();
   expires.setTime(expires.getTime() + (3600*1000) );
   
     
   var cookie_string = name + "=" + escape ( value );
   cookie_string += "; expires=" + expires.toGMTString();
   document.cookie = cookie_string;
   
}

function DeleteCookie(name)
{
   var expires = new Date();
   expires.setTime(expires.getTime() - 1 );
     
   var cookie_string = name + "=" + "";
   cookie_string += "; expires=" + expires.toGMTString();
   document.cookie = cookie_string;
}


////////////////////////////////////////////////////////////////////////////////////////////////
//
//Various Functions
//
//
////////////////////////////////////////////////////////////////////////////////////////////////


function Initialize()
{

    try
    {
        req = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            req = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(oc)
        {
            req=null;
        }
    }

    if(!req && typeof XMLHttpRequest!="undefined")
    {
        
        req = new XMLHttpRequest();
	}

}

////
//This function is not used by the moment.
//Saved for future use.
//
function ReadDocument()
{

  if (req.readyState == 4)
  {
     
      if (req.status == 200 || (this.status == 0 && document.location.protocol == "file:"))
      {
          if(req.responseText=="")
              alert('No response');
          else
          {
              
              if(req.responseText.length > 0)
              {
                  
                  FormatBasket(req.responseText);
              }

          }
      }
      else
      {

          //alert(req.status)
      }
  }
}
         


function GetProducts()
{
 Initialize();
 var hostname = location.hostname;
 var url = 'http://' + hostname + '/Hosting/getProducts.php';
 
 if (req!=null)
 {
    req.onreadystatechange = PopulateProducts;
    req.open("GET", url, true);
    req.setRequestHeader('Content-Type',"application/x-www-form-urlencoded; charset=utf-8");
    req.send(null);
 }
 
}


////////////////////////////////////////////////////////////////////////////////////////////////
//
//products part (products table)
//
////////////////////////////////////////////////////////////////////////////////////////////////


function PopulateProducts()
{
   
   
   if (req.readyState != 4) { return; }

   if ((req.status != 200) && (req.status != 0 && document.location.protocol != "file:")) {alert("Not Ready"); return;}
   
   if(req.responseText==""){return;}

   //Get the correct productCategory and so forth (XML)
   
   var elems = document.getElementById("tabs").getElementsByTagName("li");
   
   for (var j=0 ; j < elems.length ; j++)
   {
	  //The document fetched in xml format
      var xmldoc = req.responseXML.documentElement;
      var sProduct = elems[j].childNodes[0].id;

      var oCategory = xmldoc.getElementsByTagName(sProduct)[0];
      var oProduct = oCategory.getElementsByTagName("product");
   
      //Start populating the table
      var oDiv = document.getElementById("tab"+ sProduct +"_product");
      var oTbody = oDiv.getElementsByTagName("table")[0].getElementsByTagName("tbody")[0];

      var sProductDescription = oCategory.getElementsByTagName("description")[0].childNodes[0].nodeValue;
      oDiv.getElementsByTagName("div")[1].innerHTML = sProductDescription;
      for (var i=0; i< oProduct.length; i++)
      {

    	 var oId = oProduct.item(i).getElementsByTagName("id")[0].childNodes[0];
         var oName = oProduct.item(i).getElementsByTagName("name")[0].childNodes[0]; 
         var oPrice =  oProduct.item(i).getElementsByTagName("price")[0].childNodes[0]; 
         
         //If first row then just change the existing TR in table as it
         //serves as a template for rest of the rows.
         if (i == 0)
         {
               var oCells = oTbody.getElementsByTagName("TR")[i+1].childNodes;

               //ProductName
               oCells[0].innerHTML =  oName.nodeValue;
               
               //Price
               oCells[2].firstChild.innerHTML = oPrice.nodeValue;

               //get Input element
               oInput = oCells[1].firstChild
               oInput.name = "product_" + oId.nodeValue;
               oInput.id = oInput.name;
               
               //Get ev. value from stored cookie or set to 0
               oInput.value = parseInt(getCookie("product_" + oId.nodeValue) == null ? 0 : getCookie("product_" + oId.nodeValue));
               
               //sum row so correct css class is applied 
               SumRow(oInput, sProduct+'Selected', sProduct+'UnSelected');
   
         }
         else  //Clone the first row and append it with new attributes
         {
               
               var oRows = oTbody.getElementsByTagName("TR")[1];
               var oClonedRow = oRows.cloneNode(true);
               var oCells = oClonedRow.childNodes;
               
               //ProductName
               oCells[0].innerHTML =  oName.nodeValue;
               
               //Price
               oCells[2].firstChild.innerHTML = oPrice.nodeValue;
               oTbody.appendChild(oClonedRow);

               //Input
               oInput = oCells[1].firstChild
               oInput.name = "product_" + oId.nodeValue;
               oInput.id = oInput.name;
               
               //Get ev. value from stored cookie or set to 0
               oInput.value = parseInt(getCookie("product_" + oId.nodeValue) == null ? 0 : getCookie("product_" + oId.nodeValue));
               
               //sum row so correct css class is applied
               SumRow(oInput, sProduct+'Selected', sProduct+'UnSelected');
         }
         
      }
   }
   
   //Re-sum the basket..
   SumBasket();
}



function SumRow(o, cssClassSelected, cssClassUnSelected)
{
   
    
    if(o.value > 0)
    {

        o.parentNode.parentNode.className = cssClassSelected;
        o.parentNode.nextSibling.nextSibling.innerHTML = parseInt(o.parentNode.nextSibling.firstChild.innerHTML) * parseInt(o.value) + ':-';
        
    }else{
            
        o.parentNode.parentNode.className = cssClassUnSelected;
        o.parentNode.nextSibling.nextSibling.innerHTML = '';
    }
}


function ValidateInput(o, CssClassSelected, CssClassUnSelected)
{
    o.value = o.value.replace(/[^0-9]/g, '');

    //Sum the items. and set corresponding css class
    SumRow(o,CssClassSelected, CssClassUnSelected);
    SumBasket();

}


function SumBasket()
{
   
   var tabs = document.getElementById("tabs");
   var elems = tabs.getElementsByTagName('li');
   
   var iSumTable=0;
   for(var i = 0 ; i < elems.length;i++)
   {
      iSumTable += SumTable("tab"+elems[i].childNodes[0].id + "_product");
   }

   //Get div that holds totals
   tabTotal = document.getElementById("tabTotals");

   //Ex Vat
   tabTotal.getElementsByTagName("div")[0].innerHTML = iSumTable + ":-" ;
   
   //Vat
   var vat = iSumTable*0.12;
   tabTotal.getElementsByTagName("div")[2].innerHTML = vat.toFixed(2) + ":-";
   
   
}



function SumTable(id)
{
   var Table = document.getElementById(id).getElementsByTagName('table')[0];
   var rows = Table.getElementsByTagName('tr');
   
   var iSum=0;

   for(var i=1; i < rows.length; i++)
   {
      var iRow = rows[i].cells[3].innerHTML;

      iRow = iRow.replace(/[^0-9]/g, '');
      iSum += parseInt(iRow ? iRow : 0);

   }

   return iSum;

}






////////////////////////////////////////////////////////////////////////////////////////////////
//
//Validation part
//
//
////////////////////////////////////////////////////////////////////////////////////////////////


function isValidCompName()
{
   var companyName = document.getElementsByName("CompanyName")[0].value;
   if (companyName.length > 0)
   {
	   return true;
   }
   else
   {
	   return false;
   }
	
}

function isValidEmail()
{
	var emailPattern = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*\@([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*\.([a-zA-Z0-9_-]){2,3}$/;
	var email =  document.getElementsByName("EMail")[0].value;
	if (emailPattern.test(email))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function isValidPhone()
{
	var phone = document.getElementsByName("Phone")[0].value;
	phone = phone.replace(" ", "");
	
	var phonePattern = /^\+?[\-0-9]+$/;
	if (phonePattern.test(phone))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function isValidOrder()
{
   var orderSum = 0;
   //Get div that holds totals
   var tabTotal = document.getElementById("tabTotals");

   //Ex 
   orderSum = tabTotal.getElementsByTagName("div")[0].innerHTML;
   orderSum = orderSum.replace(/[^0-9]/g, '');
   
   return orderSum;
}

function ValidateOrder()
{

	var doSubmit = true;
	var errorMessage="<table class='ErrorTable'><thead><tr><th colspan='2'>" +
			         "F&ouml;ljande information saknas</th><tr><tbody>";
	
	if (isValidOrder() == 0)
	{
		errorMessage += "<tr><td>*</td><td>Du m&aring;ste v&auml;lja minst en produkt</td></tr>";
		doSubmit = false;
	}

	if (!isValidEmail())
	{
		errorMessage += "<tr><td>*</td><td>Ej giltig email adress.</td></tr>";
		doSubmit = false;
	}

	if (!isValidCompName())
	{
		errorMessage += "<tr><td>*</td><td>Namn/F&ouml;retag saknas</td></tr>";
		doSubmit = false;
	}

	if (isValidPhone() == 0)
	{
		errorMessage += "<tr><td>*</td><td>Ogiltigt telefonnummer.</td></tr>";
		doSubmit = false;
	}
	
	if (doSubmit == false)
	{
		errorMessage += "</tr></tbody></table>" 

		var oErrDiv = document.getElementById("ErrorMessage");
		
		if (oErrDiv)
		{
			oErrDiv.innerHTML = errorMessage;
			oErrDiv.style.display = "block";
		}
	}
	
	

	if (doSubmit == true)
	{
		ClearBasket();
	}
	
	isSubmitting = 1;
	
	return doSubmit;
}

//Deletes all cookie entries
//
function ClearBasket()
{
   var tabs = document.getElementById("tabs");
   var elems = tabs.getElementsByTagName("li");

    
   for (var i = 0; i < elems.length ; i++)
   {
    
	  var oTable = document.getElementById('tab' + elems[i].childNodes[0].id + '_product').getElementsByTagName('table')[0];
      var oRows = oTable.getElementsByTagName('tr'); 

      for (var j = 1; j < oRows.length ; j++)
      {
    	  //product
    	  var product = oRows[j].cells[1].childNodes[0].name;
    	  
    	  //Item
    	  var items = oRows[j].cells[1].childNodes[0].value;
    	  
    	  //delete cookie
		  DeleteCookie(product);
    	  
      }
   }
}




////////////////////////////////////////////////////////////////////////////////////////////////
//
//Generic onload function
//
//
////////////////////////////////////////////////////////////////////////////////////////////////





function CartInit()
{

   var tabs = document.getElementById('tabs').getElementsByTagName('li');

   for(var i=0;i< tabs.length;i++)
   {
      var sTable = 'tab' + tabs[i].childNodes[0].id + '_product';

      if(document.getElementById(sTable))
      {

      var elem = document.getElementById(sTable).getElementsByTagName('input');
        
        for(var j = 0; j < elem.length; j++)
        {
        	
          if(elem[j].value > 0)
          {
        	  var cssSelected = tabs[i].childNodes[0].id + 'Selected';
        	  var cssUnselected = tabs[i].childNodes[0].id + 'UnSelected';
              SumRow(elem[j],cssSelected, cssUnselected);
          }
          
        }
        
      }
      
   }
   
}


function genericOnLoad(call)
{
    if(typeof window.addEventListener != 'undefined')
    {
        window.addEventListener('load', call, false);
    }
    else if(typeof document.addEventListener != 'undefined')
    {
        document.addEventListener('load', call, false);
    }
    else if(typeof window.attachEvent != 'undefined')
    {
        window.attachEvent('onload', call);
    }
    else
    {
        if(typeof window.onload == 'function')
        {
            var existing = onload;
            window.onload = function()
            {
                existing();
                call;
            }
        }
        else
        {
            window.onload = call;
        }
    }
}

genericOnLoad(CartInit);





