// 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 reviewsCached = new Array();
var specsCached = new Array();
var pricesCached = new Array();
var clone = 0;
var selectedLangs = "";
var productInfos = new Array("tests", "prices", "specs");
var actionXPos = 0;
var actionYPos = 0;
var menuStartHeight = 0;
var menuSlideOutTime = 80;
var menuSlideInTime = 50;

var langSelectorStep = 500;
var langSelectorTimer = 0;

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

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

/**
 * Server call to retreive product data when user clicks on product in list.
 */ 
function ajaxRequestProductInfo(productId, categoryId, clickedText, whatInfo, actionObject) {
				//~ // 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;
				//~ }
  
	//~ alert(whatInfo);
				// If something else shown, hide it
				var tmpElement;
				if (whatInfo != 'specs' && (tmpElement = gEI('pD' + productId + 'specs')) != null) {
//~ alert("1" + tmpElement.tagName);				
								tmpElement.style.display = 'none';
				}
				if (whatInfo != 'reviews' && (tmpElement = gEI('pD' + productId + 'tests')) != null) {
//~ alert("1" + tmpElement.tagName);				
								tmpElement.style.display = 'none';
				}
				if (whatInfo != 'prices' && (tmpElement = gEI('pD' + productId + 'prices')) != null) {
//~ alert("1" + tmpElement.tagName);				
								tmpElement.style.display = 'none';
				}
				//~ for (infoNo = 0; infoNo < productInfos.length; infoNo++) {
								//~ if (productInfos[infoNo] != whatInfo) {
//~ //alert("jk" + thisProductDetails["shownData"]);
												//~ var shownPD = gEI('pD' + productId + productInfos[infoNo]);
												//~ if (shownPD != null) {
																//~ shownPD.style.display = 'none';
												//~ }
								//~ productSlidein('hide', productId, productInfos[infoNo]);
								//~ }
				//~ }
//  productSlidein('hide', productId, "tests");

				// Check if data already fetched and in that case, display it.
				if ((whatInfo == 'tests' && reviewsCached[productId] != null) ||
												(whatInfo == 'specs' && specsCached[productId] != null) ||
												(whatInfo == 'prices' && pricesCached[productId] != null)) {
//~ alert("2" + gEI('pD' + productId + whatInfo).tagName);				
								gEI('pD' + productId + whatInfo).style.display = 'block';
								return;
				}
				
  
				//~ // If we already have data, show it and adjust size, otherwise, start getting data
				//~ if (thisProductDetails["id"] && thisProductDetails[whatInfo] != null) {
								//~ gEI('pD' + productId + whatInfo).style.display = 'block';
								//~ productSlideout('full', productId, whatInfo);
								//~ thisProductDetails["shownData"] = whatInfo;
				//~ }
				//~ else {

				// If action demands position of cursor click, get position of clicked element and store it.
				if (whatInfo == "productPane") {
								actionXPos = getXCoordinate(actionObject);
								actionYPos = getYCoordinate(actionObject);
				}

				// Start getting data

				// Display "Fetching" icon (if needed)
				//~ document.getElementById("fD" + productId).style.display = "inline";
				gEI('more' + productId).style.cursor = 'wait';

				// Start getting data.
				var productInfoUrl = "tests.php?productId=" + productId + "&categoryId=" + categoryId + "&tLangs=" + selectedLangs;
				if (whatInfo == "productPane") {
								productInfoUrl += "&newPane=1";
				}
				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';
      gEI('more' + productId).style.cursor = 'wait';
	}
  }
  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;
				}
				productBox.style.display = 'none';
				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";
				}
				
				// Also reset the classes of the tabs opening the product data div and their container.
				var tabsBox = gEI('more'+productId);

				//~ alert(tabsBox.childNodes[0].childNodes[0].tagName);
				//~ alert(tabsBox.childNodes[0].childNodes[1].tagName);
				//~ alert(tabsBox.childNodes[0].childNodes[2].tagName);
}

/**
 * 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;
												//~ if (1) {
																//~ // If putting info into new pane, create it and go!
																
												//~ }
												//~ else {
																// Putting info in product list.
																productInfoElement = gEI("pD" + productId);
												//~ }
//      gEI('fD' + productId).style.display = 'none';
												gEI('more' + productId).style.cursor = 'pointer';
												productInfoElement.innerHTML += newProductInfo;

												// Cache retreived data.
												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);
												if (whatInfo != 'testsPane') {
																var thisProductDetails = new Array();
																var productDetailsFound = -1;
																for (var prodNo = 0; prodNo < productDetailsCachedData.length; prodNo++) {
																				if (productDetailsCachedData[prodNo]["id"] == productId) {
																								thisProductDetails = productDetailsCachedData[prodNo];
																								break;
																				}
																}
																thisProductDetails[whatInfo] = 1;
																thisProductDetails["shownData"] = whatInfo;
																thisProductDetails["id"] = productId;
																productDetailsCachedData[prodNo] = thisProductDetails;
																if (whatInfo == 'tests') {
																				// If on standalone page, we must first remove the original test list.
																				if (gEI("productBasicsTable") != null) {
																								var tmpDiv = gEI("pD" + productId + "tests");
																								if (tmpDiv != null) {
																												tmpDiv.parentNode.removeChild(tmpDiv);
																								}
																				}
																				reviewsCached[productId] = 1;
																}
																//~ else	if (whatInfo == 'testsPane') {
																				//~ // If putting into a new pane, start by creating pane
																				//~ if (gEI("productBasicsTable") != null) {
																								//~ var tmpDiv = gEI("pD" + productId + "tests");
																								//~ if (tmpDiv != null) {
																												//~ tmpDiv.parentNode.removeChild(tmpDiv);
																								//~ }
																				//~ }
																				//~ reviewsCached[productId] = 1;
																//~ }
																else if (whatInfo == 'specs') {
																				specsCached[productId] = 1;
																}
																else if (whatInfo == 'prices') {
																				pricesCached[productId] = 1;
																}

				//setTimeout("productSlideout('full', " + productId + ")", 2000);
																gEI('pD' + productId + whatInfo).style.display = 'block';
												}
												//~ if (gEI("productBasicsTable") != null) {
																//~ var pDChildren = gEI("pD" + productId + whatInfo).childNodes;
																//~ for (childNo = 0; childNo < pDChildren.length; childNo++) {
																				//~ if (pDChildren[childNo].className = "close") {
																								//~ pDChildren[childNo].style.display = 'none';
																								//~ break;
																				//~ }
																//~ }
												//~ }
												//~ 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");
								}
				}
}

/** 
  * Tracks traffic
	*/
function trackTraffic(categoryId, productId, whatInfo) {
				var staterElem = gEI('stater');
				if (staterElem != null) {
								staterElem.src = 'productTracker.php?categoryId=' + categoryId + '&productId=' + productId + '&info=' + whatInfo;
				}
				else {
								setTimeout("trackTraffic(" + categoryId + ", " + productId + ", '" + whatInfo + "')", 500);	
				}
}