// File: readXML.js

// Start function when DOM has completely loaded 
$(document).ready(function(){ 

	/* xml data using XMLHttpRequest subject to same origin browser policy */ 
	//$.ajax({url: "http://virtual.newtonfreelibrary.net/webapps/facts/repeaterXML.aspx", cache: false, success: function(xml){HTMLfromXML(xml,'fact');showDivs('fact');}});
	
	/* json data using XMLHttpRequest subject to same origin browser policy */ 
	//$.getJSON("http://virtual.newtonfreelibrary.net/webapps/facts/repeaterJSON.aspx", {}, function(json){HTMLfromJSON(json.facts.fact,"fact");showDivs('fact');});
	
	/* JSONP data retrived as parameters to somefunction that gets executed */ 
	$.getJSON("http://virtual.newtonfreelibrary.net/webapps/facts/factdata.aspx?output=jsonp&callback=?", {}, function(json){HTMLfromJSON(json.facts.fact,"fact");showDivs('fact');});

	
	$.get("./includes/blogs.xml",{},function(xml){
		HTMLfromXML(xml,'blog');
		var rand = Math.floor(Math.random()*10+1)
		//var element = $(xml).find('blogs blog[id='+rand+']');
		
		var elem = $("div.blog:eq("+rand+")");
		$("div.blog:eq("+rand+")").remove();
		
		$("div.blog").wrapAll("<div id='blogrest'></div>");
		$("#blog").prepend(elem);

	});
	
	var dt = new Date()
	$.get("./includes/db.xml?" + dt.getDate(),{},function(xml){
			HTMLfromXML(xml,'database');	
	});
});
 
 function ToggleExpansion(div, minHeight){
 	if($(div).css('height') == 'auto'){ $(div).css('height',minHeight);}
 	else{ $(div).css('height','auto');}
 	return false;
 }

function HTMLfromJSON(json, type){
	myHTMLOutput = '';
	
	// Run the function for each 'type' tag in the XML file
	$.each(json,function(f,ft) {
		//alert(ft.id);
		id = ft.id;
		
		title = ft.title;
		url = ft.url;

		fulltext = ft.fulltext;

		// Build row HTML data and store in string
		mydata = BuildHTML(id, title, url, fulltext, "fact");
		myHTMLOutput = myHTMLOutput + mydata;
	});
	 
 	$("#"+type).append(myHTMLOutput);
}
 
 function HTMLfromXML(xml,type){
 	myHTMLOutput = '';
 
 	// Run the function for each 'type' tag in the XML file
 	$(type,xml).each(function(i) {
 		
 		id = ""+$(this).attr("id");
 
 		
 		title = ""+$(this).find("title").text();
 		url = $(this).find("title").attr("url") || "";
 
 		fulltext = ""+$(this).find("fulltext").text();
 
 		// Build row HTML data and store in string
 		// for database of the month...
 		if (type == 'database') {
 		
 			year = ""+$(this).attr("year");
 			month = ""+$(this).attr("month");
 			var d = new Date();
 			var curr_month = d.getMonth() + 1; // js has 0 based array for months, so add one to match months
 			var curr_year = d.getFullYear();
 			//... only add the current month
 			if (year == curr_year  && month == curr_month) {
 				var urlInLib = ""+$(this).find("urlInLib").text();
 				var urlAtHome = ""+$(this).find("urlAtHome").text();
 				var urlInLib2 = ""+$(this).find("urlInLib2").text();
 				var urlAtHome2 = ""+$(this).find("urlAtHome2").text();
 				var showTitle = (""+$(this).find("title").attr("show") == 'true');
 				var residentsOnly = (""+$(this).find("urlAtHome").attr("residentsOnly") == 'true');
 				var residentsOnly2 = (""+$(this).find("urlAtHome2").attr("residentsOnly") == 'true');
 				if (!residentsOnly) {
 					var residentsOnly = (""+$(this).find("urlInLib").attr("residentsOnly") == 'true');
 				}
 				var imgUrl = ""+$(this).find("imageUrl").text();
 				var fulltext = ""+$(this).find("description").text();
 				mydata = BuildHTMLforDB(title, showTitle, urlInLib, urlAtHome, residentsOnly, urlInLib2, urlAtHome2, residentsOnly2, imgUrl, fulltext, type);
 				myHTMLOutput = myHTMLOutput + mydata;
 				//alert((""+$(this).find("urlAtHome").attr("residentsOnly") == 'true'));
 				$("#"+type).css('display', 'block');
 			}
 		}
 		// for other types of XML, add all elements
 		else if (type != 'database') {
 		mydata = BuildHTML(id, title, url, fulltext, type);
 		myHTMLOutput = myHTMLOutput + mydata;
 		}
 
 	});
  
  	$("#"+type).append(myHTMLOutput);
  		  	
}

 function getWidthAndHeight() {
    var possible_alert = "'" + this.name + "' is " + this.width + " by " + this.height + " pixels in size.";
    return true;
}
function loadFailure() {
    var possible_alert = "'" + this.name + "' failed to load.";
    return true;
}

 
 function BuildHTMLforDB( title, showTitle, urlInLib, urlAtHome, residentsOnly, urlInLib2, urlAtHome2, residentsOnly2, imgUrl, description, divclass){
	
	var myImage = new Image();
	myImage.name = imgUrl;
	myImage.onload = getWidthAndHeight;
	myImage.onerror = loadFailure;
	myImage.src = imgUrl;
	
	output = "<div style='text-align: center;margin: 0px auto; height:" + (myImage.height + 16) + "'>"
	urlForImage = "";
	if (urlAtHome != '') { urlForImage = urlAtHome;	}
	else { urlForImage = urlInLib; }
	
	if (imgUrl.length <= 0 || showTitle) {
		output += "<a href='" + urlForImage + "' title='" + title + "' style='font-weight:bold;'>" + title + "</a>";
	}
	if (imgUrl.length > 0) {
		output += "<br><br><a href='" + urlForImage + "' title='" + title + "'><img src='" + imgUrl + "' alt='" + title + "' border='0'></a>";
	}

	output += "</div>";
	
	output += "<div style='text-align: center;'>"
			
	if (urlAtHome == '') {
		output += "&nbsp;";
		//output += "<a href='http://bit.ly/tFHNDr'>Sign Up</a>";
		//output += "<a href='" + urlInLib + "'>" + title + "</a>";
		//output += "<span class='popup'> <a href='#'>*<span>In Library Only</span></a></span>";
		}
	else {
		output += "<a href='" + urlInLib + "'>In Library</a>";
		output += "&nbsp;";
		output += "<a href='" + urlAtHome + "'>Home Access</a>";
		if (residentsOnly) {
			output += "<span class='popup'> <a href='#'>*<span>Home access for this database is available only to Newton residents with a Newton library card number beginning 21323.</span></a></span>";
		}
	}
	
	
	if (urlAtHome2 != '' && urlInLib2 != '') {
		
		output += "<div>(Current users only: <a href='#' onClick='toggleVisibility(\"db2\"); return false;'>click here</a>)";
		output += "<div id='db2' style='display:none;'><a href='" + urlInLib2 + "'>In Library</a>";
		output += "&nbsp;";
		output += "<a href='" + urlAtHome2 + "'>Home Access</a>";
		if (residentsOnly2) {
			output += "<span class='popup'> <a href='#'>*<span>Home access for this database is available only to Newton residents with a Newton library card number beginning 21323.</span></a></span>";
		}
		output += "</div></div>";
	}
	//alert(description);
	//output += "</div>";
	output += "<div style='padding:5px 10px 10px 10px; text-align:left; font-weight:normal;'>" + description + "</div>";
	output += "</div>"; //</div>";
	
	return output;
}
 
 function BuildHTML(id, title, url, fulltext, divclass){
	output = "<div class='"+divclass+"'>";
	
	if (url.length > 1) output += "<a href='"+url+"'>" + title + "</a>"; // Check to see if there is a "url" attribute in the name field
	else output += title;	
	if (fulltext.length > 1) output += " <a style='font-style:italic; font-weight:normal;' href='http://virtual.newtonfreelibrary.net/webapps/facts/fact.aspx?showId="+id+"'>more...</a>";
	output += "</div>";
	
	return output;
}


function showDivs(type){
	$(document).ready(function(){
		
	$("div." + type + ":eq(0)").css('top','5px');
	
	var runtimeInterval = "rotation_interval_"+type;
	var blogId = 0;
	var factId = 0;
	
	var blogCount;
	var factCount;
	
	if(type == "blog"){
		blogCount = $("div." + type).size();
		rotation_interval_blog = setInterval(function(){rotate(type, blogCount, blogId++);},5000); //time in milliseconds
		$("#"+type).hover(
			function() { clearInterval(rotation_interval_blog);}, 
			function() { rotation_interval_blog = setInterval(function(){rotate(type, blogCount, blogId++);},5000); rotate(type, blogCount, blogId++); });
	}
	
	else if(type == "fact"){
		factCount = $("div." + type).size();
		rotation_interval_fact = setInterval(function(){rotate(type, factCount, factId++);},5000); //time in milliseconds
		$("#"+type).hover(
			function() { clearInterval(rotation_interval_fact);}, 
			function() { rotation_interval_fact = setInterval(function(){rotate(type, factCount, factId++);},5000); rotate(type, factCount, factId++); });
	}
	});

}
 
 function rotate(type, div_count, div_previous) {
   div_current = (div_previous + 1) % div_count;
   $("div." + type + ":eq(" + (div_previous % div_count) + ")").animate({top: -205},"slow", function() {
	 $(this).css('top','210px');
   });
   $("div." + type + ":eq(" + div_current + ")").show().animate({top: 5},"slow");
}
