'use strict';
dojo.require("esri.dijit.Bookmarks");
dojo.require("dojo.cookie");

var storageName = 'HTF_bookmarks';
var useLocalStorage = supports_local_storage();

// source for supports_local_storage function:
// http://diveintohtml5.org/detect.html
function supports_local_storage() {
	try {
		return 'localStorage' in window && window['localStorage'] !== null;
	} catch( e ) {
		return false;
	}
}

function Bookmarks(args) {
	/*jshint validthis: true */
	var options = {
		position : {
			//top: '100px',
			//left: '100px',
			//bottom: '100px',
			//right: '100px'
		},
		center : true,
		id : 0
	};
	$.extend(options, args);
	this.options = options;
}

Bookmarks.prototype.init = function() {
	var bookmarks = new esri.dijit.Bookmarks({
		map : HTF.map,
		bookmarks : [],
		editable : true
	}, dojo.byId('winBookmarks'));
	bookmarks.startup();
	// Save new bookmarks in local storage, fall back to a cookie
	// If a cookie is used, it expires after a week
	dojo.connect(bookmarks, 'onEdit', refreshBookmarks);
	dojo.connect(bookmarks, 'onRemove', refreshBookmarks);

	// Look for stored bookmarks
	var bmJSON;
	if (useLocalStorage) {
		bmJSON = window.localStorage.getItem(storageName);
	} else {
		bmJSON = dojo.cookie(storageName);
	}

	if (bmJSON && bmJSON != 'null' && bmJSON.length > 4) {
		console.log('cookie: ', bmJSON, bmJSON.length);
		var bmarks = dojo.fromJson(bmJSON);
		dojo.forEach(bmarks, function(b) {
			bookmarks.addBookmark(b);
		});
	}
	
	function refreshBookmarks() {
		if (useLocalStorage) {
			window.localStorage.setItem(storageName, dojo.toJson(bookmarks.toJson()));
		} else {
			var exp = 7;
			// number of days to persist the cookie
			dojo.cookie(storageName, dojo.toJson(bookmarkss.toJson()), {
				expires : exp
			});
		}
	}

	function clearBookmarks() {
		var conf = confirm('Click OK to remove your map bookmarks.');
		if (conf) {
			if (useLocalStorage) {
				// Remove from local storage
				window.localStorage.removeItem(storageName);
			} else {
				// Remove cookie
				dojo.cookie(storageName, null, {
					expires : -1
				});
			}
			// Remove all user defined bookmarks
			// First get all bookmark names
			var bmNames = dojo.map(bookmarks.bookmarks, function(bm) {
				if (bm.name != 'Central Pennsylvania') {
					return bm.name;
				}
			});
			// Run removeBookmark
			dojo.forEach(bmNames, function(bName) {
				bookmarks.removeBookmark(bName);
			});
			alert('Bookmarks Removed.');
		}
	}
};