////var myArticles = new Array(9);

// holds the current user object
var user;

function regionClick(node, getResults) {
	var nodeId = node.item.nodeId[0];
	console.debug("regionClick() " + nodeId + " == " + currentRegion );
	
	if ( node == null || nodeId == _selectedTagId) {
		// do nothing, topics are already loaded
		console.debug("regionClick() region are already loaded");
		return false;
	}

	// set global variable and update link status
	updateRegion( nodeId );
	
	filterTopicNodes();

	if (getResults)
		topicGetArticles(node);
};

function updateRegion( nodeId ) {
	// set global variables
	currentRegion = nodeId
	_selectedTagId = nodeId;
	_selectedMapId = nodeId;	
	
	// update bookmark URL at top of page
	//document.getElementById("inforegion").innerHTML =  element.getAttribute("href");	
};

function topicClick( node, getResults ) {
	var nodeId = node.item.nodeId[0];
	if ( node == null || nodeId == _selectedTagDetailId) {
		// do nothing, topics are already loaded
		console.debug("topicClick() topics are already loaded");
		return false;
	}

	// set global variable and update link status
	updateTopic(nodeId);
	
	if (getResults)
		topicGetArticles(node);	
}

function updateTopic( nodeId ) {

	if ( nodeId != null ) {
		// set global variables
		currentTopic = nodeId;
		_selectedTagDetailId = nodeId;
		// update bookmark URL at top of page
		// REDO document.getElementById("infotopic").innerHTML = "/" + node.title;
	}
	//return false;
	
};

function topicGetArticles( node ) {
	console.debug( "topicGetArticles: _selectedTagId" + _selectedTagId + " _selectedTagDetailId: " + _selectedTagDetailId );

	var _contentResultsList  = dijit.byId("contentResultsList");
	var _contentViewMain  = dijit.byId("contentViewMain");
	///var _contentViewLibrary  = dijit.byId("contentViewLibrary");
	
	var currentRegionElement = document.getElementById(currentRegion);
	if ( currentRegionElement != null )
		var regionText = currentRegionElement.innerHTML;

	// commenting this out due to talk with Peter, he wants every topic to have even a small overview that explains what types of articles a user might find in the results. 
	//if ( element.href.indexOf('overview') > 0 ) {
		//alert( 'topic element has overview in the href. Topic: ' + topic  );
	//}
	
	// Update the article results text to show what the user is searching for
	//document.getElementById("articleresultstitle").innerHTML = "Results: " + regionText + " > " + element.innerHTML ;
	
	// set getting text...
	_contentViewMain.domNode.innerHTML = "<img  src='/land_manager/images/flower_load_animation.gif' title='retrieving results' alt='retrieving results' />";
	///_contentViewLibrary.domNode.innerHTML = "<img  src='/css/images/flower_load_animation.gif' title='retrieving results' alt='retrieving results' />";
	//var relatedaContainer = document.getElementById("relateddirect").innerHTML = "retrieving results...";
	//var relatedbContainer = document.getElementById("relatedsite").innerHTML = "retrieving results...";
	
	var _mainTabContainer = dijit.byId("mainTabContainer");
	//var _tab;// = dijit.byId("contentResultsList");

	if ( _tabSelected == null ) {
		_tabSelected = dijit.byId("contentResultsList");
	}
	
	//_tabSelected.controlButton.label = "david";
	//_tabSelected.label = "david";
	
	_mainTabContainer.selectChild(_tabSelected);		
	
	// get the current objects selected tag(s)
	TagApply.GetInfoObjectsByTagDetail( _selectedTagId, _selectedTagDetailId, _facetSortById, getTopicArticleResultsCallBack );
	

};





// Topics can be added to the end of this list
function GeoTag( name, longitude, latitude ) {
	this.id = id;
	this.title = title;
	this.url = url

	
	this.toString = function() { return '<li><a id='+this.id+' href=' + this.url + '>' + this.title + '</a></li>'; };
};

function getTopicArticleResultsCallBack( response ) {
	var _hasResults = true;
	var _contentResultsList  = dijit.byId("contentResultsList");
	var _contentViewMain  = dijit.byId("contentViewMain");
	///var _contentViewLibrary  = dijit.byId("contentViewLibrary");
	var _countResults = 0;
	var _countLibrary = 0;
	
	if (response.error != null) {
		console.debug(response.error);
		_hasResults = false;
	}
	var ds = response.value;
	
	var _divOutputResults = document.createElement("div");
	var _divOutputLibrary = document.createElement("div");
	
	if ( _hasResults == true && ds != null && typeof(ds) == "object" && ds.Tables[0] != null && ds.Tables[0].Rows.length > 0) {
		//var article = null;
		for(var i=0; i < ds.Tables[0].Rows.length; i++) {
			var row = ds.Tables[0].Rows[i];
			
			/// remove library and just put them into results
			///if ( row.Icon.indexOf("reference.png") > 0 ) {
			///	_divOutputLibrary.appendChild(createArticleResult(row));
			///	_countLibrary ++;
			///}
			///else {
				_divOutputResults.appendChild(createArticleResult(row));
				_countResults ++;
			///}

			//" - " + row.GeoTag + "</p></div>";				
				
			//if ( row.Icon.indexOf("overview") > 0 ) {
			//	article = new Article( row.ID, row.Title, row.FullPath, "savanna crc", "1/1/05", currentTopic, currentRegion);
			//}
		}

		//if ( article != null ) {
		//	getArticleFromResults( null, article, true );
		//}
	}
	else {
		_divOutputResults.innerHTML = "<p>No items available for this topic in your selected region at present. Try selecting the same topic for a nearby region, or at the State/Territory or National level</p>"
		_divOutputLibrary.innerHTML = "<p>No items available for this topic in your selected region at present. Try selecting the same topic for a nearby region, or at the State/Territory or National level</p>"	
	}
	
	setTabCounts(_contentResultsList, _countResults, _countLibrary);
	
	///_contentViewLibrary.domNode.innerHTML = "";
	///_contentViewLibrary.domNode.appendChild(_divOutputLibrary);
	
	_contentViewMain.domNode.innerHTML = "";
	_contentViewMain.domNode.appendChild(_divOutputResults);	
	
};

function setTabCounts(tabResults, count1, count2) {
	///tabResults.controlButton.domNode.firstChild.firstChild.innerHTML = 'Results  [' + count1 + '] Library  [' + count2 + ']';
	//tabResults.controlButton.domNode.firstChild.firstChild.innerHTML = 'Results  [' + count1 + ']';
};

function search(txtBox) {
	var _txtSearchBox = document.getElementById(txtBox);
	var _txtSearch = _txtSearchBox.value;
	var _contentSearch  = document.getElementById("contentSearchResults");
	var _ddInfoObjectSortBy = document.getElementById("ddInfoObjectSortBy");
	var _infoObjectSortById = _ddInfoObjectSortBy.options[_ddInfoObjectSortBy.selectedIndex].value;
	
	// select the contentArticle tab
	var _mainTabContainer = dijit.byId("mainTabContainer");
	var _content = dijit.byId("contentSearch"); 
	_mainTabContainer.selectChild(_content);	
	
	// sync both text boxes to have the same content based on which one was clicked.
	document.getElementById('txtSearchToolBar').value = _txtSearch;
	document.getElementById('txtSearch').value = _txtSearch;
	
	document.getElementById("contentSearchNumofResults").innerHTML = "Number of results:";
	_contentSearch.innerHTML = "<img src='/land_manager/images/flower_load_animation.gif' title='searching for results' alt='searching for results' />";
	
	TagApply.GetInfoObjectsBySearchTerm(_txtSearch, _facetSortById, _infoObjectSortById, search_CallBack);

}

function search_CallBack( response ) {
	var _hasResults = true;
	var _contentSearch  = document.getElementById("contentSearchResults");
	//var _countResults = 0;
	var _MAXCOUNT = 100;
	var _searchResultCount = 0;
	
	if (response.error != null) {
		console.debug(response.error);
		_hasResults = false;
	}
	var ds = response.value;
	
	//var _divOutputResults = document.createElement("div");
	
	if ( _hasResults == true && ds != null && typeof(ds) == "object" && ds.Tables[0] != null && ds.Tables[0].Rows.length > 0) {
	
		_searchResultCount = ds.Tables[0].Rows.length
		if ( _searchResultCount > _MAXCOUNT ) 
			_searchResultCount = _MAXCOUNT;	
			
		document.getElementById("contentSearchNumofResults").innerHTML = "Number of results: " + _searchResultCount;
	
		_contentSearch.innerHTML = "";
		for(var i=0; i < _searchResultCount; i++) {
			_contentSearch.appendChild(createArticleResult(ds.Tables[0].Rows[i]));
			//_countResults ++;
		}
	}
	else {
		_contentSearch.innerHTML = "<p>Your search did not produce any results.</p>"
	}
	
};

function createArticleResult(_row) {

	var _div = document.createElement("div");
	var _h3 = document.createElement("h3");
	var _a = document.createElement("a");
	
	dojo.addClass(_div, "result");
	
	_a.id = _row.ID;
	_a.href = _row.ID;
	_a.path = _row.FullPath;
	_a.innerHTML = _row.Title;// + " " + _row.GeoTag;
	
	attachArticleResultsHandlers(_div, _a, true);
	
	// connect pieces
	_div.appendChild(_h3);
	_h3.innerHTML = _row.Icon + "&nbsp;";
	_h3.appendChild(_a);
	
	if (_row.Summary != null && _row.Summary.length > 0) {
		var _p = document.createElement("p");
		var _text = document.createTextNode(_row.Summary);
		_p.appendChild(_text);
		_div.appendChild(_p);
	}	
	
	dojo.connect(_div, "onmouseover", function(){ dojo.addClass(_div, "articleHover"); });
	dojo.connect(_div, "onmouseout", function(){ dojo.removeClass(_div, "articleHover"); });
	
	return _div;
};


function filterTopicNodes() {
	var _topicsTree = dijit.byId("Topics"); 
	if (_topicsTree != null) {
		// get selected nodes to make them visible again
		TagApply.GetTagView(_selectedTagId, showTags_CallBack);
	}
};

function showTags_CallBack( response ) {
	if (response.error != null){
		console.debug(response.error);
		return;
	}

	// show only the filtered treeNodes
	var responseArray = response.value.split(";");	
	var _topicsTree = dijit.byId("Topics"); 
	
	dojo.forEach( _topicsTree.getDescendants(), function(elem) { 

		for (var i=0; i< responseArray.length; i++) {
			var widgetId = responseArray[i];
			if (elem.item.nodeId[0] == widgetId) {
				elem.domNode.style.display = '';
				break;
			}
			else {
				elem.domNode.style.display = 'none';
			}
			
		}
	});	
	
/*
	var _treeTopics = dijit.byId("Topics");
	
	function checkNode(node) {
		console.debug(node);
		//node.domNode.style.border = '1px solid red';
		node.domNode.style.display = '';
	}

	function failed(error) {
	         console.warn(error);
	}	

		//i++;
		//console.debug(_treeTopics.store.getValue(widgetId, "nodeId"));
		//console.debug(topicStore.getValue(widgetId, "nodeId"));
		//var elem = topicStore.getValue(widgetId, "nodeId");// dijit.byId(widgetId);

		///_treeTopics.store.fetchItemByIdentity({identity:"77462", onItem: checkNode, onError: failed});
		//_treeTopics.store.fetch({query:{nodeId:"77462"}, onComplete: checkNode, onError: failed});
		
	
*/	
};	


/// Get an article at the specified URL and loads it into div#article
// NOT USED
function getArticle( url, updateList ) {
	var _contentArticle = document.getElementById("contentArticle");
	var _articleUrl = "/view/index_basic.aspx?id=" + url;
	_contentArticle.innerHTML = "wow";// '<p><img src='/land_manager/images/flower_load_animation.gif' title='retrieving results' alt='retrieving results' /> <em>Loading </em></p>';
	

	var article = new Article( 200, url, url, "savanna crc", "December", currentTopic, currentRegion);
	
	// 9 if ( updateList ) user.updateRecentlyViewedArticles( article );
	
};
// END NOT USED


function attachArticleResultsHandlers(containingElement, element, updateRecentlyArticlesList) {
	var articleRegionId = currentRegion;
	var articleTopicId = currentTopic;
	var dateModified = "December";
	
	if ( element.getAttribute("path") ) {
		var path = element.getAttribute("path");
		articleRegionId = path.split(";")[0];
		articleTopicId = path.split(";")[1];
	}
	
	if ( element.getAttribute("dateModified") ) {
		dateModified = element.getAttribute("dateModified");
	}	
	
	var article = new Article( element.id, element.innerHTML, element.href, "savanna crc", "", articleTopicId, articleRegionId);
	
	if ( element.getAttribute("path") ) {
		article.fullPath = element.getAttribute("path");
	}	
	
	// don't parse links with the # in the href as the are anchor tags
	if ( element.href.indexOf("#") == -1 && containingElement != null ) {
		dojo.connect(containingElement, "onclick", function(e){ 
			e.preventDefault();
			getArticleFromResults( containingElement, article, updateRecentlyArticlesList );
			return false;			
		});	
	}
};

function getArticleFromResults(containingElement, article, updateRecentlyArticlesList) {
	// highlight the row
	if (_previousContainingElement != null)
		dojo.removeClass(_previousContainingElement, "resultSelected");
	if (containingElement != null) {
		dojo.addClass(containingElement, "resultSelected")	
		_previousContainingElement = containingElement;
	}
	
	getArticleById(article.id);
	
	// 9 if (updateRecentlyArticlesList) user.updateRecentlyViewedArticles( article );
};

function getArticleById(articleId) {
	// select the contentArticle tab
	var _mainTabContainer = dijit.byId("mainTabContainer");
	var _content = dijit.byId("contentArticle"); 
	_mainTabContainer.selectChild(_content);	
	
	var _contentArticle = document.getElementById("contentArticle");
	_content.setContent('<p><em>Loading ...</em></p>');	
	
	var deferred = dojo.xhrGet({
		url: "/view/index_basic.aspx?basic=true&id=" + articleId,
		timeout: 5000,
		//error: function(type, error){  },
		//back: function(){ this.appState.back(); },		
		//forward: function() { this.appState.forward(); },
		changeURL: articleId, 
		//appState: null,
		handleAs: "text"
	});

	//Add another callback for the success case
	deferred.addCallback(function(response){
		//Note that attaching a callback to the deferred
		//object after the original IO call will *not* receive the ioArgs object as a function
		//argument. There will only be one argument, the response argument.
		//Since original call wanted the response handled as text (handleAs: "text"),
		//response will be a text string in this case.

		_content.setContent(response); 
		parseArticleHrefTags(_contentArticle);

		//If you think there could be other callback handlers registered with this deferred, then
		//you MUST return the response object from this function, otherwise the error callbacks
		//will be called.
		return response;
	});

	//Add another callback for the error case
	deferred.addErrback(function(response){
		//Note that attaching a callback to the deferred
		//object after the original IO call will *not* receive the ioArgs object as a function
		//argument. There will only be one argument, the response argument.
		//In the errback case, response will be an Error object. If the error was a Deferred cancel()
		//call, then response.dojoType == "cancel". If the error was a request timeout (the time specified
		//in the IO call with the "timeout" property has elapsed), then response.dojoType == "timeout".
		console.error("Another error handler", response);

		_content.setContent("<p>Item not found</p>");

		//If you think there could be other callback handlers registered with this deferred, then
		//return response to propagate the same response to other callback handlers.
		return response;
	});

};

// loops through returned sets of articles and adds handlers to the links
function parseArticleHrefTags( container ) {
	var articleHrefs = dojo.query( 'a', container);
	for (i=0;i<articleHrefs.length;i++) {
		var hit = articleHrefs[i];
		
		if ( hit.href == null || hit.href.length < 1 )
			continue;
			
		// this is because IE 6 includes the port :80 stuff at the end of the host
		var hostUrl = hit.host.split(":");
		
		// check for landmanager domain name and do check for /view/[num]/[text].html stuff and this should be 
		// stripped and transformed into a nice internal link
		if (hit.host.indexOf("landmanager.") > -1 && hit.pathname.indexOf("view/") > -1) {
			
			hit.onclick = function() {

				openWindowInfoExplorer2(this);
				return false;
			}	
		}
		else if (window.location.host != hostUrl[0]) {
			hit.onclick = function() {
				openWindowInfoExplorer(this);
				return false;
			}
			//hit.target = "newBoabWindow";
		}
		
		// don't change target for internal anchors
		///if ( hit.href.indexOf("http") > -1 || hit.href.indexOf("#") == -1 ) {
		//if ( hit.href.indexOf(":") == -1 ) {
		//alert(hit.host);
		
	}
	
	
};

function openWindowInfoExplorer( hit ) {
	var windowHeight = docHeight - 150;
	var windowWidth = docWidth - 200;
	if ( windowHeight < 400 )
		windowHeight = 400;
	if ( windowWidth < 600 )
		windowWidth = 600;
	
	newWindow = window.open( hit.href, "newBoabWindow", "menubar=yes,resizable=yes,scrollbars=yes,status=yes,titlebar=yes,toolbar=yes,height=" + windowHeight + ",width=" + windowWidth  );
	if (newWindow != null)
		newWindow.focus();
	return false;
};

function openWindowInfoExplorer2( hit ) {

	var pathName = hit.pathname;
	
	// stupid opera doesn't have a leading / so we need to check and add it 
	if (pathName.charAt(0) != "/")
		pathName = "/" + pathName;
		
	var pathArray = pathName.split("/");
		
	//alert(pathArray[0] + " " + pathArray[1] + " " + pathArray[2]);
	//getArticleById(pathArray[2]);

	var windowHeight = docHeight - 150;
	var windowWidth = docWidth - 200;
	if ( windowHeight < 400 )
		windowHeight = 400;
	if ( windowWidth < 600 )
		windowWidth = 600;
	
	newWindow = window.open( "http://landmanager.org.au/view/index2.aspx?id="+pathArray[2], "newBoabWindow", "menubar=yes,resizable=yes,scrollbars=yes,status=yes,titlebar=yes,toolbar=yes,height=" + windowHeight + ",width=" + windowWidth  );
	if (newWindow != null)
		newWindow.focus();
	return false;
};



// END Tree click Functions


	function showHideNavigation() {
		var _bttnToggleMenu = document.getElementById("bttnToggleMenu");
		var _container = dijit.byId('container');	
		var _regionscontainer = dijit.byId('regionscontainer');	
		var _topicscontainer = dijit.byId('topicscontainer');	
		var _mainTabContainer = dijit.byId('mainTabContainer');	
				
		if (_bttnToggleMenu.innerHTML == 'hide menu') {
			_bttnToggleMenu.innerHTML = 'show menu';
			
			_regionscontainer.domNode.style.display = 'none';
			_topicscontainer.domNode.style.display = 'none';	
		}		
		else {
			_bttnToggleMenu.innerHTML = 'hide menu';
			
			_regionscontainer.domNode.style.display = 'block';
			_regionscontainer.domNode.style.visibility = 'visible';
			_regionscontainer.domNode.style.width = '180px';
			
			_topicscontainer.domNode.style.display = 'block';
			_topicscontainer.domNode.style.visibility = 'visible';
			_topicscontainer.domNode.style.width = '180px';
									
		}
		
		_container.layout();
	};


/* objects */

// Topics can be added to the end of this list
function Article( id, title, url, author, date, topicId, regionId ) {
	this.id = id;
	this.title = title;
	this.url = url
	this.author = author;
	this.date = date;
	// these two prperties are used for the "reveal this article in nav" button
	this.topicId = topicId;
	this.regionId = regionId;
	
	// this takes any additional arguments to the above constructor and addes them to an array of topics that this article can appear in
	this.articleTopics = function() {
		this.topics = new Array(arguments.length);
		for(i=0;i<arguments.length;i++){  
			this.topics[i] = arguments[i];
		}
	}	
	
	this.toString = function() { return '<li><a id='+this.id+' href=' + this.url + '>' + this.title + '</a></li>'; };
};

// returns a breadcrumb trail of where article appears in the tree
Article.prototype.getBreadcrumbTrail = function() {
	var regionsTree = document.getElementById("Regions");
	var selectedRegionNode = document.getElementById(currentRegion);
	
	return getTopParent(selectedRegionNode) ;
	
	//while ( selectedRegionNode.parentNode != regionsTree &&  )
	//	o = o.parentNode;
	//return o.parentNode;
	

	
};

function getTopParent( o ) {
	if ( o == null ) return "no region found";
	console.debug( "getTopParent(): " + o );
	var output = new Array();
	while (  o.getAttribute("href") ) {
		if ( o.getAttribute("href") != null  && o.getAttribute("href") ) {
			output.push( o.getAttribute("href") );
		}
		o = o.parentNode;
	}
	output.reverse();
	return o.getAttribute("href") + " > " + output.join(" > ");
};


function User( id ) {
	//new dojo.collections.Dictionary();
	//var _dictionary = new dojo.collections.Dictionary();
	this.id = id;
	//this.recentlyViewedArticles = new Array();
	//this.recentlyViewedArticles = new Hashtable(); - OLD
	//this.recentlyViewedArticles = _dictionary;
	
	this.addArticle = function( article ) {
		//alert( this.recentlyViewedArticles.size() );
	
		// return true if this article is not already added, else return false
		/*
		if ( this.recentlyViewedArticles.containsKey ( article.title ) ) {
			return true;
		}
		else {
			this.recentlyViewedArticles.add( article.title, article );
			return false;
		}
		*/
	}
		
	this.getArticles = function(){
	var output;
	for (i=0;i<this.articles.length;i++){
		for(j=0;j<this.articles[i].authors.length;j++){
			var authName = this.books[i].authors[j].firstName + " " +  this.books[i].authors[j].lastName;
			if(output.indexOf(authName)!=-1)continue;
			output+=";"+authName;
		}
	}
	return output;
	}
	
	// returns the user as a string to be used in the cookie save function
	this.toString = function() { return this.id + getArticles(); };
};


User.prototype.updateRecentlyViewedArticles = function( boabArticle ) {
	var contains = false;
	// add article to user's list
	contains = this.addArticle( boabArticle );	
	if ( contains ) return;
	
	var articleContainer = document.getElementById("viewedarticles");	
	var content = "";
	
	var li = document.createElement("li");
	var link = document.createElement("a");
	var trail = document.createElement("span");
	//var linkText = document.createTextNode('Ready!');
	var url = boabArticle.url;
	link.href = url;
	link.id = boabArticle.id;
	link.innerHTML = boabArticle.title;
	link.title = boabArticle.date;
	
	attachArticleResultsHandlers(li, link, false);
	
	if ( boabArticle.fullPath != null )
		trail.innerHTML = '<br />' + boabArticle.fullPath.split(";")[2];
	
	//link.onclick = function () {
	//	getArticle( url, false );
	//	currentArticleRegion = boabArticle.regionId;
	//	return false; 
	//}
	li.appendChild( link );
	li.appendChild( trail );
	
	if ( articleContainer.getElementsByTagName('LI').length > 0 ) {
		articleContainer.insertBefore( li, articleContainer.getElementsByTagName('LI')[0]);
	} else {
		articleContainer.appendChild( li );	
	}
	
	// update the article count
	/* REDO
	var contentPane = dijit.byId("accordian");
	if ( contentPane.children[2] != null ) {
		contentPane.children[2].labelNode.innerHTML = "Recently Viewed Articles (" + articleContainer.childNodes.length  + ")" ;
		
	}
	*/
};


User.prototype.save = function( value ) {
	var cookie = "region=" + currentRegion + "&topic=" + currentTopic + "&articles=" + value;
	document.cookie = cookie;
};

User.prototype.read = function() {
	// put code here to get user info to a cookie
};




// publish & edit functions
var _articleId = 0;
function publisArticle(articleId) {
	var answer = confirm ("Are you sure you wish to publish this Article? (Press Ok to publish)");
	
	if (answer){
		_articleId = articleId;
		TagApply.PublishArticle(_articleId, publisArticle_callback);
		
	}
};

function publisArticle_callback( res ) {
	if ( res.error != null ){
		console.debug(res.error);
		return;
	}
	
	var link = document.getElementById('publishLink'+_articleId);
	link.style.display='none';
	
};	
	
	
//var newWindow;
function openWindow(url, windowName, windowWidth, windowHeight) {
	//widthHeight = 'height=' + windowHeight + ',width=' + windowWidth;
	//newWindow = window.open(url, windowName, widthHeight, 'status=yes,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes');
	window.name = 'boab_main';
	
	newWindow = window.open(url, windowName, 'resizable=yes,scrollbars=yes,status=yes,width=' + windowWidth +',height=' + windowHeight);
	if (newWindow != null)
		newWindow.focus();
	return false;
};		
                
