var pageUrl = "";
var cart, wishlist;
var sourcedata, data;
var restore = false;
var zoom = true;
var pagesize = 10;
var selectedMenuItem;
var zoom = true;
var subjectcode;
var felo = {fel:false,stack:function(){}};
var app;
var slideshow = true;
var google_loaded = false;
var widgets = [];
var checkout = null;
var fluxProcessor;
var search;
// always load google books with error handler in case it's not available
try {
	google.load("books", "0");
	google.setOnLoadCallback(function() {
		google_loaded = true; 
	});
} catch(e) {
}

dojo.subscribe("/dojo/hashchange", app, function(){
	console.log("hash: "+dojo.hash())
	if(restore) {
		console.log("restore")
		restore = false;
		return;
	}
	app.setContent(dojo.hash());
});

// simple globals for flipping cart button states
// TODO: this should be custom button behavior
function setAddImg(node) {
	var imgs = dojo.query("img",node).forEach(function(img) {
		img.src = img.src.replace(".png","_add.png");
	});
}
function setDefImg(node) {
	var imgs = dojo.query("img",node).forEach(function(img) {
		img.src = img.src.replace("_add.png",".png");
	});
}
// convert local setters to globals
function addToCart(code,editiontype_id,copies){
	if(!cart || !code || !editiontype_id) return;
	copies = (copies!=undefined?copies:1);
	console.log(copies);
	cart.update({
		rm:'update',
		copies:copies,
		edition:editiontype_id,
		bookid:code
	},function(items){
		console.log("cart updated")
		console.log(items)
		if(copies<=1) cart.reload(items);
		if(cart.active) {
			cart.updateFooter();
			app.tabbedApp.tabs["order"].setContent();
		}
	});
}
function removeFromCart(code,editiontype_id){
	console.log(code,editiontype_id)
	if(!cart || !code || !editiontype_id) return;
	cart.update({
		rm:'update',
		copies:0,
		edition:editiontype_id,
		bookid:code
	},function(items){
		cart.reload(items);
		if(cart.active) {
			cart.updateFooter();
			app.tabbedApp.tabs["order"].setContent();
		}
	});
}
function addToWishlist(code){
	console.log(wishlist)
	if(!wishlist || !code) return;
	wishlist.update({
		rm:'update',
		copies:1,
		bookid:code
	},function(items){
		wishlist.reload(items);
		if(wishlist.active) app.tabbedApp.tabs["wishlist"].setContent();
	});
}
function removeFromWishlist(code){
	wishlist.update({
		rm:'update',
		copies:0,
		bookid:code
	},function(items){
		wishlist.reload(items);
		if(wishlist.active) app.tabbedApp.tabs["wishlist"].setContent();
	});
}

// main search function
// note that setting state hash will also work
function doSearch(form) {
	if(!form) {
		var s = dijit.byId("search");
		search.query = s.get("value");
		search.fields = ["code","title","subtitle","desc","author","isbn","keyword"];
		search.range = "any";
	}
	search.active = true;
	var query = {
		q: search.query,
		f: search.fields,
		r: search.range
	};
	var hash = dojo.objectToQuery(query);
	hash = "catalog/search/"+hash;
	console.log(hash)
	// to be able to execute same search again:
	// - set location hash to something else
	// - set restore to true so the listener won't pick up
	// - replace the set location to the hash so listener will pick it up
	restore = true;
	window.location.hash = "";
	window.location.replace(pageUrl+"#"+escape(hash));
}

// google viewer functions
// will load the viewer when it is available,
// returns deferred announcing if it is or not
// overlaps with viewerAvailable, however
// this will actually load the preview and style the container
var loadViewer = function(editions){
	var d = new dojo.Deferred();
	var viewer = new google.books.DefaultViewer(app.tabbedApp.tabs["preview"].domNode);
	var cnt = 0;
	var isbns = [];
	dojo.forEach(editions,function(n){
		cnt++;
		isbns.push("ISBN:"+n.isbnworld);
		isbns.push("ISBN:"+n.isbnusa);
	});
	viewer.load(isbns,function(){
		d.callback(false);
	},function(){
		app.tabbedApp.tabs["preview"].domNode.style.width = "auto";
		app.tabbedApp.tabs["preview"].domNode.style.height = "100%";
		setTimeout(function(){
			viewer.resize();
		},10);
		d.callback(true);
	});
	return d;
};
//returns a deferred announcing any of the edition
//ISBNs to be available or not asynchronously
function viewerAvailable(editions) {
	var d = new dojo.Deferred();
	var cnt = 0;
	var isbns = [];
	dojo.forEach(editions,function(n){
		cnt++;
		isbns.push(n.isbnworld);
		isbns.push(n.isbnusa);
	});
	return dojo.io.script.get({
        url: "http://books.google.com/books",
        callbackParamName: "callback",
        content: {
			jscmd:"viewapi",
			bibkeys:"ISBN:"+isbns.join(","),
			callback:"callback"
        },
        load: function(res) {
        	console.debug(res);
        	for(var i in res){
	        	if(res[i].embeddable) return true;
        	}
        	return false;
        },
        error: function(error) {
        	console.debug(error);
        }
    });
}
// main google preview function
// called from configuration
// will load either of the functions above
// according to preload flag
// and return its deferred
function googlepreview(preload,doi) {
	// if load returns deferred, xhrPost returns deferred from the function
	// otherwise it returns the data from xhrPost
	var d = dojo.xhrPost({
		url:"list/isbn/"+doi,
		handleAs:"json",
		load:function(res,io){
			if(preload) {
				return viewerAvailable(res.edition);
			} else {
				return loadViewer(res.edition);
			}
		}
	});
	return d;
};
// generic iframe in tab loader
function openIframe(url,tab) {
	var d = new dojo.Deferred();
	var iframe = dojo.create("iframe",{
		style:"width:100%;height:100%;padding:0;margin0;border:none",
		src:url,
		frameborder:"no"
	},app.tabbedApp.tabs[tab].domNode);
	d.callback(true);
	return d;
}

// global series/title/article content loaders
// basically for formatting db properties to human-friendly hash
// series doi+type to hash
function viewseries(seriesdoi,seriestype) {
	var series;
	switch(seriestype.toLowerCase()) {
		case "book":
			series = "books";
			break;
		case "software":
			series = "software";
			break;
		case "journal":
		case "yearbook":
			series = "journals";
	}
	var hash = "catalog/"+series+"/"+seriesdoi;
	//app.tabbedApp.setContent(hash,true);
	window.location.hash = hash;
}
// title doi+seriestype to hash
function viewtitle(titledoi,seriestype) {
	var series;
	switch(seriestype.toLowerCase()) {
		case "book":
			series = "books";
			break;
		case "software":
			series = "software";
			break;
		case "journal":
		case "yearbook":
			series = "journals";
	}
	var hash = "catalog/"+series+"/"+titledoi;
	window.location.hash = hash;
}
// article doi+seriestype to hash
function viewarticle(articledoi,seriestype,tab) {
	var series;
	switch(seriestype.toLowerCase()) {
		case "book":
			series = "books";
			break;
		case "software":
			series = "software";
			break;
		case "journal":
		case "yearbook":
			series = "journals";
	}
	var hash = "catalog/"+series+"/"+articledoi;
	if(tab) hash+="/"+tab;
	window.location.hash = hash;
}

// global person/subject content loaders
// checks for code and converts to hash
// TODO: these me actually be called straight from XSL
// also, it may be possible to use a URL hash directly!
function viewperson(code) {
	if(!code || code==="") return;
	var hash = "catalog/persons/"+code;
	window.location.hash = hash;
}
function viewsubject(code) {
	if(!code || code==="") return;
	var hash = "catalog/subjects/"+code;
	window.location.hash = hash;
}

function setFilter(id,set) {
	// default to true, set to false to turn off filters
	if(set==undefined) set = true;
	if(id!="all") {
		var fb = dijit.byId(id);
		if(fb) fb.set("checked",set);
	} else {
		var fba = dijit.byId("filter_all");
		if(fba) fba.set("checked",true);
	}
}

function killFel(e) {
	felo.kill();
}

dojo.require("dojo.parser");
dojo.ready(function() {
	// init search properties
	search = new benjamins.Search();
	dojo.parser.parse();
	var fp = dojo.byId("fluxProcessor");
	if(fp) {
		var sess = dojo.attr(fp,"sessionkey");
		console.log(sess)
	    Flux._path = "/Flux";
	    Flux.init(sess, dojo.hitch(fluxProcessor,fluxProcessor.applyChanges));
	    dojo.subscribe("/xf/ready", function(){
	        fluxProcessor.skipshutdown=true;
	    });
	}
	app = new benjamins.App({
		tabbedApp: dijit.byId("content")
	});
	//felo.init();
	if(dijit.byId("search")) {
		dojo.connect(dijit.byId("search").domNode,"onkeypress",function(e){
			if(e.charOrCode == dojo.keys.ENTER) {
				doSearch();
				dojo.stopEvent(e);
			}
		});
	}
	dojo.style("mainBorderContainer","backgroundColor","transparent");
	dojo.xhrPost({
		handleAs:"json",
		url:"interface",
		load:function(res,io) {
			sourcedata = res.data;
			// clone data for later use
			data = dojo.clone(sourcedata);
			app.startup();
			checkout = app.checkout;
			var hash = dojo.hash();
			console.log("start with hash "+hash)
			if(!hash) hash = "home";
			if(dojo.hash()==hash) app.setContent(hash);
			dojo.hash(hash);
			setTimeout(function(){
				dojo.fadeOut({node:"loading",duration:1000,onEnd:function(){
					dojo.style("loading","display","none");
				}}).play();
			},200);
		}
	});
});

var xfDeferred = {};
var xformLoaded = function(id) {
	// make sure the DOM is moved
	var xfc = dojo.byId("xformContainer");
	var dest = app.tabbedApp.tabs[id];
	if(!xfc || !dest) return;
	dest.set("content","");
	dojo.query(">",xfc).forEach(function(node){
    	dest.domNode.appendChild(node);
	});
	xfc.innerHTML = "";
	dojo.style(xfc,"display","none");
	if(xfDeferred[id]) xfDeferred[id].callback(true);
}
