if (typeof window.console == 'undefined') {
	window.console = {
		info: function(){},
		debug: function(){},
		log: function(){}
	};
}

if (typeof window.console.debug == 'undefined') {
	window.console.debug = function() {}
}

$(document).ready(function() {

	$('[jumpOut]').livequery(function() {
		
		$(this).click(function(){
			window.location = $(this).attr('jumpOut');
			return false;
		}).addClass('link');
		
		$(this).hover(function(){
			$(this).addClass('hover');
		}, function(){
			$(this).removeClass('hover');
		});
	});


	$.history.init(LN.doJump);

	$('[jump]').livequery(function() {
		
		$(this).click(function(){
			LN.jump($(this).attr('jump'));
			return false;
		}).addClass('link');
		
		if ($(this).parent('#crumbs').length == 0) {
			$(this).hover(function(){
				$(this).addClass('hover');
			}, function(){
				$(this).removeClass('hover');
			});
		}
		
	});
	
	$('li:has(input[type="checkbox"])').livequery(function() {
		$(this).click(function() {
			$(this).find('input[type="checkbox"]').click();
		});
	}); 
	
	$('#deskCopies form').ajaxForm(function() {
		alert('Thankyou, we will contact you shortly.');
		LN.jump('home.teachers');
	});
	
	
	var doSubmitPassword = function() {
		LN.showResources($('#password .path').val(), $('#password .heading').val(), $('#password .password').val());
	};
	
	$('#password .submit').click(doSubmitPassword);
	
	$('#password .password').keydown(function(event) {
        if (event.keyCode==13) {
        	doSubmitPassword();
        }
    });

	//$('.teachers').click(function() {
	//	LN.askForPassword();
	//});
	
	$('.request').click(function() {
		$.modal.close();
		$('#request').modal({
			containerId: 'requestContainer'
		});
	});
	
	$('#buyBooks').click(function() {
		window.location = './store/';
		return false
	});
	
	$('a.quiz').livequery(function() {
		$(this).click(function() {
			LN.showQuiz($(this).attr('quiz'));
			return false;
		});
	});
	
	//$(".shadow").wrap("<div class='wrap1'><div class='wrap2'><div class='wrap3'></div></div></div>");
	
});

var LN = {};

LN.showQuiz = function(quiz) {
	console.debug('Showing quiz', quiz);
	
	var title = quiz.substr(quiz.lastIndexOf('/') + 1).replace('.js', '');
	
	$.get(quiz, {}, function(result, status) {
		console.debug(result);
		var questions = eval('{' + result + '}');

		var el = $('#quiz');
		
		el.empty();
		el.append('<h1>Quiz : ' + title + '</h1>');
		
		
		$.each(questions, function(i, q) {
			q.correct = q.answers[0];
			q.answers = shuffle(q.answers);
			
			console.debug(q.answers);
			
			var sortedAnswers = [];
			
			$.each(q.answers, function(i, a) {
				if (a.toLowerCase().indexOf('above') > -1) {
					sortedAnswers.push(a);
				} else {
					sortedAnswers.unshift(a);
				}
			});
			
			q.answers = sortedAnswers;
			
			q.correctIndex = q.answers.indexOf(q.correct);
		});
		
		var questionsTemplate = TrimPath.parseDOMTemplate("questionsTemplate");
		
		var result  = questionsTemplate.process({questions:questions, title:title || "Quiz"});
		
		
		el.append(result);
		
		var markButton = $('<button>Mark</button>');
		markButton.click(function() {
		
			
			var correct = 0;

			for (var i = 0; i < questions.length; i++) {
				var answer = el.find('input[name=' + i + ']:checked').val();

				console.debug(answer);
				var answerIndex;
				for(var j = 0; j < questions[i].answers.length; j++) {
					if (answer == questions[i].answers[j]) {
						answerIndex = j;
					}
					questions[i].answers[j] = {text: questions[i].answers[j]};
				}
				//console.debug(answerIndex);

				if (answer == questions[i].correct) {
					correct++;
					questions[i].answers[answerIndex].cls = "correct";
				} else {
					if (answer) {
						questions[i].answers[answerIndex].cls = "incorrect";
					}
					questions[i].answers[questions[i].correctIndex].cls = "actualCorrect";
				}
				
			}
			
			console.debug(correct, questions);
			//$.modal.close();
			el.empty();
			var questionsTemplate2 = TrimPath.parseDOMTemplate("questionsTemplateAnswered");
			el.append('<br/><button class="simplemodal-close">Close</button>');
			var result2  = questionsTemplate2.process({correct:correct,total:questions.length,questions:questions, title:title || "Quiz"});
			console.debug(result2);
			
			el.append(result2);
			el.append('<br/><button class="simplemodal-close">Close</button>');
			el.find('button').click(function(){$.modal.close();})
			
			$('#quiz').scrollTop(0);
			$('#quizContainer').scrollTop(0);
			el.scrollTop(0);
			
			
			/*el.modal({
				containerId: 'quizContainer'
			});*/
		
		});
		el.append(markButton);
		el.append('<br/><button class="simplemodal-close">Close</button>');
		$.modal.close();
		el.modal({
			containerId: 'quizContainer'
		});
	});
}

var shuffle = function(o){ //v1.0
	for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
};

LN.jump = function(url) {
	$.history.load(url);
}

LN.doJump = function(url) {
	if (!url) {
		url = 'home';
	}	
	
	console.debug('jumping to url', url);
	var crumbs = url.split('.');
	console.debug('split location : ', crumbs);
	
	
	var location = [];
	var node = LN.tree;
	
	var target;
	
	$.each(crumbs, function(i, crumb) {
		console.debug('checking crumb', crumb, node);
		
		if (node.children && node.children[crumb]) {
			console.debug('found child node', node.children[crumb]);
			node.children[crumb].id = crumb;
			location.push(node = node.children[crumb]);
			
			if (i == crumbs.length - 1) {
				console.debug("AT THE LAST!");
				target = $('#' + node.id);
				if (node.render) {
					node.render(target);
					delete node.render;
				}
			}
			
		} else {
			console.debug('didnt find child node, dynamic?');
			if (node.childRender && (target = node.childRender(crumb, $('#' + node.id)))) {
				console.debug("childrender successful");
				location.push(node.childNode(crumb));
			} else {
				console.debug("childrender not successful");
			}
			
		}
	});
	
	
	console.debug('ended up with location', location, target);

	// Breadcrumbs
	var crumbs = $('#crumbs').find('ul');
	// Kill the old children
	crumbs.empty();
	var curr = '';
	$.each(location, function(i, location) {
		curr += (curr?'.':'') + location.id;
		crumbs.append('<li><a href="#" jump="' + curr + '">' + location.name + '</a></li>');
	});

	// Hide the visible card, show the new one
	if (!target || (target && target.is(':hidden'))) {
		if ($('#content .card:visible').length > 0) {
			//$('#wiz').attr('src', 'images/wiz2.gif');
			setTimeout(function() {
				//$('#wiz').attr('src', 'images/wiz1.gif');
			}, 300);
			$('#buyBooks').fadeOut();
			$('#content .card:visible').animate({
				    height: 'hide',
				    opacity: 'hide'}, function(){
				(target ? target : $('#error')).animate({
				    height: 'show',
				    opacity: 'show'
				}, function() {
					$('#buyBooks').fadeIn();
				});
			});
		} else {
			(target ? target : $('#error')).animate({
				    height: 'show',
				    opacity: 'show'
				}, function() {
					setTimeout(function() {
						$('#buyBooks').fadeIn();
					}, 300);
					
				}
			);
		} 
	}
 
}

if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}

books = books.filter(function(book) {
	return book.resources;
});

var booksByISBN = {};
$.each(books, function(i, book) {
	if (typeof book.isbn != 'undefined') {
		booksByISBN[book.isbn] = book;
	}
});

books.sort(function(a,b) {
	return a.name > b.name;
});

var deskCopies = [];
$.each(books, function(i, book) {
	if (book.deskCopies) {
		deskCopies.push(book);
	}
});

var companies = {};
$.each(books, function(i, el) {
	console.debug(el);
	if (!companies[el.company]) {
		companies[el.company] = [];
	}
	companies[el.company].push(el);
	companies[el.company].sort(function(bookA, bookB) {
		if (!bookA.weight) {
			return bookA.weight<bookB.weight?-1:bookA.weight>bookB.weight?1:0;
		} else {
			return bookA.name<bookB.name?-1:bookA.name>bookB.name?1:0;
		}
	});
});

var companies2 = companies;
var companies = [];
$.each(companies2, function(i, el) {
	companies.push({
		name: i,
		books: el
	});
});
companies.sort(function(companyA, companyB) {
	return companyA.books.length<companyB.books.length?1:companyA.books.length>companyB.books.length?-1:0;
});




LN.resourceList = function(el, isbn, section) {
	if (resources[isbn] && resources[isbn][section]) {
		
		el.empty();
		
		el.append('<h1>Resources</h1>');
		
		var r = resources[isbn][section];

		$.each(r, function(heading, dirs) {
			
			if (heading != 'root') {
				el.append('<h2>' + heading + '</h2>');
			}

			var ul = $('<ul></ul>');

			$.each(r[heading], function(directory, x) {
				var item = $('<li>' + (directory=='quiz'?'Self-Test Exercises':directory) + '</li>');
				
				item.click(function() {
					LN.showResources(isbn + '/' + section + '/' + heading + '/' + directory, directory)
				});
				
				ul.append(item);
			});
			
			el.append(ul);
		});
		
		el.show();
	} else {
		el.hide();
	}
};

LN.showResources = function(path, heading, password) {
	
	// Teachers area
	if (!heading) {
		//if (password == teacherPassword) { // Don't bother you hax0r, everything is protected after here!
			LN.jump('home.teachers');
			$.modal.close();
		//} else {
		//	$.modal.close();
		//	$('#request').modal({
		//		containerId: 'requestContainer'
		//	});
		//	LN.jump('home');
		//}
		
		return;
	}
	
	var params = {
		path: path
	};
	
	if (password) {
		params.password = password;
	}
	$('body').css('cursor','wait');
	$.post('list.php', params, function(result, status) {
		$('body').css('cursor','auto');
		if (result.error) {
			if (result.error.toLowerCase().indexOf('wrong') > -1) {
				alert("Incorrect Password");
			}
			LN.askForPassword(path, heading);
		} else {
			var el = $('#resources');
			
			el.empty();
			el.append('<h1>' + (heading=='quiz'?'Self-Test Exercises':heading) + '</h1>');
			
			var ul = $('<ul></ul>');
			
			$.each(result, function(i, file) {
				var chunks = file.split('||');
				file = chunks[0];
				var fileDate = chunks[1];
				var ext = getExtension(file);
				console.debug("Heading : " + heading);
				if (heading == 'quiz') {
					ul.append('<li class="' + ext + '"><a href="#" class="quiz" quiz="data/resources/' + path + '/' + file + '">' + file.replace('.js', '') + '</a> (' + fileDate + ')</li>');
				} else {
					ul.append('<li class="' + ext + '"><a target="_new" href="data/resources/' + path + '/' + file + '">' + file + '</a> (' + fileDate + ')</li>');
				}
			});
			el.append(ul);
			el.append('<br/><button class="simplemodal-close">Close</button>');
			$.modal.close();
			
			el.modal();
			console.info(result);
		}
	}, 'json');
}

LN.askForPassword = function(path, heading){
	var el = $('#password');
	el.find('.path').val(path || '');
	el.find('.heading').val(heading || '');
	el.modal({
		containerId: 'passwordContainer'
	});
	el.find('.password').val('').focus();
}

LN.tree = {
	children: {
		home: {
			name: 'Home',
			children: {
				students: {
					name: 'Students',
					childRender: function(child, el) {
						el = $('#bookInfo');
						if (!booksByISBN[child]) {
							return false;
						}
						$.each(booksByISBN[child], function(key, val) {
							try {
								el.find('.' + key).text(val);
							} catch(e) {}
						});
						el.find('.cover img').attr('src', 'data/covers/250/' + child + '.jpg')

						LN.resourceList(el.find('.resources'), child, 'students');

						el.find('.text').text(' ').load('data/info/students/' + escape(child) + '.html');
						return el;
					},
					childNode: function(child) {
						return {
							id: child,
							name: booksByISBN[child].name
						}
					},
					render: function(el) {
						console.debug('rendering students', el);
						el.find('.bookwrap').empty();
						
						$.each(companies, function(i, company) {
							
							var ul = $('<ul class="booklist"></ul>');
						
							$.each(company.books, function(i, book) {
								console.debug('rendering', book.name);
								ul.append('<li jump="home.students.' + book.isbn + '"><img src="data/covers/small/' + book.isbn + '.jpg"/><br/>' + book.name + '</li>');
							});
							
							el.find('.bookwrap').append('<h2>' + company.name + '</h2>');
							el.find('.bookwrap').append(ul);
							el.find('.bookwrap').append('<div style="clear:both"></div>');

						});
					}
				},
				teachers: {
					name: 'Teachers',
					children: {
						deskCopies: {
							name: 'Desk Copies',	
							render: function(el) {
								console.debug('rendering desk copies', el);
								var ul = el.find('ul');
								$.each(deskCopies, function(i, book) {
									if (!book.deskCopies) {
										return;
									}
									console.debug('rendering', book.name);
									ul.append('<li><input type="checkbox" id="dc' + book.isbn + '" value="' + book.isbn + '"/><label for="dc' + book.isbn + '">' + book.name + '</label></li>');
								});
							}
						}
					},
					childRender: function(child, el) {
						el = $('#bookInfo');
						if (!booksByISBN[child]) {
							return false;
						}
						$.each(booksByISBN[child], function(key, val) {
							try {
								el.find('.' + key).text(val);
							} catch(e) {}
						});
						el.find('.cover img').attr('src', 'data/covers/250/' + child + '.jpg')

						LN.resourceList(el.find('.resources'), child, 'teachers');

						el.find('.text').text(' ').load('data/info/teachers/' + escape(child) + '.html');
						return el;
					},
					childNode: function(child) {
						return {
							id: child,
							name: booksByISBN[child].name
						}
					},
					render: function(el) {

						console.debug('rendering teachers', el);
						el.find('.bookwrap').empty();
						
						$.each(companies, function(i, company) {
							
							var ul = $('<ul class="booklist"></ul>');
						
							$.each(company.books, function(i, book) {
								console.debug('rendering', book.name);
								ul.append('<li jump="home.teachers.' + book.isbn + '"><img src="data/covers/small/' + book.isbn + '.jpg"/><br/>' + book.name + '</li>');
							});
							
							el.find('.bookwrap').append('<h2>' + company.name + '</h2>');
							el.find('.bookwrap').append(ul);
							el.find('.bookwrap').append('<div style="clear:both"></div>');

						});
					}
				}
			}	
		}
	}
};

function getExtension(file) {
	return file.substring(file.lastIndexOf('.') + 1);
}

if (typeof console == 'undefined') {
	window.console = {
		debug: function(){},
		info: function(){}
	}
}

if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}



