// Provides the flashcard functionlity
// Useage: 
////console
//JQuery ready function. 
$(document).ready(function(){
	////console.log("ready funcion");
	
	var cards = flashcards();
	
	
	//hide the two answer divs
	hideAnswer();

	//register a onclick event handler for the next navigation
	$("#nextnav").click(function() { 
		////console.log("#nextnav.click");
		hideAnswer();
		cards.next(cardType); 
	});

	//register a onclick event handler for the prev navigation
	$("#prevnav").click(function() { 
		////console.log("#prevnav.click");
		hideAnswer();
		cards.prev(cardType); 
	});
	
	$('#item').swipe( function(event, info){
		////console.log("#prevnav.swipe ... direction = " + direction);
	    if(info.direction == "left"){
			hideAnswer();
			cards.next(cardType);
		}else if(info.direction == "right"){
			hideAnswer();
			cards.prev(cardType);		
		}
	 });
	
	//register a onclick event handler for display link.
	//toggles from card display to list display.
	$(".displaylink").click(function() { 
		////console.log(".displaylink");
		$(".flashlist").toggle();
		$(".flashcard").toggle();		
	});
	
	$(".arrow").click(function() { 
		////console.log(".arrow");
		cardType = $(this).attr("id");
		cards = flashcards();
		cards.init(cardType);
	});
	
	$("#clearlocalstorage").click(function() { 
		////console.log("#clearlocalstorage");
		localStorage.clear();
		alert("localStorage Cleared");
	});
	
	////console.log("near the end!");
	cards.init(cardType);
});

function hideAnswer(){
	//hide the two answer divs
	$("#answer").hide();
}

function toggleAnswer(){
	var thisId = $(this).parent().attr("id");
	$("#" + thisId + " #answer").slideToggle();
}

var cardsArr = new Array();

var flashcards = function(){
			
	return {		
		// Intializes the cards on page load. If the cards data (json) aleady exists in localStorage then the
		// page is restored to the last state. If there is no card data in the localStorage then a request will
		// be made to the /cards/show/<type>.json API. 
		// The cards json data is stored in the localStorage using the type as a key (e.g. type = kapgretop12). 
		// And the index for this card set to 0 in the localStorage.
		init: function(type){ 
			////console.log("init: type = " + type);
			var data = this.load(type);
			if(data == null){
				var path = "/cards/show/" + type + ".json";
				//Make Request to the cards JSON API. Callback function implmented here.
				$.getJSON(path, function(json_obj){ /* this is a callback function */ 
					try{ 
						 cards = flashcards();
						 cards.save(type, json_obj); /// save to localStorage
						 cards.initPage(type, json_obj["title"]); //Display Cards 
					}catch(err){ alert(err); }
				}); 
			}else{
				this.initPage(type, data["title"]); //Display Cards 
			}
		},
	

		/*
		 * Sets up the page with the page title and a set of cards
		 */
		initPage: function(type, title){
			////console.log("initPage: " + " " + type + " " + title);
			$("#pagetitle").text( title ); //set page title	
			this.current(type);  //Display current card
			$("#item #wordtitle").click(toggleAnswer);  //add event listener
			//build list and hide 
			$(".flashlist").hide();
			this.list(type);  
			
		},


		/*
		 * Changes the card to the next one from the index passed in
		 */
		display: function(item){
			////console.log("display(item): item = " + item);
			
			// Get wordlist data from local storage and make js object
			//var json_data = localStorage.getItem(type);
			//var data = JSON.parse(json_data).items;
			//alert("display: " + data["title"]);
	
			//alert("cardNext: " + data[ind]["word"] + " " + data[ind]["meaning"] + " " + data[ind]["examples"] + " " + data.length + " " + ind);
			//if( ind>=0 && ind<data.length ){
			if(item != null){
				$("#wordtitlelink").text((item["word"] != null)? item["word"].toString() : "");
				$("#wordmeaning").text((item["meaning"] != null)? item["meaning"].toString() : "");
				$("#wordexamples").text( (item["examples"] != null)? ("e.g. " + item["examples"].toString()) : "");
				//$("#iframe_dic").attr('src', "http://m.reference.com/d/search.html?q=" + item[ind]["word"].toString());
			}
		},
		

		current: function(type){
			//Get current index
			var index = parseInt(localStorage.getItem(type + "_index"));
			var data = this.load(type);
			this.display(data.items[index]);  //change card
		},

		next: function(type){
			//Get current index
			var index = parseInt(localStorage.getItem(type + "_index")) + 1;
			var data = this.load(type);

			//loop round to first if at end
			if(index == data.items.length)
				index = 0; //reset counter
			
			//change card
			this.display(data.items[index]);
			localStorage.setItem(type + "_index", index.toString());
		},

		prev: function(type){
			//Get current index
			var index = parseInt(localStorage.getItem(type + "_index"));
			var data = this.load(type);
			
			//loop round to last if at 0
			if(index == 0)
				index = data.items.length;
				
			
			//change card and save index to localstore is successful
			this.display(data.items[index]);
			localStorage.setItem(type + "_index", index.toString()); //set new index
		},
		
		
		// //Changes the card to the next one from the index passed in
		list: function(type){
			
			//remove any existing elements
			//if( $(".list") != null )
			//	$(".list").remove();
				
			// Get wordlist data from local storage and make js object
			//var json_data = localStorage.getItem(type);
		 	//var data = JSON.parse(json_data).items;
		 	var data = this.load(type);
		
		 	//alert("cardNext: " + data[ind]["word"] + " " + data[ind]["meaning"] + " " + data[ind]["examples"] + " " + data.length + " " + ind);
		 	if( data != null ){
				var items = data.items;
		 		for (var i = 0; i < data.items.length; i++){
					//alert("flying now .. " + i);
					
					var newId = "item_"+i;  //create new ID
						
					//create new clone 
		 			$("#item").clone(true).attr("id", newId).appendTo(".flashlist");
		
					$("#" + newId).removeClass("cards");
					$("#" + newId).removeClass("touch");
					$("#" + newId).addClass("list");
					$("#" + newId + " #wordtitle #wordtitlelink").text((items[i]["word"] != null)? items[i]["word"].toString() : "");
					$("#" + newId + " #answer #wordmeaning").text((items[i]["meaning"] != null)? items[i]["meaning"].toString() : "");
					$("#" + newId + " #answer #wordexamples").text( (items[i]["examples"] != null)? ("e.g. " + items[i]["examples"].toString()) : "");
					$("#" + newId + " #wordtitle").click(toggleAnswer);  //add event listener
					
					//$("#iframe_dic").attr('src', "http://m.reference.com/d/search.html?q=" + data[ind]["word"].toString());
				}
		 	}
		 },
		
		/**
		 * Save object to local array and persistently store a stringed 
		 * JSON versionin the local version.
		 */
		save: function(type, json_obj){
			////console.log("save(type, data), type = " + type);
			
			cardsArr[type] = json_obj;
			localStorage.setItem(type, JSON.stringify(json_obj));	//Save json data in localStorage (persistent)
			localStorage.setItem(type + "_index", "0"); // set index to 0. index key e.g. kapgretop12_index (persistent)
		},
		
		/*
		 * Load and return the data object. If the data is in the local array return that
		 * and if not get the stringed JSON version local storage and parse to object. 
		 */
		load: function(type){
			////console.log("load(type), type = " + type);
			
			var data = cardsArr[type];  //get data and if not into cardsArr
			if( data == null){
				////console.log("load(type): Object not in local array, get from local storage - type = " + type);
				var json_data = localStorage.getItem(type);
				data = JSON.parse(json_data);
				cardsArr[type] = data;
			}//else{ //console.log("load(type): Object in local array " + type); }
			
			return data;
		},
				
		clear: function(type){
			//alert("removeCards(type), type = ");
			localStorage.removeItem(type);
			localStorage.removeItem(type + "_index");
			location.reload(true);
		}
		
	};
}

////  for debugging /////

//window.addEventListener('storage', storage_handler, false);

//function storage_handler(evt)
//{
//   alert('The modified key was '+evt.key);
//    alert('The original value was '+evt.oldValue);
//    alert('The new value is '+evt.newValue);
//    alert('The URL of the page that made the change was '+evt.url);
//    alert('The window where the change was made was '+evt.source);
//}

