// Global variable needed to keep track of status changes to ajaxRequest.
var ajaxRequest;
var productSliderInitHeight = 75;
var productSliderTimer = 0;
var productSliderStep = 10;
var productInitSliderTime = 350;
var productFullSliderTime = 2250;
var productHideSliderTime = 650;
var productSliderTime = 0;
var productSliderStartTime = 0;
var productSliderCurrentHeight = 0;
var productSliderEndHeight = 0;
var productDetailsHeights = new Array();
var retreivedProductDetails = new Array();
var productDetailsCachedData = new Array();
var clone = 0;
var selectedLangs = "";
var productInfos = new Array("tests", "prices", "specs");

var menuStartHeight = 0;
var menuSlideOutTime = 80;
var menuSlideInTime = 50;

var langSelectorStep = 500;
var langSelectorTimer = 0;

/**
 * Alias for ajaxRequestProductInfo.
 */ 
function aRPI(productId, categoryId, clickedText, whatInfo) {
				// Do statistics (tell that product has been shown.)
				gEI('stater').src = 'productTracker.php?categoryId=' + categoryId + '&productId=' + productId + '&info=' + whatInfo;
				firstGuideUsage = 0;

				return ajaxRequestProductInfo(productId, categoryId, clickedText, whatInfo);
}

/**
 * Server call to retreive product data when user clicks on product in list.
 */ 
function ajaxRequestProductInfo(productId, categoryId, clickedText, whatInfo) {

				// Check if we have any data for this product!
				var thisProductDetails = new Array();
				var productDetailsFound = -1;
				for (var prodNo = 0; prodNo < productDetailsCachedData.length; prodNo++) {
								if (productDetailsCachedData[prodNo]["id"] == productId) {
												thisProductDetails = productDetailsCachedData[prodNo];
												productDetailsFound = prodNo;
								}
				}
  
				// If data already shown, ignore this call.
				if (thisProductDetails["id"] && thisProductDetails["shownData"] == whatInfo) {
								return;
				}
  
				// If something else shown, hide it
				for (infoNo = 0; infoNo < productInfos.length; infoNo++) {
								if (productInfos[infoNo] != whatInfo) {
//alert("jk" + thisProductDetails["shownData"]);
												productSlidein('hide', productId, productInfos[infoNo]);
								}
				}
//  productSlidein('hide', productId, "tests");
  
				// If we already have data, show it and adjust size, otherwise, start getting data
				if (thisProductDetails["id"] && thisProductDetails[whatInfo] != null) {
								productSlideout('full', productId, whatInfo);
								thisProductDetails["shownData"] = whatInfo;
				}
				else {
								// Display "Fetching" icon (if needed)
								document.getElementById("fD" + productId).style.display = "inline";
  
								// Start getting data.
								var productInfoUrl = "tests.php?productId=" + productId + "&categoryId=" + categoryId + "&tLangs=" + selectedLangs;
								if (whatInfo == "prices") {
												productInfoUrl = "prices.php?productId=" + productId + "&categoryId=" + categoryId;
								}
								else if (whatInfo == "specs") {
												productInfoUrl = "specs.php?productId=" + productId + "&categoryId=" + categoryId;
								}
								if (window.XMLHttpRequest) {
												ajaxRequest = new XMLHttpRequest();
												ajaxRequest.onreadystatechange = showProductData;
												ajaxRequest.open("GET", productInfoUrl, true);
												ajaxRequest.send(null);
								}
								else if (window.ActiveXObject) {
												ajaxRequest = new ActiveXObject("Microsoft.XMLHttp");
												if (ajaxRequest) {
																ajaxRequest.onreadystatechange = showProductData;
																ajaxRequest.open("GET", productInfoUrl);
																ajaxRequest.send();
												}
								}
	
								thisProductDetails["id"] = productId;
				}

				// Store updated information in productdetailslist and store productId for other uses (mailing link)
				productDetailsCachedData[productDetailsFound] = thisProductDetails;
				gEI("selProductId").value = "" + productId;
  
}

/**
 * Resizes the product details div after content has been changed.
 */
function resizeProductInfoDiv(id, whatInfo) {
  var el = gEI('pD' + id + whatInfo);
//alert(" " + el.id + " " + el.clientHeight);

  el.parentNode.style.height = "" + (el.clientHeight > 0 ? el.clientHeight : el.offsetHeight) + "px";
  productDetailsHeights['pD' + id + whatInfo] = (el.clientHeight > 0 ? el.clientHeight : el.offsetHeight);
}
 
/**
 * Slides down product section. First a bit, when called with mode = 'init' and then the full monty with mode = full.
 * When called with mode = null, it just completes the begun action.
 */
function productSlideout(mode, productId, whatInfo) {
  var productBox = gEI('pD' + productId + whatInfo);
//alert('pD' + productId + whatInfo);
//alert(productBox.tagName);
  if (mode != null && mode == 'init') {
//document.title = ".";  
    // Initialize slide
    productSliderStartTime = new Date().getTime();
    productSliderTime = productInitSliderTime;
	productSliderStartHeight = 0;
    productSliderEndHeight = productSliderInitHeight;
    productBox.style.overflow = "hidden";
    productBox.parentNode.style.overflow = "hidden";
	productBox.parentNode.style.height = "1px";
    productBox.style.display = 'block';
	if (productDetailsHeights['pD' + productId + whatInfo] == null) {
      gEI('fD' + productId + whatInfo).style.display = 'inline';
	}
  }
  else if (mode != null && mode == 'full') {
//alert("pp " + productDetailsCachedData[0]["shownData"]);
	productSliderStartTime = new Date().getTime();
    productSliderTime = productFullSliderTime;
	productSliderStartHeight = productBox.parentNode.clientHeight + 1;
//alert("pr " + "pD" + productId + whatInfo + "    " + productDetailsHeights["pD" + productId + whatInfo]);
	if (!productDetailsHeights["pD" + productId + whatInfo]) {
  	  if (isIE && parseInt(navigator.appVersion) < 7) {
        clone = productBox.cloneNode(true);
        clone.style.position = "absolute";
        clone.style.left = -50000;
        clone.style.display = "block";
        productBox.parentNode.appendChild(clone);
	    productDetailsHeights["pD" + productId + whatInfo] = clone.clientHeight;
	  }
	  else {
	    productDetailsHeights["pD" + productId + whatInfo] = productBox.clientHeight;
	  }
	}
	else {
//      productDetailsHeights["pD" + productId + whatInfo] = productBox.clientHeight;
	}  
    productSliderEndHeight = productDetailsHeights["pD" + productId + whatInfo];
//alert("ps " + productSliderEndHeight);
    productBox.parentNode.style.overflow = "hidden";
	productBox.parentNode.style.height = "" + (productSliderStartHeight + 1) + "px";
    productBox.style.display = 'block';
//document.title += "+" + productSliderStartTime+"+" + productSliderTime+"+" + productSliderStartHeight+"+" + 
//                    "+" + productSliderEndHeight+"+" + productBox.style.overflow+"+" + productBox.parentNode.style.height+"+" + productSliderCurrentHeight;
  }

  // Calculate new height
  var elapsedTime = new Date().getTime() - productSliderStartTime;
  productSliderCurrentHeight = productSliderStartHeight + Math.floor((productSliderEndHeight - productSliderStartHeight) * (elapsedTime / productSliderTime));
  productSliderCurrentHeight = productSliderCurrentHeight > productSliderEndHeight ? productSliderEndHeight : 
                                                             (productSliderCurrentHeight > productSliderStartHeight ? productSliderCurrentHeight : productSliderStartHeight + 1);

  // Resize and set new timer.
//document.title += " ch " + productSliderCurrentHeight;
  productBox.parentNode.style.height = "" + productSliderCurrentHeight + "px";
  if (productSliderCurrentHeight < productSliderEndHeight) {
    productSliderTimer = setTimeout("productSlideout(null, " + productId + ", '" + whatInfo + "')", productSliderStep);
  }
  else {
    if (clone) {
	  if (clone.parentNode) {
        clone.parentNode.removeChild(clone);
	  }
      clone = 0;
	}
    if (productBox.clientHeight > productSliderEndHeight) {
      productDetailsHeights["pD" + productId + whatInfo] = productBox.clientHeight;
	  productSliderEndHeight = productDetailsHeights["pD" + productId + whatInfo];
      productSliderTimer = setTimeout("productSlideout(null, " + productId + ", '" + whatInfo + "')", productSliderStep);
	}
	else {
      productSliderCurrentHeight = 0;
	}
  }
}

/**
 * Slides up (in) product section for the specified product.
 */
function productSlidein(mode, productId, whatInfo) {
  var productBox = gEI('pD' + productId + whatInfo);
  if (productBox == null) {
    return;
  }

  // Note to cache info that no data is shown.
  if (mode != null) {
//alert("ps " + productDetailsCachedData[0]["shownData"]);
    for (var prodNo = 0; prodNo < productDetailsCachedData.length; prodNo++) {
      if (productDetailsCachedData[prodNo]["id"] == productId) {
  	    productDetailsCachedData[prodNo]["shownData"] = null;
	    break;
	  }
	}
  }

  if (mode != null) {
//document.title = "";
    // Initialize slide
    productSliderStartTime = new Date().getTime();
    productSliderTime = productHideSliderTime;
	productSliderStartHeight = productBox.clientHeight;
    productSliderEndHeight = 0;
    productBox.style.overflow = "hidden";
    productBox.parentNode.style.overflow = "hidden";
  }

  // Calculate new height
  var elapsedTime = new Date().getTime() - productSliderStartTime;
  productSliderCurrentHeight = productSliderStartHeight + Math.floor((productSliderEndHeight - productSliderStartHeight) * (elapsedTime / productSliderTime));
  productSliderCurrentHeight = productSliderCurrentHeight < productSliderEndHeight ? productSliderEndHeight : 
                                                             (productSliderCurrentHeight < productSliderStartHeight ? productSliderCurrentHeight : productSliderStartHeight);

  // Resize and set new timer.
  productBox.parentNode.style.height = "" + productSliderCurrentHeight + "px";
  if (productSliderCurrentHeight > productSliderEndHeight) {
    productSliderTimer = setTimeout("productSlidein(null, " + productId + ", '" + whatInfo + "')", productSliderStep);
  }
  else {
    productBox.style.display = "none";
  }
}

/**
 * Updates product info box with data retreived from server.
 */
function showProductData() {
//alert("ps " + productDetailsCachedData[0]["shownData"]);

  if (ajaxRequest.readyState == 4) {
//    document.getElementById("fetchingProduct").style.display = "none";
    if (ajaxRequest.status == 200) {
      var prodIdPrefix = "Product no: ";
	  var newProductInfo = ajaxRequest.responseText.replace(/&amp;/, "&");
	  var startPos = newProductInfo.indexOf(prodIdPrefix) + prodIdPrefix.length;
	  var endPos = newProductInfo.indexOf("'", startPos);
	  var productId = newProductInfo.substring(startPos, endPos);
	  var productInfoElement = gEI("pD" + productId);
      gEI('fD' + productId).style.display = 'none';
      productInfoElement.innerHTML += newProductInfo;
	  
	  // Cache retreived data.
      var thisProductDetails = new Array();
      var productDetailsFound = -1;
      for (var prodNo = 0; prodNo < productDetailsCachedData.length; prodNo++) {
        if (productDetailsCachedData[prodNo]["id"] == productId) {
	      thisProductDetails = productDetailsCachedData[prodNo];
		  break;
	    }
      }
	  var startPos = newProductInfo.search(new RegExp("<div class.+Div")) + 12;   // Get what info has been received!
	  endPos = newProductInfo.indexOf("Div", startPos);
	  var whatInfo = newProductInfo.substring(startPos, endPos);
      thisProductDetails[whatInfo] = 1;
	  thisProductDetails["shownData"] = whatInfo;
	  thisProductDetails["id"] = productId;
	  productDetailsCachedData[prodNo] = thisProductDetails;
	  
//setTimeout("productSlideout('full', " + productId + ")", 2000);
	  productSlideout('full', productId, whatInfo);
	}
	else {
	  alert("" + lang("product", "lostServerContact"));
	} 
  }
}

function fL(obj) {
//  var curleft = 0;
//  if (obj.offsetParent) {
//    do {
//	  curleft += obj.offsetLeft;
//    } while (obj = obj.offsetParent);
//  }
  return obj.offsetLeft + (obj.offsetParent ? fL(obj.offsetParent) : 0);
}
function fT(obj) {
  var curtop = 0;
  if (obj.offsetParent) {
    do {
	  curtop += obj.offsetTop;
	} while (obj = obj.offsetParent);
  }
  return curtop;
}

/**
 * Toggles test language selection dialogue
 */
function showLangSelector(id) {
  if (isNaN(id)) {
    id = "";
  }
  clearTimeout(langSelectorTimer);
  var langSelector = gEI("langSelector" + id);
  sIEI("langSelector" + id);
  langSelector.style.position = "absolute";
  var testLangs = gEI("testLangs" + id);
//  langSelector.style.left = "" + (testLangs.offsetLeft + (isIE ? testLangs.offsetParent.offsetLeft : 0)) + "px";
//  langSelector.style.top = "" + (testLangs.offsetTop + testLangs.clientHeight) + "px"; 
  setXCoordinate(langSelector, getXCoordinate(testLangs) - getXCoordinate(gEI("overviewcontent"))); 
  setYCoordinate(langSelector, getYCoordinate(testLangs) - getYCoordinate(gEI("overviewcontent")) + testLangs.clientHeight); 
}

/**
 * Toggles test language selection dialogue
 */
function hideLangSelector(id) {
  if (isNaN(id)) {
    id = "";
  }
  hEI("langSelector" + id);
  clearTimeout(langSelectorTimer);
}
/**
 * Sets timer to hide language selection dialogue
 */
function hLS(id) {
    langSelectorTimer = setTimeout("hideLangSelector(" + id + ")", langSelectorStep);
}

/**
 * Toggles test texts of specified language.
 */
function toggleTestLang(lang, id) {
  if (isNaN(id)) {
    id = "";
  }
  var langButton = gEI("testLang" + lang + id);
  var hideLang = 1;
  // Toggle button as selected or deselected.
//  if (langButton.className == "shownLang") {
//    langButton.className = "hiddenLang";
//  }
//  else {
//    langButton.className = "shownLang";
//	hideLang = 0;
//  }
  if (langButton.checked) {
    hideLang = 0;
  }

  // Show / hide the test quotes depending on their language and if the language should be displayed or not.
//  var quotes = gEI("testQuotes").getElementsByTagName("span");
  var quotes = gEI("overviewcore").getElementsByTagName("span");
  for (var qNo = 0; qNo < quotes.length; qNo++) {
    if (quotes[qNo].className == lang) {
	  if (hideLang) {
	    quotes[qNo].style.display = "none";
	  }
	  else {
	    quotes[qNo].style.display = "inline";
	  }
	}
  }
  
  // Store the setting in case user shows more products. Then use it in server call.
  selectedLangs = selectedLangs.replace(new RegExp("." + lang), "");
  selectedLangs += (hideLang ? "-" : "+") + lang; 
  
  var divs = gEI("overviewcore").getElementsByTagName("div");
  for (var divNo = 0; divNo < divs.length; divNo++) {
    if (divs[divNo].className == "testsDiv") {
	  resizeProductInfoDiv(divs[divNo].parentNode.id.substr(2), "tests");
	}
  }
}

