// File: readXML.js

// Start function when DOM has completely loaded 
$(document).ready(function(){ 
	
	readFile();
	addLike();
});

function readFile() {
	//open XML and read
	$.get("/wp-content/plugins/likethisphoto/js/images.xml",{},function(xml){
		// Build an HTML string
		// Run the function for each image tag in the XML file
		$('image',xml).each(function(i) {
			myHTMLOutput = '<span class="leftalign">';
	 		//myHTMLOutput += '<br />';
			imgId = $(this).find("imageid").text();
			imgLike = $(this).find("liked").text();
			myHTMLOutput += imgLike;
			
			//myHTMLOutput += ' <a class="addLike">LIKE</a>';
			myHTMLOutput += ' *heart*</span>';

			$("#" + imgId).prepend(myHTMLOutput);
		});
	});	
}

// function to add a Like
function addLike() {
	//when the event tag a is triggered
	$(".addLike").bind("click", function(event){
		event.preventDefault();			   
		numoflike = 0;
		//variables that may be useful for later updates
		var parentId = $(this).parent().attr('id');
		//var parentIdText = $('#' + parentId).text();
		
		//parse string and grab the integer (number of people that like this image)
		var numoflike = parseInt($('#' + $(this).parent().attr('id')).text().replace(/[^\d\.]+/,''));
		//alert(numoflike);
		//replace the output by adding +1 to the LIKE and removing the link event tag <a>
		replaceHTMLOutput = $('#' + $(this).parent().attr('id')).html().replace(numoflike,numoflike+1);
		//replaceHTMLOutput = replaceHTMLOutput.replace('zero', '1');
		replaceHTMLOutput = replaceHTMLOutput.replace('<a href="" class="addLike">*heart* this photo</a>', '<img src="/wp-content/plugins/likethisphoto/js/heart-clicked.gif" class="leftalign" />');
		//replaceHTMLOutput = replaceHTMLOutput.replace('', '');
		$('#' + $(this).parent().attr('id')).html(replaceHTMLOutput);

		//add a thank you for voting feature
		$(".thankyou").stop().css("opacity", 1)
               .text("Thank You!")
               .fadeIn(30).fadeOut(1000);

		
		/*$.post("http://www.karinlouwerse.com/js/updatedata.php",
		{ id:$(this).parent().attr('id'), likes:numoflike },
		function(data){
			alert("Data Loaded: " + data);
		});*/
		
		$.post("/wp-content/plugins/likethisphoto/js/updatedata.php",
		{ id:parentId, likes:numoflike },
		function(data){
			//alert("Data Loaded: " + data);
		});
		
	});	
}