// This set of functions will allow a license product 
// to be added to the cart as a FOC item for downloads
// or as a cost item if a media kit is requested. 
// The license item will hold the details of the customer within it.

var sMEDIA_PACK = 'LIC/PK';
var sDOWNLOAD_LICENSE = 'LIC/DL';
var sAGENT_PREFIX = "s";

//try {
//	var ConsSrv = Components.classes['@mozilla.org/consoleservice;1'].getService(Components.interfaces.nsIConsoleService);
//  }
//catch(err) {
//    var ConsSrv = "";
//  }

function addLicense(bContainsDigital)
{
  showSiteBox(bContainsDigital);
}
  
function hideSiteBox() { 
  hideElement('licenseDetails');
  hideElement('siteBoxLayer');
  showElement('videoBox');
  showElement('demoBox');
}

function showSiteBox(bContainsDigital) { 
  hideElement('videoBox');
  hideElement('demoBox');

  if (document.getElementById('googlecart-widget-body'))
  {
    googlecartWidget.close();	  
  }
  //if (bContainsDigital)
  //{
    showElement('licenseDetails');
  //}
  //else
  //{
  //  hideElement('licenseDetails');
  //}
  showElement('siteBoxLayer');
  window.scrollTo(50,50);
  window.location.hash="licenseBoxTop"; 
}

function showElement(elementName)
{
  if (document.getElementById) 
  { // DOM3 = IE5, NS6 
    if (document.getElementById(elementName))
	{
      document.getElementById(elementName).style.visibility = 'visible'; 
      document.getElementById(elementName).style.display = 'inline'; 
    }
  } 
  else 
  { 
      if (document.layers) 
	  { // Netscape 4 
        document.hideShow.visibility = elementName; 
      } 
      else 
	  { // IE 4 
        document.all.hideShow.style.visibility = elementName; 
      } 
  } 
}

function hideElement(elementName)
{
  if (document.getElementById) { // DOM3 = IE5, NS6 
    if (document.getElementById(elementName)) 
    { 
      document.getElementById(elementName).style.visibility = 'hidden'; 
      document.getElementById(elementName).style.display = 'none'; 
    }
  } 
  else 
  { 
    if (document.layers) 
	{ // Netscape 4 
      document.hideShow.visibility = elementName; 
    } 
    else 
	{ // IE 4 
      document.all.hideShow.style.visibility = elementName; 
    } 
  } 
	
}

function googlecartOnCheckoutClick(items,form) 
{
  if ((items.length ==0))
  {
    window.alert('Your cart is empty!'); 	  
  }
  else
  {
    var bLicenseFound = false;
    var bContainsDigital = false;
    var bRemovedExtras = false;
    var sProductCode = '';
    var bBundledProduct = false;
    var bConfirmation = false;
	var sCode1 = '';
	var sCode2 = '';
    
	if (window.document.getElementById("ljConfirmation")) 
    {
      bConfirmation=(window.document.getElementById("ljConfirmation").value=='true');
    }
  
    if (items.length >0)
    {
      for (var i=0; i<items.length; i++)
      {
        if (items[i].isMarkedForRemoval()==false)
	    {
          sProductCode = items[i].getCustomAttribute('product-attr-code');
          items[i].setCustomAttribute('product-attr-agent', sAGENT_PREFIX+iLJAgentID);
		
		  if ((sProductCode==sMEDIA_PACK) || (sProductCode==sDOWNLOAD_LICENSE))
		  {
		    bLicenseFound = true;
		  }

          if (items[i].isDigital()) 
		  {
		    bContainsDigital = true;
		  }
		
          if (bIsBundledProduct(sProductCode))
		  {
		    bBundledProduct = true;
		  }
		
  	      //Do not allow for more than one copy of downloads.
		  if (items[i].getQuantity()>1)
		  {
            //window.alert(items[i].getQuantity()+' copies of "'+sProductCode+'"'); 	  
		    items[i].setQuantity(1);
 	        bRemovedExtras=true;
		  }

	      for (var j=i+1; j<items.length; j++)
	      {
			  sCode1 = (''+sProductCode).toUpperCase();
			  sCode2 = items[j].getCustomAttribute('product-attr-code');
			  sCode2 = (''+sCode2).toUpperCase();
			
			  if (sCode1 == sCode2)
			  {
			    items[j].markForRemoval();
			    bRemovedExtras=true;
			  }
		  }
        }
	  }
    }

    if (bRemovedExtras)
    {
      googlecart.expungeMarkedForRemoval();
      googlecart.saveCartAndRefreshWidget();
      window.alert(sMultipleOrder); 	  
    }
    
    // If there is no agreement, and the cart contains 
    // at least one digital download, then redirect the checkout to 
    // display the license entry box.
	  
    //if ((bLicenseFound==true) || (bBundledProduct==false))
    if ((bLicenseFound==true) || (bConfirmation==true))
    {
      return true;
    }
    else
    {
      addLicense(bBundledProduct);
    }

  }
}

function containsBothPCandMac(sCodeA, sCodeB)
{
	var a=sCodeA.toUpperCase();
	var b=sCodeB.toUpperCase();
	
	var bRetVal = ((a==b+'/MAC')
		   || (b==a+'/MAC')
		   || (a==b+'/IWR')
		   || (b==a +'/IWR')
		   || (a==b.substring(1,b.length-4) +'/IWR')
		   || (b==a.substring(1,a.length-4) +'/IWR'));
		   
    return bRetVal;
}


function checkOffers()
{
  // SPECIAL OFFER SECTION - CUSTOMISE FOR NEW OFFERS...
  var sBETT11Offer = 'BETT Show 2011: 10% Discount Offer';
  var sExciteOffer = 'Excite and Engage: 10% Discount Offer';
  var sTWitterOffer = 'Twitter: 25% Discount Offer';
  var sSSATOffer = 'SSAT: 15% Discount Offer';
  var sSSATALOffer = 'SSAT Applied Learning 2009: 10% Discount Offer';
  var sASEOffer = 'ASE East of England Area Conference: 25% Discount Offer';
  var sSIWROffer = 'Science Interactive Whiteboard Resources: 25% Discount Offer';
  var sLJUserOffer = 'LJ Website Users: 25% Discount Offer';
  var sRIAMTECOffer = 'RIAMTEC: 5% Discount Offer';
  var sBETTOffer = 'BETT 2010: 20% Discount Offer';
  var sISTEOffer = 'ISTE 2010: 20% Discount Offer';
  var sSLFOffer = 'SLF 2011: 10% Discount Offer';
  var sMultiPlatformOffer = 'Multiple Platform Discount (PC/Mac/Online)';
  var sCode1 = '';
  var sCode2 = '';
  var sCodeA = '';
  var sCodeB = '';
  
  var sOfferCode = ""+window.document.getElementById("ljOffer").value.toUpperCase();
  
  // Remove any existing offers from the cart.
  var oAllItems = googlecart.getItems();
  
  if (oAllItems.length >0)
  {
	for (var i=0; i<oAllItems.length; i++)
	{
		if ((oAllItems[i].getCustomAttribute('type') == 'offer')
			|| (oAllItems[i].getCustomAttribute('type') == 'discount'))
		{
		  oAllItems[i].markForRemoval();
		}
	}
	googlecart.expungeMarkedForRemoval();
  }
  var oDiscounts = new Array();
  
  iwrShopDebug("Checking for duplicates");

  //Find any multi-buy discounts.
  var oAllItems = googlecart.getItems();
  var iDiscountIndex = 0;
  
  if (oAllItems.length >0)
  {
	for (var i=0; i<(oAllItems.length-1); i++)
	{
       sCode1 = (''+oAllItems[i].getCustomAttribute('product-attr-code')).split(" ");
	   for (var j=i+1; j<oAllItems.length; j++)
	   {
		   sCode2 = (''+oAllItems[j].getCustomAttribute('product-attr-code')).split(" ");
		   
		   // If bundled products are used, then check the second word of the order code.
		   if (bIsBundledProduct(sCode1[0])) {sCodeA = sCode1[1];} else {sCodeA = sCode1[0];}   
		   if (bIsBundledProduct(sCode2[0])) {sCodeB = sCode2[1];} else {sCodeB = sCode2[0];}   
		   
		   if (containsBothPCandMac(sCodeA,sCodeB))
		   {
		     //Discount the lowest priced item.
			 if (oAllItems[j].getPricePerUnit() < oAllItems[i].getPricePerUnit()) {
			   iDiscountIndex = j;
			 }
		     else {
			   iDiscountIndex = i;
			 }
		     var iOfferPrice = (oAllItems[iDiscountIndex].getPricePerUnit() * -0.5);
			 
			 oDiscounts.push(googlecart.makeItem({'title':sMultiPlatformOffer,'price': iOfferPrice,'digital':true}, {'type':'discount','code':'DIS-'+oAllItems[iDiscountIndex].getCustomAttribute('product-attr-code').toUpperCase()}, 1));
			 iwrShopDebug(oDiscounts.length + " multibuy Discount(s) Added");
           }
	   }
	}
  }
 
  //Add all the discounts to the basket.
  for (var k=0; k<oDiscounts.length; k++)
  {
    googlecart.addItem(oDiscounts[k]);
  }
 
  var nTotalCost = googlecart.getSubtotal();

  if ((sOfferCode=="WEB22") || (sOfferCode=="TES22") || (sOfferCode=="TWEET22"))
  {
	  if (nTotalCost > 199.99)
	  {
		var iOfferPrice = (nTotalCost * -0.1);
		var oOfferItem = googlecart.makeItem({'title':sExciteOffer,'price': iOfferPrice},
											 {'type':'offer','code':sOfferCode}, 1);
		googlecart.addItem(oOfferItem);
	  }
	  else
	  {
		  window.alert("The offer code '"+sOfferCode+"' is only valid if you send over "+sDisplayedCurrency+"200.00");
		  return false;
	  }
  }
  else if ((sOfferCode=="SSATSC10") || (sOfferCode=="SSATSC1O") || (sOfferCode=="SSATSCIO") || (sOfferCode=="SSATSCIO"))
  {
	var iOfferPrice = (nTotalCost * -0.15);
	var oOfferItem = googlecart.makeItem({'title':sSSATOffer,'price': iOfferPrice},
											 {'type':'offer','code':sOfferCode}, 1);
	googlecart.addItem(oOfferItem);
  }
  else if ((sOfferCode=="ISTE371") || (sOfferCode=="ISTE37I") || (sOfferCode=="1STE371") || (sOfferCode=="1STE37I"))
  {
	var iOfferPrice = (nTotalCost * -0.2);
	var oOfferItem = googlecart.makeItem({'title':sISTEOffer,'price': iOfferPrice},
											 {'type':'offer','code':sOfferCode}, 1);
	googlecart.addItem(oOfferItem);
  }
  else if ((sOfferCode=="ASENOR") || (sOfferCode=="ASEN0R"))
  {
	var iOfferPrice = (nTotalCost * -0.25);
	var oOfferItem = googlecart.makeItem({'title':sASEOffer,'price': iOfferPrice},
											 {'type':'offer','code':sOfferCode}, 1);
	googlecart.addItem(oOfferItem);
  }
  else if (sOfferCode=="TWIT231")
  {
	var iOfferPrice = (nTotalCost * -0.25);
	var oOfferItem = googlecart.makeItem({'title':sTWitterOffer,'price': iOfferPrice},
											 {'type':'offer','code':sOfferCode}, 1);
	googlecart.addItem(oOfferItem);
  }
  
  else if ((sOfferCode=="SLF2011") || (sOfferCode=="SLF2OII"))
  {
	var iOfferPrice = (nTotalCost * -0.10);
	var oOfferItem = googlecart.makeItem({'title':sSLFOffer,'price': iOfferPrice},
											 {'type':'offer','code':sOfferCode}, 1);
	googlecart.addItem(oOfferItem);
  }
  
  else if ((sOfferCode=="KSBT11") || (sOfferCode=="KSBTII"))
  {
	var iOfferPrice = (nTotalCost * -0.1);
	var oOfferItem = googlecart.makeItem({'title':sBETT11Offer,'price': iOfferPrice},
											 {'type':'offer','code':sOfferCode}, 1);
	googlecart.addItem(oOfferItem);
  }
  else if ((sOfferCode=="DTB10") || (sOfferCode=="DTB1O"))
  {
	var iOfferPrice = (nTotalCost * -0.1);
	var oOfferItem = googlecart.makeItem({'title':sSSATALOffer,'price': iOfferPrice},
											 {'type':'offer','code':sOfferCode}, 1);
	googlecart.addItem(oOfferItem);
  }
  else if (sOfferCode.length >0)
  {
	  window.alert("The offer code '"+sOfferCode+"' is not valid!");
	  return false;
  }
  return true;
}

function bIsBundledProduct(sProductCode)
{
	var sShortCode = (sProductCode.slice(0,4).toUpperCase());
	return ((sShortCode=="WA20") || (sShortCode=="WA80") || (sShortCode=="WP20") || (sShortCode=="WP80"))

}

function sendCart(button)
{
  if (checkOffers())
  {
      window.document.getElementById("ljConfirmation").value="true";
	
	  googlecart.expungeMarkedForRemoval();
	  var oNewItem = googlecart.makeItemFromNode(window.document.getElementById("license"));
	  var sNewSiteName = ""+window.document.getElementById("siteName").value;
	  var sNewSiteAddress = ""+window.document.getElementById("siteAddress").value;
	  var sNewSiteContact = "";
	  var sNewSiteEmail = "";
	  var sNewTax = ""+window.document.getElementById("ljTax").value;
	  
	  if (document.getElementById("ljContactName")) 
	    sNewSiteContact=sNewSiteContact+window.document.getElementById("ljContactName").value;
	  if (document.getElementById("ljContactEmail"))
	    sNewSiteEmail=sNewSiteEmail+window.document.getElementById("ljContactEmail").value;
	  
	  document.getElementById('googlecart-checkout-config').innerHTML += document.getElementById('applyTaxRules').innerHTML;
	  //If a US tax exemption number has not been applied, then add the tax rules to the submitted form.
	  if (window.document.getElementById('chkTaxExempt'))
	  {
		  if (window.document.getElementById('chkTaxExempt').checked==false)
		  {
			  document.getElementById('googlecart-checkout-config').innerHTML += document.getElementById('USTaxRules').innerHTML;
		  }
	  }
	  oNewItem.setTitle(sLJLicenseProduct+' '+sLJMediaPack);
	  oNewItem.setCustomAttribute('product-attr-code', sMEDIA_PACK);
	  oNewItem.setCustomAttribute('product-attr-agent', sAGENT_PREFIX+iLJAgentID);
	  oNewItem.setDigital(true);
	  oNewItem.setPricePerUnit(rLJMediaPrice);
	  oNewItem.setCustomAttribute('product-attr-sitename', sNewSiteName);
	  oNewItem.setCustomAttribute('product-attr-siteAddress', sNewSiteAddress);
	  oNewItem.setCustomAttribute('product-attr-tax', sNewTax);
	  oNewItem.setCustomAttribute('product-attr-contact', sNewSiteContact);
	  oNewItem.setCustomAttribute('product-attr-email', sNewSiteEmail);
	  oNewItem.setQuantity(1);
	
	  googlecart.addItem(oNewItem);	
	  googlecart.saveCartAndRefreshWidget();
	  hideSiteBox();
	  googlecart.checkout();
  }

}

function googlecartWidgetLoaded() 
{
  var items = googlecart.getItems();
  var nTotalCost = googlecart.getSubtotal();
  
  if (items.length >0)
  {
	for (var i=0; i<items.length; i++)
	{
        sProductCode = items[i].getCustomAttribute('product-attr-code');
        items[i].setCustomAttribute('product-attr-agent', sAGENT_PREFIX+iLJAgentID);
		
		if ((sProductCode==sMEDIA_PACK) || (sProductCode==sDOWNLOAD_LICENSE))
		{
		  window.document.getElementById("siteName").value = 
		          items[i].getCustomAttribute('product-attr-sitename');
		  window.document.getElementById("siteAddress").value =	
		          items[i].getCustomAttribute('product-attr-siteAddress');
		  window.document.getElementById("ljTax").value =	
		          items[i].getCustomAttribute('product-attr-tax');
		  if (window.document.getElementById("ljContactName"))
		      window.document.getElementById("ljContactName").value =	
		          items[i].getCustomAttribute('product-attr-contact');
		  if (window.document.getElementById("ljContactEmail"))
		      window.document.getElementById("ljContactEmail").value =	
		          items[i].getCustomAttribute('product-attr-email');
		  
		  items[i].markForRemoval();
		  
		  if (window.document.getElementById('chkTaxExempt'))
	      {
			  if (window.document.getElementById('ljTax').value=='US Tax Exempt')
			  {
				window.document.getElementById('chkTaxExempt').checked=true;
			  }
			  else
			  {
				window.document.getElementById('chkTaxExempt').checked=false;
			  }
		  }
		}
		else if (items[i].getCustomAttribute('type') == 'offer')
		{
		  window.document.getElementById("ljOffer").value =	items[i].getCustomAttribute('code');
		}
		
	}
	googlecart.expungeMarkedForRemoval();
  }
  window.document.getElementById("ljConfirmation").value=='';
}

function googlecartAfterAdd(item, index)
{
  //if ((item.getQuantity()>0) || (item.isDigital()))
  //{
  //  item.setQuantity(0);
  //  googlecart.saveCartAndRefreshWidget();
	//window.alert(sMultipleOrder); 	  
	//return false
  //}
}


// The following three functions have been moved from the product ASP.
// Change made 21/06/2010 DLP.
function addToList(theForm, theProduct, theLicence, theCost){
var theForm = "frm_addToList_"+theForm;
var theMultiplier = document.forms[theForm].inp_multiplier.value;
if (theMultiplier > 1){
	theMultiplierStr = " (x "+theMultiplier+")";
}
else{
	theMultiplierStr="";
}
	if (confirm('You are about to add the following item.\n\n Title: '+theProduct+'\n Package: '+theLicence+'\n Qty: '+theMultiplier+'\n\n Continue?')){
		document.forms[theForm].submit();
	}
}

function toggleDetails(theLicId){
	var btnDetails = document.getElementById("btn_details_"+theLicId);
	var divDetails = document.getElementById("div_details_"+theLicId);
	if (divDetails.style.display == "none"){
		divDetails.style.display = "";
		btnDetails.src = "../img/btn_up.png";
		btnDetails.alt = "Hide details";
	}
	else{
		divDetails.style.display = "none";
		btnDetails.src = "../img/btn_down.png";
		btnDetails.alt = "Show details";
	}
}

iwrShopDebug = function (log_txt) {
	
	try {
	  //window.alert(log_txt);
	}
	catch(err){}
}

