/*
* FirmListRender
* 
* Writes/renderers the project name from the project xml in to html.
*
*/

function FirmListRender(){}
//function render(object,contentRenderer){

FirmListRender.toggleCheckedFirm = function toggleCheckedFirm(firmObj,address){

	//alert(firmObj.id + " , " + firmObj.status);

	var imgElement = $("img_"+firmObj.id);
	
	if((imgElement.src).indexOf("unchecked.png")==-1){
		prospectHandler.removeProspectByFirmId(firmObj.id);
	}else{
		prospectHandler.createProspect(firmObj.id,address); 
	}
}


FirmListRender.firmIdsInPage = new HashMap(); 

FirmListRender.openAllFirmInfos = function openAllFirmInfos(){

	FirmListRender.firmIdsInPage.foreach(function(key) {
	   FirmListRender.openFirmInfo(key);
	});
	
} 



FirmListRender.renderFirm = function renderFirm(node){
	
	var id = node.getAttribute("id");
	var hash = node.getAttribute("hash");

//firm title.

	var firminfoDiv = document.createElement("div");		
  	firminfoDiv.className = "firminfoclosed";
  	firminfoDiv.id = id;
  	firminfoDiv.fid = id; // not to get same id...
  	//firminfoDiv.style.border = "1px solid #dddddd";
	//firminfoDiv.style.padding = "5px 5px 5px 5px";

	firminfoDiv.onmouseover = function() {
		$(this.id).className = "listrowon";
		if (window["map"] && window["map"] != null) {
			guiMapRender.changePinColor(guiMapRender.pins.get(this.id),"yellow");
		}
	}
	
	firminfoDiv.onmouseout = function() {
			$(this.id).className = "listrowoff";
			if (window["map"] && window["map"] != null) {
				guiMapRender.changePinColor(guiMapRender.pins.get(this.id),null);
			}
	}
  	
   			
 	var openCloseDatailInfoLinkTag = document.createElement("a");
 	openCloseDatailInfoLinkTag.setAttribute("href","#");
 	openCloseDatailInfoLinkTag.onclick = function() { FirmListRender.openFirmInfo(id); return false;};
			
	FirmListRender.firmIdsInPage.put(id);

 	var openCloseImg = document.createElement("img");
	openCloseImg.setAttribute("src",window["contextPath"]+"/images/arrowright.png");
	openCloseImg.id = id+"open";
	openCloseImg.setAttribute("hspace","5");
	openCloseImg.setAttribute("vspace","0");
	openCloseImg.setAttribute("border","0");
	
	openCloseDatailInfoLinkTag.appendChild(openCloseImg);
   			
	firminfoDiv.appendChild(openCloseDatailInfoLinkTag);
   			
   	//firminfoDiv.onclick = function() { showHandyBox();firmHandler.loadFirmInfoDetails('firmdetailinfo',this.fid);};
  			
  	var titleLink = document.createElement("a");
  	titleLink.className = "firmtitle";
  	var firmName = node.getAttribute("name")+" ";
	titleLink.appendChild(document.createTextNode(firmName));
	titleLink.href=window["contextPath"]+"/firm/?id="+id+"."+hash;
	firminfoDiv.appendChild(titleLink);

  	var newWindowLink = document.createElement("a");
	newWindowLink.href=window["contextPath"]+"/firm/?id="+id+"."+hash;
	newWindowLink.target="_blank";
	newWindowLink.innerHTML = "<img src=\""+window["contextPath"]+"/images/newwin.png\">";
  	firminfoDiv.appendChild(newWindowLink);
  	
	
	var zoomLink = document.createElement("a");
  	zoomLink.setAttribute("href","#");
  	zoomLink.innerHTML="<img src='"+window["contextPath"]+"/images/blue-dot-mini.png' border='0' id='maptag-"+id+"'/>";
  	//zoomLink.id = "maptag-"+id; // TODO: disable this if map-marker cant be loaded
  	zoomLink.id2 = id;
  	zoomLink.onclick = function() {
  		if (window["map"] && window["map"] != null) {
  			var marker = guiMapRender.pins.get(this.id2);
  			if(marker){
  				showlink = true;
  				if(map.getZoom()<17){
  						map.zoomIn();
  				}
  				map.panTo(marker.getPoint());
  			}
  		}
  		return false;
  	}
	firminfoDiv.appendChild(zoomLink);	
	
	
	//firm presentation.
	var firminfotextSpan = document.createElement("span");
  	firminfotextSpan.className = "firminfotext";
	
	var profile = node.getElementsByTagName("profile");
  	if(profile != null && profile != undefined && profile.length > 0){
  			
  		var profileNode = profile[0];
  		
		var v = profileNode.firstChild
	    var data = {};
	    while(v != null) {
	      if (v.nodeName != null && v.nodeName == "var") data[v.getAttribute("name")]=v.innerHTML; // firstChild.nodeValue;
	      v = v.nextSibling;
	    } 
  		
  		var presentation = data["description"];
  			
  		if(!presentation || "" == presentation){
  			presentation = data["presentation"];
  		}
  			
  		if(presentation && presentation.length > 0){
  			//presentation = (presentation.length>30) ? presentation.substring(0,30)+"..." : presentation; 	
  			firminfotextSpan.appendChild(document.createTextNode(presentation));
  			firminfotextSpan.appendChild(document.createElement("br"));
			firminfoDiv.appendChild(firminfotextSpan);
		}
  	}
	
	//firm address	
	var addresses = node.getElementsByTagName("address");
	var firmTown = "";
	var street = "";
	var streetnr = "";
	var zip = "";
	
	// TODO this could be a list of matching places...
  	if(addresses && addresses.length > 0){
  		var addressNode = addresses[0];
  		firmAddressId = addressNode.getAttribute("id");
  		geo = addressNode.getAttribute("geo");
  		firmTown = addressNode.getAttribute("city");
  		street = addressNode.getAttribute("street");
  		zip = addressNode.getAttribute("zip");
  		streetnr = addressNode.getAttribute("streetnr");
  		if (streetnr == "-1") streetnr = "";
  		titleLink.href = titleLink.href + "&a="+firmAddressId
  		newWindowLink.href = newWindowLink.href + "&a="+firmAddressId
  	}
  			
	var firmaddressSpan = document.createElement("div");
	firmaddressSpan.className = "firmaddress";
	firmaddressSpan.id = id + "div";
	
	var firmaddressSpanHeader = document.createElement("span");
	//firmaddressSpanHeader.className = "";
	firmaddressSpanHeader.appendChild(document.createTextNode("Adress: "));
	
	firmaddressSpan.appendChild(firmaddressSpanHeader);

	firmaddressSpan.appendChild(document.createTextNode(street  + " "+streetnr+", "));
	firmaddressSpan.appendChild(document.createTextNode(zip  + " "));
	firmaddressSpan.appendChild(document.createTextNode(" " + firmTown + ". "));
	
	firmaddressSpan.appendChild(document.createElement("br"));
	
	var wwwAddressWrapper = document.createElement("span");
  	var contactInfoSpanWrapper = document.createElement("span");
	
	var contacts = node.getElementsByTagName("contact");
  	if(contacts != null && contacts != undefined && contacts.length > 0){
  			
  		for(var i = 0; i != contacts.length ; i++){	
  			var contactNode = contacts[i];
  			if(contactNode.getAttribute("type")!=null && contactNode.getAttribute("type")!="HTTP" && contactNode.getAttribute("type")!="MAIL" && (contactNode.getAttribute("url") != null || "" != contactNode.getAttribute("url"))){
  		
  				var contactInfo = document.createElement("span");
				var contactInfoHeader = document.createElement("span");
  						
  				contactInfoHeader.appendChild(document.createTextNode(FirmListRender.getTranslatedContactInfoType(contactNode.getAttribute("type"))+": "));
  				contactInfo.appendChild(document.createTextNode(FirmListRender.washContactInfoUrl(contactNode.getAttribute("url"))+". " ));
  				//contactInfo.appendChild(document.createElement("br"));
  						
  				contactInfoSpanWrapper.appendChild(contactInfoHeader);
  				contactInfoSpanWrapper.appendChild(contactInfo);
  			}
  			
  			if(contactNode.getAttribute("type")!=null && contactNode.getAttribute("type")=="MAIL"){
  			
  				var emaillink = document.createElement("a");
  				emaillink.className = "emailaddresslink";
  				emaillink.setAttribute("href","#");
  				var emaillinkSpanHeader = document.createElement("span");
				emaillinkSpanHeader.className = "emailaddressheader";
				var emailheader = FirmListRender.getTranslatedContactInfoType(contactNode.getAttribute("type"));
  				emaillinkSpanHeader.appendChild(document.createTextNode(emailheader+": "));
  				emaillink.appendChild(document.createTextNode(FirmListRender.washContactInfoUrl(contactNode.getAttribute("url"))));
  				//emaillink.setAttribute("href","mailto:" + );
  				
  				var str = FirmListRender.washContactInfoUrl(contactNode.getAttribute("url"));
  				var str1 = str.substring(0,(str.indexOf("@")));
  				var str2 = str.substring((str.indexOf("@")+1));
  				str = "function() { onClickEmail('"+str1+"','"+str2+"'); return false; }";
	  		
		  		if(window.execScript){
					window.execScript("tmp="+str);
					emaillink.onclick = tmp;			 	    
				} else {
		 			window.eval("window.tmp="+str);
					emaillink.onclick = window.tmp;
					delete window["tmp"];	    		    
				}
  				
  				contactInfoSpanWrapper.appendChild(emaillinkSpanHeader);
  				contactInfoSpanWrapper.appendChild(emaillink);
  			
  			}
  			
  			if(contactNode.getAttribute("type")!=null && contactNode.getAttribute("type")=="HTTP"){
  				//firm contacts address
				var wwwaddressLink = document.createElement("a");
  				wwwaddressLink.className = "wwwaddress";
				var wwwaddressSpanHeader = document.createElement("span");
				wwwaddressSpanHeader.className = "wwwaddressheader";
  				var header = FirmListRender.getTranslatedContactInfoType(contactNode.getAttribute("type"));
  				wwwaddressSpanHeader.appendChild(document.createTextNode(header+": "));
  				wwwaddressLink.setAttribute("href",contactNode.getAttribute("url"));
  				wwwaddressLink.setAttribute("target","new");
  				wwwaddressLink.appendChild(document.createTextNode(FirmListRender.washContactInfoUrl(contactNode.getAttribute("url"))));
  				// ls wwwAddressWrapper.appendChild(document.createElement("br"));
  				wwwAddressWrapper.appendChild(wwwaddressSpanHeader);
  				wwwAddressWrapper.appendChild(wwwaddressLink);
  			}
  			
			wwwAddressWrapper.appendChild(document.createTextNode(" "));
  			
  		}
  	}
  			
  	firmaddressSpan.appendChild(contactInfoSpanWrapper);
	firmaddressSpan.appendChild(wwwAddressWrapper);

    firminfoDiv.appendChild(firmaddressSpan);
 
	return firminfoDiv;
}

FirmListRender.washContactInfoUrl = function washContactInfoUrl(url){
	if(url.indexOf(":")!=-1){
		if(url.indexOf("http://")!=-1){
			return url.substring((url.indexOf(":")+3));
		}else{
			return url.substring((url.indexOf(":")+1));
		}
	}
	return url; 
}

FirmListRender.contactNames = { "HTTP":"Hemsida", "TEL":"Telefon", "FAX":"Fax", "CELL":"Mobil", "SIP":"Sip", "UNKNOW":"", "MAIL":"E-post" };

FirmListRender.getTranslatedContactInfoType = function getTranslatedContactInfoType(typeName){

	var v = FirmListRender.contactNames[typeName];
	if (v) return v;
	return "["+typeName+"]";
}

FirmListRender.openFirmInfo = function openFirmInfo(id){

	var imgElement = $(id+"open");

	var firmInfoDiv = $(id); 
	
	var obj = $(id+"div");
		
		if(obj!=null && obj != undefined){
			toggleDisplay(id+"div");
		}
	
		if(imgElement != null && imgElement != undefined && (imgElement.src).indexOf("arrowright.png")==-1){
			imgElement.src = window["contextPath"]+"/images/arrowright.png";
		
			if(firmInfoDiv){
				firmInfoDiv.className = "firminfoclosed";
			}
		}else if(imgElement != null && imgElement != undefined){
			imgElement.src = window["contextPath"]+"/images/arrowdown.png";
	
			if(firmInfoDiv){
				firmInfoDiv.className = "firminfoopen";
			}
		}
}


FirmListRender.changeRegionMapOn = function changeRegionMapOn(id){
		var mapImage = $("regionmap");
		mapImage.src = window["contextPath"]+"/images/"+id+".png";
	}

FirmListRender.changeRegionMapOff =	function changeRegionMapOff(){
		var mapImage = $("regionmap");
		mapImage.src = window["contextPath"]+"/images/map_blekinge_kommuner.png";
	}


/**
* render
* \u00f6 = �
* \u00e5 = �
* \u00e4 = �
**/
FirmListRender.prototype.render = function render(object,htmlElementId){
	
	var textBox = $(htmlElementId);
	var j,id;
	
	while(textBox.childNodes.length > 0){
	  	textBox.removeChild(textBox.childNodes.item(0));
	}
	
	var header = object.getElementsByTagName("firms");
	
	var totalSize = parseInt(header[0].getAttribute("totalsize"));
  	var sIndex = parseInt(header[0].getAttribute("sindex"));
  	var size = parseInt(header[0].getAttribute("size"));
  	var srankc = parseInt(header[0].getAttribute("rankclass"));
  	
	var showing = 0;
	if(sIndex+size>=totalSize){
		showing = totalSize;
	}else{
		showing=sIndex+size;
	}

    // felmeddelanden
    var events = object.getElementsByTagName("event");
    if (events != null) {
         // alert("events");
         for(j = 0 ; j < events.length ; j++){    
            var e = events[j];
            // alert(e.getAttribute("type"));
            if (e.getAttribute("type") == "error") {
                // alert("got:"+e.childNodes[0].nodeValue);
                var p = document.createElement("p");
                p.appendChild(document.createTextNode(e.childNodes[0].nodeValue));
                textBox.appendChild(p);
            }       
         }
    }

    // clear and select the right tab (again?)
    //renderTabs(srankc);
    
	// -------fill rank tabs with nr of matches---------- 
	var setList = object.getElementsByTagName("set");
	if(setList){
		for(j = 0 ; j < setList.length ; j++){
			if(setList[j].getAttribute("type") == "rankgroups"){
				var groupList = setList[j].getElementsByTagName("val");
				if(groupList){
					for(var k = 0 ; k < groupList.length ; k++){
						var rankcountTab = $("rankcount"+groupList[k].getAttribute("name"));
						if(rankcountTab) rankcountTab.innerHTML = groupList[k].getAttribute("count") + " ";
					}
				}
			break;
			}
		}
	}

    
	// Lista firmor ...  
	var elementList = object.getElementsByTagName("firm");
	if (elementList != null && elementList != undefined && elementList.length > 0) {
	  
	  		//var textRow = document.createElement("div");
  	  		// textBox.appendChild(document.createElement("br"));	
  	  	
  	  		var spansoktag = document.createElement("span");
  	  		spansoktag.className = "rubrik";
  	  	  	spansoktag.appendChild(document.createTextNode("Träfflista - visar företag " + (sIndex + ((sIndex==0)? 1 : 0)) + " till " +  showing + " av " + totalSize + ". \u00a0"));
  	  	  	textBox.appendChild(spansoktag);
  			
  		// ----select nr to show-------	
  			
  			var std = $c("span");
  			var select = $c("select");
  			select.id = "displaySize";
  			select.sranc = lastSearchRankc;

  			var str = "function(){ var size = $('displaySize').options[$('displaySize').selectedIndex].value; searchPage(0,size); }";

  			if (window.execScript) {
  				window.execScript("xXx=" + str);
  				select.onchange = xXx;
  			} else {
  				var func = eval("window.tmp=" + str);
  				select.onchange = window.tmp;
  				delete window.tmp;
  			}

  			var option = $c("option");
  			option.value = "15";
  			if (size == 15) option.selected = "true";
  			option.appendChild($t("visa 15"));
  			select.appendChild(option);

  			option = $c("option");
  			option.value = "25";
  			if (size == 25) option.selected = "true";
  			option.appendChild($t("visa 25"));
  			select.appendChild(option);

  			option = $c("option");
  			option.value = "50";
  			if (size == 50) option.selected = "true";
  			option.appendChild($t("visa 50"));
  			select.appendChild(option);

  			std.appendChild(select); 

  			std.appendChild($t(" "));
  			
  			textBox.appendChild(std);
  			  			
  			textBox.appendChild($c("br"));
  			var openAlllink = $c("a");
  			openAlllink.setAttribute("href","javascript:FirmListRender.openAllFirmInfos();");
  			openAlllink.appendChild($t("\u00f6ppna/st\u00e4ng alla"));
  			//textBox.appendChild(openAlllink);
  			//textBox.appendChild($c("br"));
  		 	
  		 	var tableTag = document.createElement("table");
  	  		tableTag.className = "firmtable";
  	  		tableTag.setAttribute("border","0");
  	  		// tableTag.setAttribute("width","600");
			tableTag.setAttribute("cellspacing","0");
			tableTag.setAttribute("cellpadding","0");
	
			//must have tbody tag for tables to work in IE.6.
	  		tbodyTag = document.createElement("tbody");
	  
	  		var trHeader = document.createElement("tr");
	  		
	  		var headerCell1 = document.createElement("td");
	  		headerCell1.className ="smalbuttonheadercell";
	  		
	  		var headerCell2 = document.createElement("td");
	  		headerCell2.className ="rubrikcell";
	  
	  		var spantag = document.createElement("span");
	  		spantag.className = "rubrik";
			spantag.appendChild(document.createTextNode("V\u00e4lj"));

	  		var spantagCompany = document.createElement("span");
	  		spantagCompany.className = "rubrik";
			spantagCompany.appendChild(document.createTextNode("F\u00f6retag"));

	  		headerCell1.appendChild(spantag);
	  		headerCell2.appendChild(spantagCompany);
	  	
	  		trHeader.appendChild(headerCell1);
	 		trHeader.appendChild(headerCell2);
	 
	  		tbodyTag.appendChild(trHeader);

	  		textBox.appendChild(document.createElement("br"));
	  
  	  	  	for(j = 0 ; j < elementList.length ; j++){
  	  	
	  	  		var row = document.createElement("tr");
				var cell1 = document.createElement("td");
				cell1.className = "smalbuttoncell";
				
		  		var cell2 = document.createElement("td");
		  		cell2.className = "firminfocell";
		  		
		  		var node = elementList[j];
	  	  		id = node.getAttribute("id");
	  	  
	  	  		var firmwrapDiv = document.createElement("div");
	  	  	 	//(ska bort, DT)firmwrapDiv.className = "firmwrapper";
	  	  	  	firmwrapDiv.id = id+"w"; 	  	  		
	  	  	  	//(ska bort, DT)firmwrapDiv.onmouseover = function() {this.className = "firmwrapperon";}
	  	  	  	//(ska bort, DT)firmwrapDiv.onmouseout = function() {this.className = "firmwrapper";}
	  	  	  			  	  		
	  	  		var firmcheckboxDiv = document.createElement("span");
	  	  		firmcheckboxDiv.className = "firmcheckbox";
	  	  			
	  	  		//textRow.appendChild(firmwrapDiv);

	  	  		var imgCheckTag = document.createElement("img");
	  	  		imgCheckTag.id = "img_"+id;
	  	  		imgCheckTag.fid = id;
	  	  		imgCheckTag.aid = 0;
	  	  		
	  	  		var addressesList = node.getElementsByTagName("address");
	  	  		if(addressesList != null && addressesList != undefined && addressesList.length > 0){
	  	  			var addressListNode = addressesList[0];
	  	  			imgCheckTag.aid = addressListNode.getAttribute("zip");
					//alert(imgCheckTag.aid);
	  	  		}
	  	  		
	  	  		//check if this firm is marked.
	  	  		var firmObj = ProspectListRender.markedfirms.get(id);
	  	  		//if checked, set reference to firmObj from markedfirms, that also holds status.
	  	  		if(firmObj){
	  	  			imgCheckTag.fid = firmObj;
	  	  		}else{
	  	  			imgCheckTag.fid = {id:id,status:"NEW"};
	  	  		}
	  	  		
	  	  		if(firmObj && firmObj.status && firmObj.status == "NEW"){
	  	   			imgCheckTag.setAttribute("src",window["contextPath"]+"/images/checkbox_checked.png");  
	  	   		
	  	   		}else if(firmObj && firmObj.status && firmObj.status != "NEW"){
	  	   			imgCheckTag.setAttribute("src",window["contextPath"]+"/images/checkbox_disabled_checked.png");
	  	   		
	  	   		}else{
	  	   			imgCheckTag.setAttribute("src",window["contextPath"]+"/images/checkbox_unchecked.png");
	  	   		}
	  	   			
	  	   	  	imgCheckTag.onclick = function() { FirmListRender.toggleCheckedFirm(this.fid,this.aid); };
	  	  		firmcheckboxDiv.appendChild(imgCheckTag);
	  	  		cell1.appendChild(firmcheckboxDiv);
	  	  	
	  	 		//firmRender.
	  	  	
	  	  		var firminfoDiv = FirmListRender.renderFirm(node);
					
				//firm render
					
				firmwrapDiv.appendChild(firminfoDiv);
					
				//attach firm to page. 				
				//textRow.appendChild(firmwrapDiv);	
	  			cell2.appendChild(firmwrapDiv);	
	   	 		//textBox.appendChild(document.createElement("br"));
	    		row.appendChild(cell1);
		  		row.appendChild(cell2);
	  	  		tbodyTag.appendChild(row);
	  	  	 
  	  	  	}
      	 	
      	 	tableTag.appendChild(tbodyTag);
	  		textBox.appendChild(tableTag);
	  		textBox.appendChild(document.createElement("br"));
      	 	
      	 	//paging...
      	 	if(sIndex > 0){
  	  	  	
  	  	  		var prevIndex = (sIndex-size);
  	  	  		if(prevIndex<0){
  	  	  			prevIndex=0;
  	  	  		}
  	  	  		var prevTag = document.createElement("a");
  	  	  		prevTag.setAttribute("href","javascript:searchPage("+prevIndex+","+size+","+srankc+");");
  	  	  		prevTag.appendChild(document.createTextNode("<< f\u00f6reg\u00e5ende "));
  	  	  		
  	  	  		textBox.appendChild(prevTag);
  	  	  	}
  	  	  	
  	  	  	var loopsize = Math.round(totalSize / size);
  	  		if(loopsize>20){
  	  			loopsize = 20;
  	  			//more logic needed here to print end and start, steps between should adjust accordingly.
  	  		}
  	  		
  	  	  	for(var i = 0; i < loopsize ; i++){
  	  		
  	  			var pageTag = document.createElement("a");
  	  		    pageTag.setAttribute("href","javascript:searchPage("+(i*size)+","+size+","+srankc+");");

  	  			//write steps of pages.
  	  			var strLink = ""+(i+1)+" ";
  	  			
  	  			//only print dots if total loopsize is over threshold 12 and between some % from begining and end.
  	  			if(( i > Math.round(loopsize*0.33) && i < Math.round(loopsize*0.66)) && loopsize >= 12){
  	  				strLink = " . ";	
  	  			}
  	  			//mark current page index.
  	  			if(sIndex == i*size){
  	  				strLink = "[" + (i+1) + "]";
  	  			}
  	  			pageTag.appendChild(document.createTextNode(strLink));
  	  			textBox.appendChild(pageTag);
  	  		}
  	  	  	if((sIndex+size) < totalSize){	
  	  	  		var nextTag = document.createElement("a");
  	  	  		nextTag.setAttribute("href","javascript:searchPage("+(sIndex+size)+","+size+","+srankc+");");
  	  	  		nextTag.appendChild(document.createTextNode(" n\u00e4sta >>"));
  	  	  		textBox.appendChild(nextTag);
  	  	  	}
  	  	  	
  	  	  	if(ProspectListRender.markedfirms.isEmpty()){
  			//open address info for 2 first firms.
  	  	  		for(j = 0 ; j < 2 && j < elementList.length ; j++){
  	  	  			id = elementList[j].getAttribute("id");
  	  	  			FirmListRender.openFirmInfo(id);
  	  	  		}
  	  	  	}else{
  	  	  	//open address info for all marked firms.
  	  	  		ProspectListRender.markedfirms.foreach(function(key) {FirmListRender.openFirmInfo(key);});
  	  	  	}
     	  } else {
  	  	  	textBox.appendChild(document.createTextNode('Inga f\u00f6retag hittades'));
  	  	  }
}



