var currentOpen = '';
var searchParamCount = 0;
var partcode = '';
var manufacturer = '';
var scope = '';
var incident_type = '';
var pagesize = 0;
var pagestart = 0;
var selectedSmallTextBar = '';
var selectedTab = '';
var selectedOpenDiv = '';
var search_type = '';
var selectedForumMenu = '';
var openMenu = '';
var openParent = 0;
var openForum = 0;
var keepMenusOpen = false;
var search_public = false;
var the_partcode = '';

var selectedLeftTab = '';
var selectedLeftDiv = '';

var searchingCompanies = false;

// graph display variables
var graphType = '';
var graphQuantity = 0;
var graphPeriod = '';
var selectedGraphType = '';
var selectedGraphQuantity = '';
var selectedGraphPeriod = '';


function checkPartCode()
{
	var a = $F('pc');
	var l = a.length;
	
	for(x=0;x<l;x++)
	{
		var char = a.charAt(x);
		var reg = /(\w|\-|\.|\,|\/|\d)/;
		if (!reg.test(char))
		{
			alert("Please remove '" + char + "' from your search");
			return false;
		}
	}

	if (a.length == 0)
	{
		alert("You need to enter a partcode");
		return false;
	}
	else if (a.length < 4)
	{
		alert("You need to search for a longer partcode");
		return false;
	}
	else
	{
		//document.partsearch_form.submit();
		return true;
	}
}

function toggleLoginForm()
{
	Element.toggle('dashboard');
	Element.toggle('loginform');
}

function hideSummary()
{
	$('summary_viewer').hide();
	Effect.Fade('dashboard', {duration:0.2});
}

function placeViewer(id)
{
	/*var a = $(id);
	var top = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
	var bottom = 0;

	var divTop = top + 20;
	
	a.style.top = divTop + 'px';

	if (top > 0)
	{
		bottom = 20 - (top);
	}
	else
	{
		bottom = 20;
	}
	
	a.style.bottom = bottom + 'px';*/
	
	Effect.Appear(id, {duration:.5});
	Effect.Appear('dashboard', {duration:0.2, to:0.6});
}


function togglePhotoVisibility(link, id, visible)
{
    var visible = (visible == 1 ? 0 : 1);
    var newClick = 'togglePhotoVisibility(this,' + id + ',' + visible + ')';
    var newSrc = 'images/' + ( visible == 0 ? 'switch_off.png' : 'switch_on.png');
    var url = 'includes/setPhotoVisible.php?p=' + id + '&v=' + visible;
    
    link.setAttribute('onclick', newClick);
    $('img' + id).src = newSrc;
    new Ajax.Request(url, {});
}

function formatCurrency(num) 
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function buildSearchString()
{
    var empty = true;
    var vars = '';
      
    if ($F('searchbox') != '')
    {
    	vars = 'partcode=' + $F('searchbox');
    }
    
    // add future variables as needed
    
    return vars;
}

function setStart(num)
{
    pagestart = num;
	showFullSearchResults(the_partcode);
}

function checkSavedSearches()
{
	if ($('saved_searches').innerHTML != '')
	{
		$('saved').show();
	}
	else
	{
		$('saved').hide();
	}
}

function getSavedSearches()
{
    new Ajax.Updater('searches', '/includes/getSavedSearches.php', { onComplete:checkSavedSearches });
}

function saveSearch()
{
    var vars = buildSearchString();
    
    new Ajax.Request(
        '/includes/save_search.php?' + vars,
        {
            onComplete:handleSearchSaved
        }
    );
}

function handleSearchSaved()
{
	Effect.Appear('search_status');
	$('search_status').update('Search Saved');
	setTimeout("Effect.Fade('search_status')",5000);
	
	getSavedSearches();
}

function deleteSavedSearch(id)
{
    new Ajax.Request(
        '/includes/delete_saved_search.php?id=' + id,
        {
            onComplete:function(e)
            {
                getSavedSearches();
            }
        }
    );
}

function getLoadingScreen()
{
    return Builder.node('div', { className:'loading' }, [Builder.node('img', { src:'/images/loading.gif' })]);
}

function $CF(name)
{
	return ($F(name) == 1 ? 1 : 0);
}

function getPartDetails(partcode)
{
	$(partcode).toggle();
	var imgid = 'img' + partcode;

	if ($(partcode).style.display == 'none')
	{
		$(imgid).src = '/images/tree_closed.png';
	}
	else
	{
		$(imgid).src = '/images/tree_open.png';
		var url = '/includes/getPartLookup.php?detail=1&partcode=' + partcode;
		var loading = getLoadingScreen();
		$(partcode).update(loading);
		new Ajax.Updater(partcode, url, {});	
	}
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

function deleteCookie( name, path, domain ) {
if ( getCookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


function watchPartcodeLookup(e)
{   
   var e = (window.event) ? window.event : e ;
   if ($('usequicklookup').checked == true)
   {
		var name = $F('pc');
		if (name.length >= 4)
		{
			if ($('quicklookup').style.display == 'none')
			{
				Effect.Appear('quicklookup', {duration:0.5});
			}
	
			Element.show('lookup_working');
			var url = 'getPartLookup.php?quick=1&partcode=' + name;

			new Ajax.Updater('quicklookup_content', url, { asynchronous:false, evalScripts:true, onComplete:Element.hide('lookup_working') });
			e.cancel = true;
			return false;
		}
		else
		{
			$('quicklookup_content').update('');
			Element.hide('quicklookup');
			//Element.hide('companylookup_results');
		}   
   }
}

function watchFrontPagePartSearch(e)
{
   var e = (window.event) ? window.event : e ;

   if (e.keyCode == 13)
   {
   		validateMainSearch();
   		return false;
   }
   else if (e.keyCode == 27)
   {
		resetFrontPage();
   		return false;
   }
   if ($F('searchbox').length >= 4)
   {
   		doFrontPagePartSearch();
   		e.cancel = true;
   		return false;
   }
   else
   {
   		resetFrontPage();
   }
}

function doFrontPagePartSearch()
{
	$('searchbox_image').src = '/images/spinner.gif';
	$('search_results').show();
	
	var url = '/includes/getPartLookup.php?quick=1&partcode=' + $F('searchbox');
	new Ajax.Updater('result_list', url, 
		{ 
			asynchronous:false, 
			evalScripts:true, 
			onComplete:handleLookupDone
		}
	);
}

function handleLookupDone(e)
{
	$('searchbox_image').src = '/images/close_widget.jpg';
}

function showFullSearchResults(partcode)
{
	if (partcode != the_partcode)
	{
		pagestart = 0;
	}
	the_partcode = partcode;

	$('search_legend').hide();
	$('search_results').hide();
	$('frontpage').hide();
	$('full_search_results').show();
	var url = '/includes/getPartLookup.php?partcode=' + partcode + '&start=' + pagestart;

	userid = getCookie('userid');
	if (userid == '')
	{
		url = url + '&public=1';
	}
	var l = getLoadingScreen();
	$('full_search_results').update(l);
	$('searchbox').value = partcode;
		
	new Ajax.Updater('full_search_results', url, 
		{ 
			asynchronous:true, 
			evalScripts:true
		}
	);
}

function loadSavedSearch(partcode)
{
	$('searches_button').removeClassName('selected');
	$('saved_searches').hide();
	$('searchbox').value = partcode;
	showFullSearchResults(partcode);
}

function resetFrontPage()
{
	$('search_results').hide();
	$('frontpage').show();
	$('full_search_results').hide();
	$('searchbox_image').src = '/images/blank.gif';
	$('search_legend').hide();
}

function validateMainSearch()
{
	if ($F('searchbox') != '')
	{
		showFullSearchResults($F('searchbox'));
	}
}
 
function selectAboutTab(a,b)
{
	if (selectedSmallTextBar)
	{
		Element.removeClassName(selectedSmallTextBar, 'selected');
	}
	Element.addClassName(a, 'selected');
	selectedSmallTextBar = a;
	
	if (b != '')
	{
		if (selectedOpenDiv)
		{
			Element.hide(selectedOpenDiv);
		}
		Element.show(b);
		selectedOpenDiv = b;
	}
	
	if (selectedOpenDiv != '')
	{
		if (selectedOpenDiv == 'transaction')
		{
			for(x=1;x<27;x++)
			{
				var name = 'fball' + x;
				Element.appear(name);
			}
		}
		else
		{
			for(x=1;x<27;x++)
			{
				var name = 'fball' + x;
				Element.hide(name);
			}
		}
	}
}

function showDisclaimer(name)
{
	var url = '';
	switch(name)
	{
		case 'price':
			url = 'disclaimer_price.html';
			break;
		case 'photos':
			url = 'disclaimer_photos.html';
			break;
		case 'liability':
			url = 'disclaimer_liability.html';
			break;

	}
	window.open(url,'','height=200,width=400');
}

function showLargePhoto(id)
{
    var img = '<img id=bigimage style=display:none; src=/includes/photo.php?p=' + id + '&l=1>';
	$('photo_viewer_content').update(img);
	if ($('photo_viewer').style.display == "none")
	{
		Effect.Appear('photo_viewer', {duration:0.5});
	}
	Effect.Appear('bigimage');
}

function viewPressFile(name)
{
	new Ajax.Updater('press_content','press_files/' + name, { method:'get' });
}


function $RF(el, radioGroup) { 
    if($(el).type && $(el).type.toLowerCase() == 'radio') { 
        var radioGroup = $(el).name; 
        var el = $(el).form; 
    } else if ($(el).tagName.toLowerCase() != 'form') { 
        return false; 
    } 
 
    var checked = $(el).getInputs('radio', radioGroup).find( 
        function(re) {return re.checked;} 
    ); 
    return (checked) ? $F(checked) : null; 
} 

function showSavedSearches()
{
	if ($('searches_button').hasClassName('selected'))
	{
		$('searches_button').removeClassName('selected');
		$('saved_searches').hide();
	}
	else
	{
		$('searches_button').addClassName('selected');
		$('saved_searches').show();
	}
}

function handle404(t)
{
	alert('Error 404: location "' + t.statusText + '" was not found.');
}

function handleFailure(t){
	alert('Error ' + t.status + ' -- ' + t.statusText);
}
