var Cookie = {
	set: function(name, value, daysToExpire) {
		var expire = '';
		daysToExpire = (daysToExpire != undefined) ? daysToExpire : 365;
		if (daysToExpire != undefined) {
			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');
	}
};

/*
var GetUtils = {
	innerText: function(element) {
		if(document.all) {
			return $(element).innerText;
		} else {
			return $(element).textContent;
		}
	}
}
*/

// Element.addMethods(GetUtils);

function TravelPlannerManager() {
	
	this.singularMode = true; // close all other categories on opening one
	this.cookieName = 'travelPlannerToken';
	this.token = null;
	this.debug = true;
	this.itemString = '';

	this.init = function() {

	    this.getToken();

	    if (this.token == null) {

	    } else {
	        var now = new Date();
	        var stamp = now.getDate() + now.getMonth() + now.getHours() + now.getMinutes() + now.getSeconds() + now.getMilliseconds();
	        // get items
	        itemRequest = new Ajax.Request('/ws/travelplanner.svc/getitems/' + stamp + "/" + this.token, {
	            method: 'get',
	            asynchronous: false,
	            onSuccess: function(transport) {
	                var root = transport.responseXML.documentElement;
	                var itemsString = (root.getElementsByTagName('GetItemsResult')) ? root.getElementsByTagName('GetItemsResult')[0].firstChild.data : null;
	                this.items = itemsString.split('|');
	                var source = $('source');
	                source.update('<div class="category open"><div class="title">Saved items</div><div class="items"><div class="box"></div></div></div>');
	                var itemBox = $$('#source .box')[0];
	                this.items.each(function(item) {
	                    var idRequest = new Ajax.Request('/ws/items.svc/item/' + item, {
	                        method: 'get',
	                        asynchronous: false,
	                        onSuccess: function(transport) {

	                            root = transport.responseXML.documentElement;

	                            /*excerpt = (root.getElementsByTagName('Excerpt')) ? root.getElementsByTagName('Excerpt')[0].childNodes[0].nodeValue : null;
	                            iconicImage = (root.getElementsByTagName('IconicImage')) ? root.getElementsByTagName('IconicImage')[0].childNodes[0].nodeValue : null;
	                            name = (root.getElementsByTagName('Name')) ? root.getElementsByTagName('Name')[0].childNodes[0].nodeValue : null;
	                            template = (root.getElementsByTagName('Template')) ? root.getElementsByTagName('Template')[0].childNodes[0].nodeValue : null;
	                            uri = (root.getElementsByTagName('Uri')) ? root.getElementsByTagName('Uri')[0].childNodes[0].nodeValue : null;*/
	                            var excerpt = "Awaiting description";
	                            if (root.getElementsByTagName('Excerpt').length != 0 && root.getElementsByTagName('Excerpt')[0].childNodes.length > 0) {
	                                excerpt = root.getElementsByTagName('Excerpt')[0].childNodes[0].nodeValue;
								}

	                            var iconicImage = "Awaiting image";
	                            if (root.getElementsByTagName('IconicImage').length != 0 && root.getElementsByTagName('IconicImage')[0].childNodes.length > 0) {
	                                iconicImage = root.getElementsByTagName('IconicImage')[0].childNodes[0].nodeValue;
								}

	                            var name = root.getElementsByTagName('Name')[0].childNodes[0].nodeValue;
	                            var template = root.getElementsByTagName('Template')[0].childNodes[0].nodeValue;
	                            var uri = root.getElementsByTagName('Uri')[0].childNodes[0].nodeValue;

	                            var el = new Element('div', { 'class': 'item' });
	                            var content = '<div class="check"><input type="checkbox" name="select[' + item + ']" /></div>';
	
	                            content = content + '<img class="iconic" src="http://images1.audleytravel.com/?w=50&h=-&q=80&id=' + iconicImage + '" />';
	                            content = content + '<div class="content">';
	                            content = content + '<div class="itemTitle"><span>' + name + '</span>'; //'<a href="' + uri + '" title="Read more">Read more &#187;</a></div>';
	                            content = content + '<div class="itemID">' + item + '</div>';
	                            content = content + '<div class="excerpt" style="display: none"><p>' + excerpt + '</p><a href="' + uri + '" title="Read more">Read even more &raquo;</a></div>';
	                            content = content + '<div class="links"><a class="toggleExcerpt" href="' + uri + '" title="Read more">Read more</a><a class="removeFromPlanner" href="#" title="Remove from planner">Remove from Travel Planner</a></div>';
	                            content = content + '</div>';
	                            el.update(content);
	                            itemBox.insert(el);
	                        }
	                    });
	                });
	            }
	        });

	        // remove empty categories
	        $$('.category').each(function(el) {
	            if (typeof el.down('.item') == 'undefined') {
	                el.remove();
	            }
	        });

	        // close all but the first category
	        if (this.singularMode) {
	            $$('.category').each(function(category, i) {
	                if (i == 0) {
	                    this.showCategory(category);
	                } else {
	                    this.hideCategory(category);
	                }
	            }.bind(this));
	        }

	        // attach accordian action to each category title
	        $$('.category .title').each(function(el) {
	            el.observe('click', function(ev) {
	                title = ev.element();
	                // new Effect.toggle(title.up('.category').down('.box'), 'slide');
	                category = title.up('.category');
	                this.toggleCategory(category);
	                /*
	                container = category.down('.items');
	                if(container.visible()) {
	                container.hide();
	                } else {
	                container.show();
	                }
	                */
	                // hide the other categories
	                $$('.category').each(function(el) {
	                    if (el != category) {
	                        this.hideCategory(el);
	                    }
	                }.bind(this));
	            }.bind(this));
	        }.bind(this))

	        // attach click and doubleclick the event to each item
	        $$('.category .item').each(function(el) {
	            el.observe('click', function(ev) {
	                el = ev.element();
	                var item = (el.tagName == 'DIV' && el.hasClassName('item')) ? el : el.up('div.item');
	                if (item.hasClassName('selected')) {
	                    this.removeFromEnquiry(item);
	                } else {
	                    this.addToEnquiry(item);
	                }
	                this.updateTarget();
	            }.bind(this));
				el.observe('dblclick', function(ev){
					el = ev.element();
					el = (el.hasClassName('item')) ? el : el.up('.item');
					link = el.down('.toggleExcerpt').getAttribute('href');
					window.location.href = link;
				});
	        }.bind(this));

	        // attach the add all events
	        $$('.category .addAll').each(function(el) {
	            el.observe('click', function(ev) {
	                Event.stop(ev);
	                category = Event.element(ev).up('.category');
	                items = category.down('.items').down('.box').immediateDescendants();
	                if (items.length != 0) {
	                    items.each(function(item) {
	                        this.addToEnquiry(item);
	                    }.bind(this));
	                }
	                this.updateTarget();
	            }.bind(this));
	        }.bind(this));

	        // attach to add everything
	        $('addEverything').observe('click', function(ev) {
	            Event.stop(ev);
	            $$('.category .item').each(function(item) {
	                this.addToEnquiry(item);
	            }.bind(this));
	            this.updateTarget();
	        }.bind(this));

	        // attach to empty
	        $('empty').observe('click', function(ev) {
	            Event.stop(ev);
	            $$('.category .item').each(function(item) {
	                this.removeFromEnquiry(item);
	            }.bind(this));
	            this.updateTarget();
	        }.bind(this));

	        // attach excerpt show/hide control
	        $$('.category .toggleExcerpt').each(function(link) {
	            link.observe('click', function(ev) {
	                ev.stop();
	                link = ev.element();
	                link = (link.tagName == 'A') ? link : link.up('a');
	                excerpt = link.up('.item').down('.excerpt');
	                if (excerpt.visible()) {
	                    excerpt.hide()
	                    link.update('Show info');
	                } else {
	                    excerpt.show();
	                    link.update('Hide info');
	                }
	            }.bind(this));
	        }.bind(this));

	        $$('.category .removeFromPlanner').each(function(link) {
	            link.observe('click', function(ev) {
	                ev.stop();
	                var link = ev.element();
	                link = (link.tagName == 'A') ? link : link.up('a');
	                var item = link.up('.item');
	                item.setOpacity(0.5);
	                id = item.down('.itemID').firstChild.data;
	                id = (document.all) ? item.down('.itemID').innerText : item.down('.itemID').textContent;
					uri = (item.down('a.toggleExcerpt')) ? item.down('a.toggleExcerpt').readAttribute('href') : '';
	                if (confirm('This will permanently be removed from your planner. Are you sure?')) {
						pageTracker._trackEvent('travelPlanner', 'remove', uri);
						// add a stamp to avoid IE WS caching issues
	                    var now = new Date();
	                    var stamp = now.getDate() + now.getMonth() + now.getHours() + now.getMinutes() + now.getSeconds() + now.getMilliseconds();
	                    url = '/ws/travelplanner.svc/removeItem/' + stamp + "/" + this.token + '/' + id;
	                    console.log(url);
	                    new Ajax.Request(url, {
	                        method: 'get',
	                        onSuccess: function(transport) {
	                            item.remove();
	                            this.updateTarget();
	                        }.bind(this),
	                        onFailure: function(transport) {
	                            item.setOpacity(1);
	                        }.bind(this)
	                    });
	                } else {
	                    item.setOpacity(1);
	                }
	            }.bind(this));
	        }.bind(this));

	        $('submitTravelPlanner').observe('click', function(ev) {
	            ev.stop();
	
				if($$('.item.selected').length == 0) {
					alert('Please select some items from your travel planner to include in your enquiry.');
					return false;
				}

	            itemString = '';
/*
	            if ($$('.item.selected').length != 0) {
	                $$('.item.selected').each(function(el, i) {
	                    if (i != 0) {
	                        itemString = itemString + '|';
	                    }
						// itemString = itemString + document.all ? el.down('.itemID').textContent : el.down('.itemID').innerText;
						itemString = itemString + ($$('body')[0].innerText != undefined) ? el.down('.itemID').innerText : el.down('.itemID').textContent;						
	                    // itemString = itemString + el.down('.itemID').innerText();
	                });
	            }
*/
				itemString = $$('.item.selected').collect(function(el){
					return ($$('body')[0].innerText != undefined) ? el.down('.itemID').innerText : el.down('.itemID').textContent;
				}).join('|');
	
	            formData = new Hash();
	            formData.set('firstname', $F('firstname'));
	            formData.set('surname', $F('surname'));
	            formData.set('email', $F('email'));
	            formData.set('telephone', $F('telephone'));
	            formData.set('dates', $F('traveldates'));
	            formData.set('othercomments', $F('message'));
	            formData.set('items', itemString);
				itemCount = itemString.split('|').length;

	            new Ajax.Request('/ws/travelplanner.svc/submitenquiry', {
	                method: 'post',
	                parameters: formData,
	                onCreate: function(transport) {
	                    // $('formStatus').show().removeClassName('complete').update('Sending your enquiry...');
	                    $('submitTravelPlanner').value = 'Sending your enquiry...';
	                },
	                onComplete: function(transport) {
						if(transport.status == 200) {
		                    $('details').update('Thanks! We\'ve received your enquiry and will be in touch soon to discuss your plans');
							pageTracker._trackEvent('travelPlanner', 'send', itemString, itemCount);
		                    // $('formStatus').addClassName('complete').update('Thanks! We\'ve received your enquiry.');
		                    // console.log(transport.status);
						} else {
							$('formStatus').update('Sorry, there has been an error - please call us on 01993 838 000').show();
							tpm.transport = transport;
						}
	                }
	            });

	        }.bind(this));

	    }
	}
	
	this.getSelectedItems = function() {
		itemString = '';
        if ($$('.item.selected').length != 0) {
            $$('.item.selected').each(function(el, i) {
                if (i != 0) {
                    itemString = itemString + '|';
                }
				thisID = ($$('body')[0].innerText != undefined) ? el.down('.itemID').innerText : el.down('.itemID').textContent;
                // itemString = itemString + el.down('.itemID').innerText();
				// itemString = itemString + document.all ? el.down('.itemID').textContent : el.down('.itemID').innerText;
				itemString = itemString + thisID;
            });
        }
		return itemString;
	}

	this.attach = 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.toggleCategory = function(category) {
		if(category.down('.items').visible()) {
			this.hideCategory(category);
		} else {
			this.showCategory(category);
		}
	}
	
	this.hideCategory = function(category) {
		category.down('.items').hide();
		category.removeClassName('open');
	}
	
	this.showCategory = function(category) {
		category.down('.items').show();
		category.addClassName('open');
		// new Effect.ScrollTo(category);
	}

	this.addToEnquiry = function(item) {
		item.addClassName('selected');
		item.down('input[type="checkbox"]').checked = 'checked';
	}
	
	this.removeFromEnquiry = function(item) {
		item.removeClassName('selected');
		item.down('input[type="checkbox"]').checked = '';
	}
	
	this.removeItem = function(ev) {
		alert('You clicked on ' + Event.element(el).identify());
	}
	
	this.updateTarget = function() {
		var target = $('target').down('.box');
		target.update('');
		ul = new Element('ul');
		$$('.category .item.selected').each(function(el){
			title = '';
			// title = (document.all) ? el.down('.itemTitle').innerText : el.down('.itemTitle').textContent;
			title = ($$('body')[0].innerText != undefined) ? el.down('.itemTitle span').innerText : el.down('.itemTitle span').textContent;
			li = new Element('li');
			li.addClassName('hover');
			li.update(title);
			ul.insert(li);
		});
		descendants = ul.immediateDescendants();
		if(descendants.length != 0) {
			descendants[0].addClassName('first');
			descendants[descendants.length - 1].addClassName('last');
			target.insert(ul);
			descendants.each(function(li) {
/*
				li.observe('mouseover', function(ev){
					li = Event.element(ev);
					li.addClassName('hover');
				});
				li.observe('mouseout', function(ev){
					li = Event.element(ev);
					li.removeClassName('hover');
				});
*/
				li.observe('click', function(ev){
					li = Event.element(ev);
					
					// de-select the item
					itemPosition = li.previousSiblings().length;
					$$('.category .item.selected')[itemPosition].removeClassName('selected');
					
					this.updateTarget();
				}.bind(this));
			}.bind(this));
		} else {
			target.update('<div id="helper">Select some items on the left</div>');
		}
/*
		new Effect.Highlight(target, {
			startcolor: '#ffff99',
			endcolor: '#ffffff' 
		});
*/
	}
	
}

document.observe('dom:loaded', function(ev){
	tpm = new TravelPlannerManager();
	tpm.init();
	var signout = new Element('a', {
		id: 'signout',
		href: '#',
		title: 'Sign out'
	}).update('Sign out of the Travel Planner');
	signout.observe('click', function(ev){
		Cookie.erase('travelPlannerToken');
		window.location = 'http://www.audleytravel.com/';
	});
	$('source').insert(signout, 'bottom');
});
