function search(f){
	var q = f.q.value;
	if(/^\s*$/.test(q) || /^Enter an industry$/.test(q) || /^.$/.test(q)){alert("Please enter an industry to search for.");return;}
	$("#pointer").css("display","none");
	naics.startWait();
	$.ajax({type:"POST",dataType:"json",url:"/cgi-bin/naics/search.js",data:{"q":q},
	success:function(msg,txtStatus){
		if(!msg.failure){
			if(msg.result){
			
				if(msg.result.length){
					var a = "";
					var inst = "Click on this industry to see its position in the classification tree.";
					$.each(msg.result,function(i,val){
						a+= '<li>'+val[1]+': <a href="javascript:naics.expandTo(\''+val[1]+'\');" alt="'+inst+'" title="'+inst+'">'+val[0]+'</a></li>';
					});
					a = "<ul>"+a+"</ul>";
				}else{
					a = "No industries match your search term.  Try again with a different term.";
				}
				
				$("#answers").empty();
				$("#answers").append(a);
				naics.endWait();
				
			}
		}else{
			alert("api returns: "+msg.failure);
		}
	},
	complete:function(rq, textStatus){
		pageTracker._trackEvent("naics", "search", q);
	}
	
	});
}



function aClass(code,clsName,isLast,industryCount){
	this.code = code;
	this.clsName = clsName;
	this.industryCount = industryCount;
	this.isLast = isLast;
	this.definition = "";
	this.subClasses = [];
	this.jsonObj;
	
	this.startWait = function(){$("#loading").css({"display":"block"});}
	this.endWait = function(){$("#loading").css({"display":"none"});}
	
    this.findTargetSubClass = function(clsObj,code){
    	//alert(code+": "+clsObj.clsName);
		var sc;
    	for(var i = 0; i < clsObj.subClasses.length; i++){
    		sc = clsObj.subClasses[i];
			if(sc.code == code){return sc;}
    	}
		var found;
    	for(var j = 0; j < clsObj.subClasses.length; j++){
    		sc = clsObj.subClasses[j];
				if(sc.subClasses.length){found = sc.findTargetSubClass(sc,code);}	
				if(found)return found;
    	}    
		return 0;
    }
    
	this.displaySelf = function(trg){
	    var className = this.clsName.replace(/'/g,"\\'");
	    var clsLink;
	    if(this.isLast){clsLink = '- '+this.clsName+' ';}
	    else{clsLink = this.code+': <a href="#" onclick="naics.toggleSubClasses(\''+this.code+'\',this,\''+className+'\'); return false;" title="view sub-classifications of '+this.clsName+'">'+this.clsName+'</a> ('+this.industryCount+' industries) ';}
		
		var defLink = '<a href="#getDefinitionFor'+this.code+'" onclick="naics.getDefinition(\''+this.code+'\',this); return false;" title="view NAICS definiton of '+this.clsName+'"><img src="/images/icon-dictionary-small.gif" /></a> ';
		var censusData = '<a href="http://factfinder.census.gov/servlet/SAFFEconFacts?_event=&geo_id=01000US&_geoContext=01000US&_street=&_county=&_cityTown=&_state=&_zip=&_lang=en&_sse=on&ActiveGeoDiv=&_useEV=&pctxt=bg&pgsl=010&_submenuId=business_2&ds_name=&_ci_nbr=&qr_name=&reg=%3Anull&_keyword=&_industry='+this.code+'" title="view 2002 US Census data for this Sector/Industry"><img src="/images/icon-pie-chart-small.gif" /></a>';
                var census2007Link = '<a href="http://factfinder.census.gov/servlet/EconSectorServlet?caller=dataset&amp;sv_name=*&amp;_SectorId='+this.code+'&amp;ds_name=EC0700A1&amp;_lang=en" title="view 2007 US Economic Census data for this sector" ><img src="/images/icon-pie-chart-small.gif" /></a>';
               
                if(this.code.length != 2 || /(11|21|92)/.test(this.code) ){census2007Link = "";}
		if(this.isLast){defLink = ""; censusData = "";}
		if(this.code.length != 6){defLink = ""; censusData = "";}
		
		var newLI = '<li id="'+this.code+'">'+clsLink+
		'<span>'+defLink+'<a href="http://news.google.com/news?q='+escape('"'+this.clsName+'"')+'" title="view recent news for '+this.clsName+'"><img src="/images/icon-newspaper-small.png" /></a> '+
		'<a href="http://www.google.com/search?q='+escape('"'+this.clsName+'"')+'" title="web search for '+this.clsName+'"><img src="/images/icon-search-small.png" /></a> '+
		censusData+census2007Link+
		'</span>'+
		'</li>';
		trg.append(newLI);
		this.visible = true;
	}

	this.assignNewClasses = function(trg){
		var obj = this;
		$.each(obj.jsonObj.result,function(i,val){
			if(/[a-z]/i.test(val[1]) && val[2] != obj.code){
				//code,clsName,isLast,industryCount
				obj.subClasses.push(new aClass(val[2],val[1],0,val[0]));
			}else if(val[1].length == 6){
				//code,clsName,isLast,industryCount
				obj.subClasses.push(new aClass(val[1],val[0],1,0));
			}
		});
		$(trg).append("<ol></ol>");
		trg = $(trg).children("OL");
		var li;
		for(var i=0; i< obj.subClasses.length; i++){
			li = obj.subClasses[i];
			li.displaySelf(trg);
		}	
        }

	this.getSubClasses = function(code,trg){
		 var parentClass = this;
		 var strLn;
		 var getIndus = 0;
		 if(!code){strLn = 2;}
		 else if(/-/.test(code)){strLn = 3;}
		 else if(code.length == 6){getIndus=1;strLn = 6;}
		 else{strLn = code.length+1;}
		 
		 parentClass.startWait();
		 $.ajax({type:"POST",dataType:"json",url:"/cgi-bin/naics/getD.js",data:{"strLn":strLn,"cls":code,"getIndus":getIndus},
			success:function(msg,txtStatus){
				if(!msg.failure){
					if(msg.result){
						parentClass.jsonObj = msg;
						parentClass.endWait();
					}
				}else{
					alert("api returns: "+msg.failure);
				}
			},
			complete:function(rq, textStatus){
				//alert(rq.responseText);
				//alert(textStatus);
			}
			
		 });
		 
	}

	this.toggleSubClasses = function(code,trgTag,clsName){
		var clickedObj;
		if(trgTag.attr && trgTag.attr("id") && trgTag.attr("id") == "listsNAICS"){  // DISPLAY FIRST LEVEL CLASSIFICATIONS
			clickedObj = this;
			$(window).bind("ajaxComplete",function(){
				clickedObj.assignNewClasses(trgTag);
				$(window).unbind("ajaxComplete");
				var bk = window.location.hash;
				if(/#code/.test(bk)){
					bk = bk.split("#code");
					clickedObj.expandTo(bk[1]+'');
				}
			});
			clickedObj.getSubClasses(code,trgTag);
		}else{
			//if(code.length == 6){this.getDefinition(code,trgTag);this.scrollTo(code,trgTag);return;}
			clickedObj = this.findTargetSubClass(this,code);
			if(!clickedObj){alert("This classification:"+code+" does not exit."); return;}
			trgTag = trgTag.parentNode;
			if(clickedObj.subClasses.length){
				if($(trgTag).children("OL").length){
					$(trgTag).children("OL").remove();
				}else{
					$(trgTag).children("DD").remove();
					$(trgTag).append("<ol></ol>");
					trgTag = $(trgTag).children("OL");
					for(var i=0; i< clickedObj.subClasses.length; i++){
						clickedObj.subClasses[i].displaySelf(trgTag);
					}
					pageTracker._trackEvent("naics", "showSubClasses", code);
				}
				clickedObj.scrollTo(code);
			}else{	
				$(trgTag).children("DD").remove();
				$(window).bind("ajaxComplete",function(){
						$(window).unbind("ajaxComplete");
						clickedObj.assignNewClasses(trgTag);
						clickedObj.scrollTo(code);
						pageTracker._trackEvent("naics", "showSubClasses", code);
					}
				);
				clickedObj.getSubClasses(code,trgTag);
			}
		}
	}
	
	this.toggleDefinition = function(code,trgTag){
		while($(trgTag).attr("id") != code){trgTag = trgTag.parentNode;}
		
		if(!$(trgTag).children("DD").length){
			$(trgTag).children("OL").remove();$(trgTag).append("<dd>"+this.definition+"</dd>");
		}else{
			$(trgTag).children("DD").remove();
		}
		this.point(code,trgTag);
	}

	this.getDefinition = function(code,trgTag){
		var clickedObj;
		clickedObj = this.findTargetSubClass(this,code);
		if(!clickedObj){alert("not part of classification."); return;}
		if(!clickedObj.definition){
			 clickedObj.startWait();
			 $.ajax({type:"POST",dataType:"json",url:"/cgi-bin/naics/getD.js",data:{"cls":code,"getDef":1},
				success:function(msg){
					if(!msg.failure){
							if(msg.result.length){
								clickedObj.definition = clickedObj.makeCrossReferences(msg.result[0][0]);
							}else{
								clickedObj.definition = "There is no definition for this sub-classification.";
							}
					}else{
						alert("api returns: "+msg.failure);
					}
					clickedObj.endWait();
					clickedObj.toggleDefinition(code,trgTag);
				}
			 });
			
			
		}else{
			clickedObj.toggleDefinition(code,trgTag);
		}
	
	}
	
	this.makeCrossReferences = function(txt){
		txt = txt.replace(/Industry\s(\d{2,6})/g,'<a href="javascript:naics.expandTo(\'$1\');">$&</a>');
		txt = txt.replace(/Industry\sGroup\s(\d{2,6})/g,'<a href="javascript:naics.expandTo(\'$1\');">$&</a>');		
		txt = txt.replace(/Sector\s(\d\d(?:-\d\d)?)/g,'<a href="javascript:naics.expandTo(\'$1\');">$&</a>');
		txt = txt.replace(/Subsector\s(\d{2,6})/g,'<a href="javascript:naics.expandTo(\'$1\');">$&</a>');
		return txt;
	}

	this.expandTo = function(code){
		var levels = new Array();		
		levels[0] = code;
		var codes;
		//if code is not two digits long or containing a dash
		if(!(/^\d\d$/.test(code) || /-/.test(code))){
			//while code is still greater than 2 digits long still does not contain a dash,
			//cut off last digit of code until we reach a top code
			while(levels[0].length > 2 && !/-/.test(levels[0])){
				levels.unshift(levels[0].substring(0,levels[0].length-1));
				if(levels[0] == 44 || levels[0] == 45){levels[0] = "44-45";}
				if(levels[0] == 48 || levels[0] == 49){levels[0] = "48-49";}
				if(levels[0] == 31 || levels[0] == 32 || levels[0] == 33){levels[0] = "31-33";}
			}
		}

		var obj = this;
		var trgTag;
		//loop through levels
		for(var i = 0; i<levels.length; i++){
			//loop through classifications in each level
			for(var j=0; j<obj.subClasses.length; j++){
				if(obj.subClasses[j].code == levels[i]){
					obj = obj.subClasses[j];
					if(!obj.subClasses.length){
						$(window).bind("ajaxComplete",function(){
							$(window).unbind("ajaxComplete");
							obj.assignNewClasses("#"+levels[i]);
							if(obj.code != code){obj.expandTo(code);}
						});
						obj.getSubClasses(levels[i],trgTag);
						this.scrollTo(code);
						
						return;
					}else{
						if(!$("#"+levels[i]).children("OL").length){
							$("#"+levels[i]).append("<ol></ol>");
							trgTag = $("#"+levels[i]).children("OL");
							for(var x=0; x< obj.subClasses.length; x++){
								obj.subClasses[x].displaySelf(trgTag);
							}
						}
					}
				}
			}
		
		}
		this.scrollTo(code);
		pageTracker._trackEvent("naics", "expandToClass", code);
		
	
	}
	
	
	this.scrollTo = function(code,trgTag){
		var os;
		if(typeof trgTag != "undefined"){
			while($(trgTag).attr("id") != code){trgTag = trgTag.parentNode;}
			os = $(trgTag).offset();
		}else{
			os = $("#"+code).offset();
		}
		if(!os){return;}
		var iebody=(document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body
		var dsocleft=document.all? iebody.scrollLeft : pageXOffset;
		var dsoctop=document.all? iebody.scrollTop : pageYOffset;
		if(os.top < dsoctop || os.top > dsoctop+$(window).height()){ 
			window.scrollTo(0,os.top-($(window).height()/2));
		}
		var loc = window.location.href;
		loc = loc.replace(/\#.*$/,"");
		window.location = loc+"#code"+code;
		this.point(code,trgTag);
	}
	
	this.point = function(code,trgTag){
		var os;
		if(typeof trgTag != "undefined"){
			while($(trgTag).attr("id") != code){trgTag = trgTag.parentNode;}
			os = $(trgTag).offset();
		}else{
			os = $("#"+code).offset();
		}
		if(!os){return;}
                var la=17; var ta = 1;
                if($.browser.msie){la=20;ta=4;}
                var pl = $(".pages").offset();
		$("#pointer").css("left",os.left-pl.left - la);
		$("#pointer").css("top",os.top+ta);
		$("#pointer").css("display","block");
	}
	
}//END CLASS DECLARATION
//$(window).bind("ajaxComplete",function(){alert("global complete");});
var naics = new aClass("","NAICS",0,0,"");







$(document).ready(function(){
	naics.toggleSubClasses(naics.code,$('#listsNAICS'));
	
});
