/* site javascript file, not included in the CMS */

/* ####### Misc functions #######  */

function getObj(name) 
{
	obj = document.getElementById(name);
	return obj;
}

function getTags(name)
{
	obj = document.getElementsByTagName(name);
	return obj;
}

function newTag(name)
{
  obj = document.createElement(name);
  return obj;
}

function removeAllChildren(obj)
{
	if (obj.hasChildNodes())
	{
		while(obj.childNodes.length >= 1)
		{
			obj.removeChild(obj.firstChild);
		}
	}
}

function createEle(name)
{
	var ele = document.createElement(name);
	return ele;
}

function ie6classChange(classFrom, classTo, tag)
{
  if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.substring(22, 23) <= 6) 
  {
    var elements = document.getElementsByTagName("div");
    for (var i = 0; i < elements.length; i++) 
    {
      if (elements[i].getAttribute("class") == classFrom || elements[i].className == classFrom) 
      {
        elements[i].className = classTo;
        elements[i].setAttribute("class", classTo);
      }
    }
  }
}


var slider_slideSpeed = 20;
var slider_timer = 5;
var objectIdToSlideDown = false;
var slider_activeId = false;
var slider_slideInProgress = false;
function showHideContent(e, inputId){
    if (slider_slideInProgress) 
        return;
    slider_slideInProgress = true;
    if (!inputId) 
        inputId = this.id;
    inputId = inputId + '';
    var numericId = inputId.replace(/[^0-9]/g, '');
    var answerDiv = document.getElementById('slider_a' + numericId);
    objectIdToSlideDown = false;
    if (!answerDiv.style.display || answerDiv.style.display == 'none') {
        if (slider_activeId && slider_activeId != numericId) {
            objectIdToSlideDown = numericId;
            slideContent(slider_activeId, (slider_slideSpeed * -1));
        }
        else {
            answerDiv.style.display = 'block';
            answerDiv.style.visibility = 'visible';
            slideContent(numericId, slider_slideSpeed);
        }
    }
    else {
        slideContent(numericId, (slider_slideSpeed * -1));
        slider_activeId = false;
    }
}

function slideContent(inputId, direction){
    var obj = document.getElementById('slider_a' + inputId);
    var contentObj = document.getElementById('slider_ac' + inputId);
    height = obj.clientHeight;
    if (height == 0) 
        height = obj.offsetHeight;
    height = height + direction;
    rerunFunction = true;
    if (height > contentObj.offsetHeight) {
        height = contentObj.offsetHeight;
        rerunFunction = false;
    }
    if (height <= 1) {
        height = 1;
        rerunFunction = false;
    }
    obj.style.height = height + 'px';
    var topPos = height - contentObj.offsetHeight;
    if (topPos > 0) 
        topPos = 0;
    contentObj.style.top = topPos + 'px';
    if (rerunFunction) {
        setTimeout('slideContent(' + inputId + ',' + direction + ')', slider_timer);
    }
    else {
        if (height <= 1) {
            obj.style.display = 'none';
            if (objectIdToSlideDown && objectIdToSlideDown != inputId) {
                document.getElementById('slider_a' + objectIdToSlideDown).style.display = 'block';
                document.getElementById('slider_a' + objectIdToSlideDown).style.visibility = 'visible';
                slideContent(objectIdToSlideDown, slider_slideSpeed);
            }
            else {
                slider_slideInProgress = false;
            }
        }
        else {
            slider_activeId = inputId;
            slider_slideInProgress = false;
        }
    }
}

function initShowHideDivs(){
    var divs = document.getElementsByTagName("div");
    var totalDivs = divs.length;
    var divCounter = 1;
    for (var x = 0; x < totalDivs; x++) {
        if (divs[x].className == 'scroller_title_bar') {
            divs[x].onclick = showHideContent;
            divs[x].id = 'slider_q' + divCounter;
            var answer = divs[x].nextSibling;
            while (answer && answer.tagName != 'DIV') {
                answer = answer.nextSibling;
            }
            answer.id = 'slider_a' + divCounter;
            contentDiv = answer.getElementsByTagName('DIV')[0];
            contentDiv.style.top = 0 - contentDiv.offsetHeight + 'px';
            contentDiv.className = 'scroller_wrapper';
            contentDiv.id = 'slider_ac' + divCounter;
            answer.style.display = 'none';
            answer.style.height = '1px';
            divCounter++;
        }
    }
}



function populateCategory(industryObj)
{
	var dateObj = new Date();
	var timestamp = dateObj.getTime();
	var industryId = industryObj.value;
	var categorySelect = getObj("search_category_id");
	var xmlHttp = createXMLHttpRequest();
	xmlHttp.open("GET", "/ajax/findCategories.php?time="+timestamp+"&industry_id="+industryId, true);
	xmlHttp.onreadystatechange = function()
	{
 		if(xmlHttp.readyState == 4)
		{
 	   	if (xmlHttp.responseText != "")
			{
				// lets remove all the children
				removeAllChildren(categorySelect);
				var results = xmlHttp.responseText.split("|");
				var option = createEle("option");
				option.value = "_all_";
				option.innerHTML = "All Categories";
				categorySelect.appendChild(option);				
				populateSubCategory(option)
				for (var x=0; x < results.length; x++)
				{
					var details= results[x].split(":");
					var catId = details[0];
					var catName = details[1];
					var option = createEle("option");
					option.value = catId;
					option.innerHTML = catName;
					categorySelect.appendChild(option);
				}
			} else
			{ 
				// we've not got any matches so lets remove all the child elements
				removeAllChildren(categorySelect);
				var option = createEle("option");
				option.value = "_all_";
				option.innerHTML = "All Categories";
				categorySelect.appendChild(option);
				populateSubCategory(option)
			}
	  }	
	}
  xmlHttp.send(null);	
}

function populateSubCategory(categoryObj)
{
	var dateObj = new Date();
	var timestamp = dateObj.getTime();
	var categoryId = categoryObj.value;
	var subCategorySelect = getObj("search_sub_category_id");
	var xmlHttp = createXMLHttpRequest();
	xmlHttp.open("GET", "/ajax/findSubCategories.php?time="+timestamp+"&category_id="+categoryId, true);
	xmlHttp.onreadystatechange = function()
	{
 		if(xmlHttp.readyState == 4)
		{
 	   	if (xmlHttp.responseText != "")
			{
				// lets remove all the children
				removeAllChildren(subCategorySelect);
				var results = xmlHttp.responseText.split("|");
				var option = createEle("option");
				option.value = "_all_";
				option.innerHTML = "All Sub Categories";
				subCategorySelect.appendChild(option);
				for (var x=0; x < results.length; x++)
				{
					var details= results[x].split(":");
					var catId = details[0];
					var catName = details[1];
					var option = createEle("option");
					option.value = catId;
					option.innerHTML = catName;
					subCategorySelect.appendChild(option);
				}
			} else
			{ 
				// we've not got any matches so lets remove all the child elements
				removeAllChildren(subCategorySelect); 
				var option = createEle("option");
				option.value = "_all_";
				option.innerHTML = "All Sub Categories";
				subCategorySelect.appendChild(option);
			}
	  }	
	}
  xmlHttp.send(null);	
}


function trackExternalClick(type, product_id, supplier_id, hash)
{
	var dateObj = new Date();
	var timestamp = dateObj.getTime();
	var xmlHttp = createXMLHttpRequest();
	xmlHttp.open("GET", "/ajax/externalClick.php?time="+timestamp+"&type="+type+"&product_id="+product_id+"&supplier_id="+supplier_id+"&hash="+hash, true);
	xmlHttp.onreadystatechange = function()
	{
 		if(xmlHttp.readyState == 4)
		{
	 	   	if (xmlHttp.responseText != "")
	 	   	{	
	 	   	}
		}
	}
 	   	
 	xmlHttp.send(null);	
}


function createXMLHttpRequest() 
{
		if (typeof XMLHttpRequest != "undefined") 
		{
        return new XMLHttpRequest();
    } else if (typeof ActiveXObject != "undefined") 
		{
        return new ActiveXObject("Microsoft.XMLHTTP");
    } else 
		{
        throw new Error("XMLHttpRequest not supported");
    }
}


function highlightMenu()
{
  var aEles = getTags("a");
  for (var x = 0; x < aEles.length; x++)
  {
    var hrefElements = aEles[x].href.split('.');
    if (aEles[x].className == "menu_link" && window.location.href.indexOf("."+hrefElements[1]) != -1)
    {
      aEles[x].style.color = '#2874B4';
      aEles[x].style.fontWeight = 'bold';

      var ids = aEles[x].parentNode.parentNode.id.split("list_");
      showHideContent(false, ids[1]);
      
      var wrapper = getObj("item_"+ids[1])
      wrapper.style.backgroundImage = "url(/images/menu_bg5.gif)";
    }
  }
}


function searchShowHide(obj)
{
  // scroller_content_search
  var searchEle = getObj('search_content_box');
  if (searchEle.style.display == 'none' || searchEle.style.display == '')
  {
    searchEle.style.display = "block";
  } else
  {
    searchEle.style.display = "none";  
  }
}

function openExternalWindow(object){
    window.open(object.href, '', 'scrollbars=yes,menubar=yes,height=600,width=800,resizable=yes,toolbar=yes,location=yes,status=yes');
}

function loadBookmarker()
{
	document.write('<script type="text/javascript" src="/script/add_bookmark.js"><\/script>');
}


function initTopMenuHover()
{
  var elements = getTags("div");
  for (var x = 0; x < elements.length; x++)
  {
    if (elements[x].className == "top_menu_item")
    {
			elements[x].onmouseover = function()
			{
				menuHoverAction(this);
			}
			elements[x].onmouseout = function()
			{
				menuHoverAction(this);
			}
    }
  }
}

function menuHoverAction(obj)
{
  if (obj.className == "top_menu_item")
  {
    obj.className = "top_menu_item_hover";  
  } else if (obj.className == "top_menu_item_hover")
  {
    obj.className = "top_menu_item";
  }
}

/* ####### DOM alterations, performed after window load ####### */

var urlAddress;

function applyDOMAlterations() 
{
	var hrefItems = window.location.href.split("/");
  urlAddress = "http://" + hrefItems[2];
	menuItem = hrefItems[4];
	sectionItem = hrefItems[5];
  
  ie6classChange('scroller_title_bar', 'title_bar', 'div');  
  initShowHideDivs();
	//initSearchShowHideDivs();
  highlightMenu();
  initTopMenuHover();  
}


function headerExec()
{
	loadBookmarker();
}

// this runs in the HTML header
headerExec();

window.onload = applyDOMAlterations;
