var Cookie = {
	set: function(name, value, daysToExpire) {
		var expire = '';
		if (daysToExpire != undefined && daysToExpire != null) {
			var d = new Date();
			d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
			expire = '; expires=' + d.toGMTString();
		}
		return (document.cookie = escape(name) + '=' + escape(value || '') + expire + '; path=/');
	},
	get: function(name) {
		var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
		return (cookie ? unescape(cookie[2]) : null);
	},
	erase: function(name) {
		var cookie = Cookie.get(name) || true;
		Cookie.set(name, '', -1);
		return cookie;
	},
	accept: function() {
		if (typeof navigator.cookieEnabled == 'boolean') {
			return navigator.cookieEnabled;
		}
		Cookie.set('_test', '1');
		return (Cookie.erase('_test') === '1');
	}
};

function TravelPlanner() {
	
	this.debug = true;
	this.token = null;
	this.cookieName = 'travelPlannerToken';
	this.cookieTime = 90;
	this.buttonID = 'wishlistButton';
	this.targetID = 'travelPlanner';
	this.itemID = null;
	this.items = null;
	this.addImage = '/images/components/travelplanner/addGrey.png';
	this.tickImage = '/images/components/travelplanner/inGrey.png';
	this.transport = null;
	this.wsBase = '/ws/travelplanner.svc/';
	
	this.init = function(){
		this.log('Loading travel planner');
		// see if there's a token cookie
		this.getToken();
		this.log('Token: ' + this.token);
		
		// attach the sign in box to the target
		$(this.targetID).observe('click', function(ev){
			if(this.token == null) {
				ev.stop();
				this.showOverlay('enquire');
			}
		}.bind(this));
		
		// get the ID of the current item
		if($('travelPlannerID')) {
			this.itemID = (document.all) ? $('travelPlannerID').innerText : $('travelPlannerID').textContent;
			this.log('itemID: ' + this.itemID);
			if(this.itemID != null) {
				var title = $$('h2.pageTitle')[0];
				if(title) {
					this.log('inPlanner: ', this.inPlanner());
					if(!this.inPlanner()) {
						var button = new Element('img', { 'id': this.buttonID, 'src': this.addImage });
						button.observe('click', this.saveItem.bind(this));
					} else {
						var button = new Element('img', { 'id': this.buttonID, 'src': this.tickImage });			
					}
				
					button.show();
					this.log('Adding button');
					title.insert(button);
				}
			}        }
		
		this.log('Getting items');
		this.getItems();
	}
	this.log = function(msg){
		if(this.debug) {
			console.log(msg);
		}
	}
	this.isValidEmail = function(email){
		//^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$
		
		var reg = new RegExp('^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$');
		return reg.test(email);
	}
	this.inPlanner = function() {
	    this.log('in planner: ' + this.items + ' (' + this.itemID + ')');
	    if (this.items == null) {
	        return false;
	    } else {
	        return (this.items.indexOf(this.itemID) !== -1) ? true : false;
	    }
	}
	this.getItems = function() {

	    if (this.token != null) {
	        var now = new Date();
	        var stamp = now.getDate() + now.getMonth() + now.getHours() + now.getMinutes() + now.getSeconds() + now.getMilliseconds();
	        url = '/ws/travelplanner.svc/getitems/' + stamp + "/" + this.token;
	        new Ajax.Request(url, {
	            method: 'get',
	            onSuccess: function(transport) {
	                this.log('get items success status: ' + transport.status);
	                if (204 !== transport.status) {
	                    items = transport.responseXML.documentElement.getElementsByTagName('GetItemsResult')[0].childNodes[0].nodeValue;
	                    this.log('items: ' + items);
	                    this.log('items length: ' + items.length);
	                    if (items.length != 0) {
	                        this.items = items.split('|');
	                        if (this.inPlanner()) {
	                            this.log('In planner');
	                            if ($(this.buttonID)) {
	                                $(this.buttonID).src = this.tickImage;
	                            } else {
	                                this.log('No button found');
	                            }
	                        } else {
	                            this.log('Not in planner');
	                        }
	                    } else {
	                        this.items = '';
	                    }
	                } else {
	                    this.items = '';
	                }

	                this.updateCounter();
	            } .bind(this),
	            onFailure: function(transport) {
	                this.log('error status: ' + transport.status);
	                this.items = 'fail';
	                this.updateCounter();
	            } .bind(this)
	        });
	    } else {
	        this.items = null;
	        //this.updateCounter();
	    }
	}
	this.updateCounter = function() {
	    openLink = $('travelPlanner');
	    if (!openLink) {
	        this.log('No open link');
	        return false;
	    }
	    switch (this.items) {
	        case 'fail':
	            openLink.update('Travel Planner');
	            break; 
	        case 0:
	        case null:
	            openLink.update('Travel Planner (0 items)');
	            break;
	        case 1:
	            openLink.update('Travel Planner (1 item)');
	            break
	        default:
	            openLink.update('Travel Planner (' + this.items.length + ' items)');
	            break
	    }
	}
	// prompts for an email then passes on to the original action
	this.showOverlay = function(action){
		
		// create the overlay
		if($('travelPlannerOverlay')) {
			var overlay = $('travelPlannerOverlay');
		} else {
			var overlay = new Element('div', {
				'id': 'travelPlannerOverlay'
			});
		}

		// set the overlay HTML
		overlay.update('');
		var frame = new Element('div', {'class': 'internal'});
		var close = new Element('a', {
			'id': 'close',
			'href': '#',
			'title': 'Close this box'
		}).update('Close');
		var instructions = new Element('div', {'class': 'about'}).update('<h2>Welcome to the Travel Planner</h2><p>Our Travel planner is designed to help you plan your trip. As you browse our site, clicking the \'Add to Planner\' button will save this item to your list.</p><p>You can log in from any computer to view your list using just your email address.</p>');
		var form = new Element('form', {
			'class': 'signin',
			'action': '',
			'method': 'POST'
		}).update('<h2>Enter your email to continue...</h2><input type="string" name="tpEmail" id="tpEmail" /><input type="submit" id="tpSubmit" value="Go &#187;" /><div class="field"><input type="checkbox" id="shared" /><label for="shared">I\'m on a shared or public computer<br /><p class="helper">If you tick this, you\'ll be prompted for your email address every time you use the planner.</p></label></div><div class="messages" style="display: none">&nbsp;</div>')
		frame.insert(close);
		frame.insert(instructions);
		frame.insert(form);
		overlay.insert(frame);
//		overlay.update('<div class="internal"><a id="close" href="#" title="Close this box">Close</a><div class="about"><h2>About the Travel Planner</h2><p>When you add pages to your Travel Planner, they are saved for future reference.</p></div><form class="signin" action="" method="POST"><h2>Sign In</h2><input type="string" name="tpEmail" id="tpEmail" /><input type="submit" id="tpSubmit" value="Sign in &#187;" /><div class="messages" style="display: none">&nbsp;</div></form></div>');
		
		// calculate the position of the overlay
		width = 660;
		height = null;
		viewportWidth = document.viewport.getWidth();
		viewportHeight = document.viewport.getHeight();
		pTop = 200;
		pLeft = (viewportWidth / 2) - (width / 2);
		overlay.setStyle({
			'top': pTop + 'px',
			'left': pLeft + 'px'
		});

//		overlay.down('form').observe('submit', this.signIn.bindAsEventListener(this, action));
		overlay.down('form').observe('submit', function(ev){
			ev.stop();
			this.signIn(action);
		}.bind(this));
		overlay.down('#close').observe('click', function(ev) {
			ev.stop();
			this.hideOverlay();
		}.bind(this));

		// add the overlay to the document
		$$('body')[0].insert(overlay);
		overlay.show();
		
	}
	this.hideOverlay = function() {
		if($('travelPlannerOverlay')) {
			$('travelPlannerOverlay').hide();
		}
	}
	this.signIn = function(ev, action, shared) {
		shared = $('shared').checked;
		overlay = $('travelPlannerOverlay');
		if(!this.isValidEmail($F('tpEmail'))) {
			overlay.down('.messages').addClassName('error').update('Please enter a valid email').show();
			return false;
		}
		url = '/ws/travelplanner.svc/gettoken/' + escape($F('tpEmail'));
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				this.token = transport.responseXML.documentElement.getElementsByTagName('GetTokenResult')[0].firstChild.data;
				overlay.update('<div class="internal"><h2>Thanks</h2><p>You can access your travel planner at any time using the link at the top right of the page</p><p><a href="#">Click here to close this message</a></p></div>');
				overlay.observe('click', function(ev){
					ev.stop();
					overlay.remove()
				}.bind(this));
				this.getItems();
				// save token to a cookie
				if(shared) {
					// user is on a shared machine - cookie is a session cookie
					Cookie.set(tp.cookieName, tp.token, null);
				} else {
					Cookie.set(tp.cookieName, tp.token, tp.cookieTime);
				}
				if(action == 'save') {
					this.saveItem();
				}
				if(action == 'enquire') {
					window.location = $(this.targetID).getAttribute('href');
				}
			}.bind(this),
			onFailure: function(transport) {
				messageBox = overlay.down('.messages');
				messageBox.addClassName('error').update('There was an error. Please try again');
				messageBox.show();
			}.bind(this)
		});
	}
	this.hideOverlay = function(){
		if($('travelPlannerOverlay')) {
			$('travelPlannerOverlay').hide();
		}
	}
	this.emailPrompt = function(action){
		
		$$('div#travelPlannerOverlay form')[0].observe('submit', function(ev){
			ev.stop();
			url = '/ws/travelplanner.svc/gettoken/' + escape($F('tpEmail'));
			new Ajax.Request(url, {
				method: 'get',
				onSuccess: function(transport) {
					this.token = transport.responseXML.documentElement.getElementsByTagName('GetTokenResult')[0].firstChild.data;
					overlay.update('<div class="internal">&nbsp;</div>');
					//Cookie.set(tp.cookieName, tp.token, 7);
				}.bind(this),
				onFailure: function(transport) {
					alert('AJAX failed');
				}
			});
		}.bind(this));
		
		if(action = 'save') {
			//this.saveItem();
		}
	}
	this.registerEmail = function(){}
	this.getToken = function(){
		// check to see if there's a token cookie
		token = Cookie.get(this.cookieName);
		if(token != null) {
			this.token = token;
		}
	}
	this.saveItem = function() {
	    if (this.token == null) {
	        this.showOverlay('save');
	    } else {
	    var now = new Date();
	    var stamp = now.getDate() + now.getMonth() + now.getHours() + now.getMinutes() + now.getSeconds() + now.getMilliseconds();
	        url = this.wsBase + 'addItem/' + stamp + "/" + this.token + '/' + this.itemID;
	        this.log(url);
	        new Ajax.Request(url, {
	            method: 'get',
	            onSuccess: function(transport) {
	                this.log('Save success');
	                this.getItems();
	            } .bind(this),
	            onFailure: function(transport) {
	                if (403 == transport.status) {
	                    alert('You have already added this to your Travel Planner');
	                }
	            } .bind(this)
	        });
	    }
	}
	this.removeItem = function(){}
	
}

document.observe('dom:loaded', function(ev){
	if(typeof tp == 'undefined') {
		tp = new TravelPlanner();
		tp.init();
	}
});
