var DROPDWNPREFIX='_ctl0__ctl0_ContentPlaceHolderPageSetup_ContentPlaceHolderMain_DropDownListfilterTopics';                   
var LISTBOXPREFIX='_ctl0__ctl0_ContentPlaceHolderPageSetup_ContentPlaceHolderMain_ListBox';
var LISTBOXASSOCSID='_ctl0__ctl0_ContentPlaceHolderPageSetup_ContentPlaceHolderMain_ListBoxAssocType';

function GetAssocs(){	
new Ajax.Request('/ajax/GetTagAssocTypes.aspx',   
{     
   method:'get', onSuccess: function(transport)
     {    
        var res=transport.responseText || "No Response";                     
        if(!isErrorMsg(res)){
       	//clear listbox	
		    listboxAssocs = $(LISTBOXASSOCSID);
			if(listboxAssocs){
			    while (listboxAssocs.options.length > 0) {
				    listboxAssocs.options[0] = null;
			    }
	
		        var arrItems = res.split("\n");
		        for(i=0; i<arrItems.length; i++)
		        {
				    var arrItem = arrItems[i].split("##");
				    if(arrItem[1] != null && arrItem[0]!='undefined')
				    {
				        listboxAssocs.options[listboxAssocs.options.length] = new Option(arrItem[1].replace(/^\s+|\s+$/g,''), arrItem[0]);						
				    }
                }   	
            }			   
        }
		else{msgErr(res);}                	
     },onFailure:function(t){msgErr('Error '+t.status +' - '+t.statusText);}  
}); 
}



function assocListboxClicked(assocListBox){
//alert('assocListboxClicked');	
var assocId = assocListBox.options[assocListBox.selectedIndex].value;
//alert(assocId);						
GetRolesForAssoc(assocId);			   
}


function resetView(){	
changeObjectDisplayStyle('PanelStartup','block');
changeObjectDisplayStyle('PanelTagsSelectedOK','none');
changeObjectDisplayStyle('PanelCreateReleation','none');
//changeObjectDisplayStyle('PanelAssocRolePreview','none');


changeObjectDisplayStyle('PanelRelationExists','none'); 	
//alert($('PanelRelationsList'));
if($('PanelRelationsList'))		
  document.getElementById('PanelRelationsList').innerHTML = '';	
		
}


var tA=-1;
var tB=-1;
//when clicking on a topic item
function listboxClicked(theListBox,listboxIdentifier){
		
//call Ajax function
getStyleObject('panelAjaxFeedback').display = 'none';
getStyleObject('welcome').display = 'none';

getDescriptionAndAliasesForTopic(theListBox.options[theListBox.selectedIndex].value, listboxIdentifier);
		
if(listboxIdentifier == 'A'){				
   tA = theListBox.options[theListBox.selectedIndex].value;
   }
else{
   tB = theListBox.options[theListBox.selectedIndex].value;
   }

$('jumpToTopic'+listboxIdentifier).innerHTML = '<a href="../tag/'+ eval('t'+listboxIdentifier) +'">Open</a>';


//if both Tags have been selected then show lnks between them
if(tA>-1 && tB>-1){					
	changeObjectDisplayStyle('PanelStartup','none');
//alert(tA + '--'+tB );				
	//if(getStyleObject('PanelAssocRolePreview').display == 'none'){  
		//if we are previewing roles then dont start showing create button
		changeObjectDisplayStyle('PanelTagsSelectedOK','block');	
		//changeObjectDisplayStyle('PanelCreateReleation','none');
	//}	
	
	getRelationsBetweenTopics(tA,tB); 				  
}else{
	resetView();				
}
changeObjectDisplayStyle('panelAjaxFeedbackError','none'); 	



//if we have choosen in dropdpownlist B to view items relate to A then update view
var dropDownB = document.getElementById(DROPDWNPREFIX+'B');
//alert(dropDownB.options[dropDownB.selectedIndex].value);
var dropdownBselectedView = dropDownB.options[dropDownB.selectedIndex].value;
if(dropdownBselectedView == 104){
//alert();
  if(listboxIdentifier=='A')  //only update list B if listbox A was clicked
   GetTagsPlainListing(tA, 104, 'B', $('startUpTopic').value);   //104 means show linked to listbox A topic
}	


//if we have choosen assoc roles then update roles preview
var listBoxA = $(LISTBOXPREFIX+'A');
var listBoxB = $(LISTBOXPREFIX+'B');
var listBoxAssocs = $(LISTBOXASSOCSID);
if((listBoxA.selectedIndex > -1) && ( listBoxB.selectedIndex > -1)){
  if(listBoxAssocs.selectedIndex > -1){
     assocListboxClicked(listboxAssocs);
  }
}   			
}




//when selecting topic viewing 
function dropdownClicked(dropdownBox, listboxIdentifier, selectItem){
//alert('dropdownClicked');						
resetView();	

if(dropdownBox.options[dropdownBox.selectedIndex].value == -1)
  return;


var theOtherListBox = -1;
if(listboxIdentifier=='A'){
	theOtherListBox =  $(LISTBOXPREFIX+'B');
	tA=-1;			
}else{
	theOtherListBox = $(LISTBOXPREFIX+'A');
	tB=-1;
}
	
$('jumpToTopic'+listboxIdentifier).innerHTML = '';  //clear jump to link

startUpValue='';
if($('startUpTopic')){startUpValue = $('startUpTopic').value;}

if(selectItem){ //force click on item
   dropdownBox.selectedIndex = selectItem;
}
	
//alert(theListBox.options[theListBox.selectedIndex].value); //debug
var otherListboxValue = -1;
//alert(theOtherListBox.selectedIndex);
if(theOtherListBox.selectedIndex >= 0)
{				
   otherListboxValue = theOtherListBox.options[theOtherListBox.selectedIndex].value;
}				

GetTagsPlainListing(otherListboxValue, dropdownBox.options[dropdownBox.selectedIndex].value, listboxIdentifier, startUpValue);

}


function startupViewAutoPopulatedItems()
{			
dropdownClicked($(DROPDWNPREFIX+'A'),'A',0);
dropdownClicked($(DROPDWNPREFIX+'B'),'B',0);

}




function showCreateAssocPanel(show){
if(show){
	getStyleObject('PanelCreateReleation').display='block';
	getStyleObject('PanelTagsSelectedOK').display='none';
}else{
	getStyleObject('PanelCreateReleation').display='none';
	getStyleObject('PanelTagsSelectedOK').display='block';

}
}


function mergeTags(){
var listBox = $(LISTBOXPREFIX+'A');
var topicIdA = listBox.options[listBox.selectedIndex].value;
listBox = $(LISTBOXPREFIX+'B');
var topicIdB = listBox.options[listBox.selectedIndex].value;
issueTopicMerge(topicIdA,topicIdB);

}


function swapRoles(){			
//swap text
var roleACtrl = $('roleA');
//alert(roleACtrl); 
var roleBCtrl = $('roleB');
var temp = 	roleACtrl.innerHTML;
// alert(temp);
roleACtrl.innerHTML = roleBCtrl.innerHTML;  
roleBCtrl.innerHTML = temp; 

//also swap id' stored in hidden form fields
temp = $('hiddenRoleIdA').value;
$('hiddenRoleIdA').value = $('hiddenRoleIdB').value;			                       
$('hiddenRoleIdB').value = temp;         			

}



function createRelation(){
var listBoxA = $(LISTBOXPREFIX+'A');	
var listBoxB = $(LISTBOXPREFIX+'B');	
var listBoxAssocs = $(LISTBOXASSOCSID);	
var topicIdA = listBoxA.options[listBoxA.selectedIndex].value;				
var topicIdB = listBoxB.options[listBoxB.selectedIndex].value;	
var assocId = listBoxAssocs.options[listBoxAssocs.selectedIndex].value;	
var roleIdA = $('hiddenRoleIdA').value;								
var roleIdB = $('hiddenRoleIdB').value;		
issueCreateTopicRelation(assocId, topicIdA, topicIdB, roleIdA, roleIdB);
			  	
showCreateAssocPanel(false);


//show the newly created relation in list
//with some delay so we dont try to show items that have not been saved yet
window.setTimeout('getReleations()',500);			
}			


function deleteRelation(assocId){				
issueDeleteRelation(assocId);	
window.setTimeout('getReleations()',500);			
		
}
		

function voteRelationUp(assocId,tagId){			
issueAssociationVote(assocId,true,tagId)			
getReleations();			
}			


function voteRelationDown(assocId,tagId){			
issueAssociationVote(assocId,false,tagId)			
getReleations();			
}


function getReleations(){				
var listBoxA = $(LISTBOXPREFIX+'A');	
var listBoxB = $(LISTBOXPREFIX+'B');				
var topicIdA = listBoxA.options[listBoxA.selectedIndex].value;				
var topicIdB = listBoxB.options[listBoxB.selectedIndex].value;	
getRelationsBetweenTopics(topicIdA, topicIdB); 			
}


//auto select the only row in listbox a if topic mapper was started with startup topic
function hihglighStartUpTopic(){			    
var listBoxA = $(LISTBOXPREFIX+'A');	
if(listBoxA){
	if(listBoxA.length>0){
	listBoxA.selectedIndex = 0;
	listboxClicked(listBoxA,'A');
	}  
 }
}


function textBoxKeyPressed(txtbox, listBoxId){	
if(txtbox.value.length > 0){ 				   	 	   	   	   
	getTagsStartingWithFromTopicMapper(txtbox.value, listBoxId);				     	     
}
//KeyDownHandler('buttonAddTagSearch');
} 



function getTagsStartingWithFromTopicMapper(strName,listboxId){
	new Ajax.Request('/ajax/tag/GetSuggestedTopicsPlain.aspx?q='+strName+'&listboxId='+listboxId+ts(),   
	{     
	   method:'get', onSuccess: function(transport)
	     {    
	        var res=transport.responseText || "No Response";                     
            if(!isErrorMsg(res)){
            
             	var nPos = res.indexOf("&items="); 
				if(nPos < 1) return;
				var strListboxId = res.substr(10, nPos-10);
				var strListBoxItems = res.substr(nPos+7); 											
							
				//clear listbox			
				selectBox = document.getElementById(LISTBOXPREFIX+strListboxId);
		
				while (selectBox.options.length > 0) {
					selectBox.options[0] = null;
				}
				
			    var arrItems = strListBoxItems.split("\n");
			    for(i=0; i<arrItems.length; i++)
			    {
					var arrItem = arrItems[i].split("&&");
					if(arrItem[1] != null && arrItem[0]!='undefined')
					{
					    selectBox.options[selectBox.options.length] = new Option(arrItem[1], arrItem[0]);						
					}
                }   
                
                
                 if(selectBox.options.length == 0){
                     getStyleObject('PanelCreateReleation').display = 'none'; 	
                     getStyleObject('PanelStartup').display = 'block'; 	
                     getStyleObject('PanelTagsSelectedOK').display = 'none'; 
                     if(strListboxId=='A')
                       tA=-1;
                       else
		            tB=-1;
                     
                     selectBox.selectedIndex = -1;
                 }else if(selectBox.options.length == 1){ 
                    selectBox.selectedIndex = 0;
                    //selectBox.focus();
              // alert(strListboxId);
                    listboxClicked(selectBox,strListboxId);
                 }else{
                    selectBox.selectedIndex = -1;
                 }                
            }
			else{msgErr(res);}                	
	     },onFailure:function(t){msgErr('Error '+t.status +' - '+t.statusText);}  
	}); 
}


function GetTagsPlainListing( topicId, listingType, listboxId, startUpTopic){ 	
	new Ajax.Request('/ajax/tagmapper/GetTagPlainListOption.aspx?topicId='+topicId +'&listing='+listingType+'&listboxId='+listboxId+'&startUpTopic='+startUpTopic+ts(),   
	{     
	   method:'get', onSuccess: function(transport)
	     {    
	        var res=transport.responseText || "No Response";                     
            if(!isErrorMsg(res)){
            	var nPos = res.indexOf("&items="); 
				if(nPos < 1) return;
				var strListboxId = res.substr(10, nPos-10);
				var strListBoxItems = res.substr(nPos+7); 				
				//clear listbox			
				selectBox = document.getElementById(LISTBOXPREFIX+strListboxId);
				//alert(selectBox);
				while (selectBox.options.length > 0) {
					selectBox.options[0] = null;
				}					
			    var arrItems = strListBoxItems.split("\n");
			    for(i=0; i<arrItems.length; i++)
			    {
					var arrItem = arrItems[i].split("&&");
					if(arrItem[1] != null && arrItem[0]!='undefined')
					{
					    selectBox.options[selectBox.options.length] = new Option(arrItem[1], arrItem[0]);						
					}
                }                     
                 if(selectBox.options.length == 0){
                     getStyleObject('PanelCreateReleation').display = 'none'; 	
                     getStyleObject('PanelStartup').display = 'block'; 	
                     getStyleObject('PanelTagsSelectedOK').display = 'none'; 
                     if(strListboxId=='A')
                       tA=-1;
                       else
		            tB=-1;                         
                     selectBox.selectedIndex = -1;
                 }else if(selectBox.options.length == 1){ 
                    selectBox.selectedIndex = 0;
                    //selectBox.focus();
              // alert(strListboxId);
                    listboxClicked(selectBox,strListboxId);
                 }else{
                    selectBox.selectedIndex = -1;
                 }                
            
            }
			else{msgErr(res);}                	
	     },onFailure:function(t){msgErr('Failed to load tags.<br>Error '+t.status +' - '+t.statusText);}  
	}); 
}



function getRelationsBetweenTopics(topicIdA,topicIdB){
	new Ajax.Request('/ajax/tag/GetRelationsBetweenTopics.aspx?topicidA='+topicIdA+'&topicidB='+topicIdB+ts(),   
	{     
	   method:'get', onSuccess: function(transport)
	     {    
	        var res=transport.responseText || "None";                     
            if(!isErrorMsg(res)){
                if(res.length > 0){			
			        changeObjectDisplayStyle('PanelRelationExists','block'); 			
			        document.getElementById('PanelRelationsList').innerHTML = res;		
		        }else{
		            changeObjectDisplayStyle('PanelRelationExists','none'); 	
			        document.getElementById('PanelRelationsList').innerHTML = '';
		        }
            }
			else{msgErr(res);}                	
	     },onFailure:function(t){msgErr('Error '+t.status +' - '+t.statusText);}  
	}); 
}


function GetRolesForAssoc(assocId){ 	
	new Ajax.Request('/ajax/GetRolesForAssoc.aspx?assocId='+assocId+ts(),{     
	   method:'get', onSuccess: function(transport){    
	        var res=transport.responseText || "None";                     
            if(!isErrorMsg(res)){
                var strPreview;				    
				var arrRoles = res.split("\n");						
				var arrRolesItem1 = arrRoles[0].split("&&");						
				var arrRolesItem2 = arrRoles[1].split("&&");						
                var listBoxA=$(LISTBOXPREFIX+'A');
                var listBoxB=$(LISTBOXPREFIX+'B');
				var textA =  listBoxA.options[listBoxA.selectedIndex].text;
				var textB =  listBoxB.options[listBoxB.selectedIndex].text;
				var nPos = textA.indexOf('(');
				if(nPos > 0){
					textA = textA.substr(0,nPos-1);
					//textA = textA.substr(0,textA.length-1);
				}
				nPos = textB.indexOf('(');
				if(nPos > 0){
					textB = textB.substr(0,nPos-1);
					//textB = textB.substr(0,textB.length-1);
				}			
				
			    strPreview = '<div class=\"smallText\">Relation preview:</div><table cellpadding="1" border=0>'
			       + '<tr><td align=\"center\">' + textA + '</td><td align=\"center\"><b><span id="roleA">' + arrRolesItem1[1] + '</span></b></td><td align=\"center\"> '+ textB +'. </td></tr>' 
			       + '<tr><td align=\"center\"> ' + textB + '</td><td align=\"center\"><b><span id="roleB">' + arrRolesItem2[1] + '</span></b></td><td align=\"center\"> ' + textA +'.</td></tr>'
			       +' <tr><td align=\"center\"><div class=\"smallText\">tag</div></td><td align=\"center\"><div class=\"smallText\">role</div></td><td align=\"center\"><div class=\"smallText\">tag</div></td></tr></table>' 
			       + '<input type="button" class=\"button\" id="ButtonRelationSwap" title=\"Preview relation with roles switched\" onclick="swapRoles();" value="Swap roles">&nbsp; '                  
			       + '<input type="button" class=\"button\" id="ButtonRelationCreateSave" onclick="createRelation();" value="Create">';                  
                                    
                $('hiddenRoleIdA').value = arrRolesItem1[0];                     	                   
                $('hiddenRoleIdB').value = arrRolesItem2[0];                    		                 
                           
                $('PanelAssocRolePreview').innerHTML = strPreview;                    
                new Effect.Appear('PanelAssocRolePreview', {duration:.1});                    
                
            }
			else{msgErr(res);}                	
	     },onFailure:function(t){msgErr('Error '+t.status +' - '+t.statusText);}  
	}); 
}
	

function issueTopicMerge(topicIdA, topicIdB){ 	
	new Ajax.Request('/ajax/tag/topicMerge.aspx?topicIdA='+topicIdA+'&topicIdB='+topicIdB+ts(),{     
	   method:'get', onSuccess: function(transport){    
	        var res=transport.responseText || "No Response";                     
            if(!isErrorMsg(res)){msg(res);}
			else{msgErr(res);}                	
	     },onFailure:function(t){msgErr('Error '+t.status +' - '+t.statusText);}  
	}); 
}

