/**
 * @author Gavin Williams
 * @
 */
var currentChar=1;
var text;
$(document).ready(function(){
	// Setup all of the rating fields
	if ($('.rating').length > 0) {
		$('.rating').rating();
	}

	  
	  	$('#map').each(function(){
	  	if (GBrowserIsCompatible()) {
	  		var map = new GMap2(document.getElementById("map"));
	  		var postcode = $(this).attr('title') + ', UK';
			var mapControl = new GMapTypeControl();
			map.addControl(mapControl);
			map.addControl(new GLargeMapControl());
	  		var geocodeClient = new GClientGeocoder();
	  		geocodeClient.getLatLng(postcode, function(point){
				map.setCenter(point, 13);
		        var marker = new GMarker(point);
		        map.addOverlay(marker);
	  			
	  		});
	  		
	  }
	  	});

	/*
	$('body#propertyItem #details').prev('h2').each(function(){
		$(this).css({backgroundImage: 'url(/images/arrow_down.gif);', backgroundPosition: '98% 50%', backgroundRepeat: 'no-repeat', cursor: 'pointer'});
		$(this).next('div').css('display', 'none');
		$(this).toggle(function(){
			$(this).css({backgroundImage: 'url(/images/arrow_up.gif);'});
			$(this).next('div').slideDown();
		}, function(){
			$(this).css({backgroundImage: 'url(/images/arrow_down.gif);'});
			$(this).next('div').slideUp();
		});
	});*/
	
	$('#summary a.print').click(function(){
		window.print();
		return false;
	});
	
	if($('#module_propertiesForSale').length > 0){
		$('#module_propertiesForSale ul li').each(function(i){
		
			$(this).css({cursor: 'pointer', display: 'block'});
			
			$(this).click(function(){
				var link = $('a', this).attr('href');
				window.location = link;
			});
			
		});
	}
	
	if($('body.section-ucp').length > 0){
		$('#tabs a').click(function(){
			var link = $(this).attr('href') + '#tabs';
			window.location = link;
			return false;
		});
		
		$('#cp-menu a').click(function(){
			var link = $(this).attr('href') + '#tabs';
			window.location = link;
			return false;
		});
		
	}
	
	$('#module_login.expert .profile a').click(function(){
		var top = (($(window).height() / 2) - ($('#expertDialog').height() / 2)) + document.documentElement.scrollTop;
		var left = (($(window).width() / 2) - ($('#expertDialog').width() / 2));
		var tmpTop = top - 50;
		$('#expertDialog').css({top: tmpTop, left: left, display: 'block', opacity: 0});
		
		$('#expertDialog').animate({opacity: 1, top: top}, 'slow');
		
		return false;
	});
	
	$('#expertDialog a').click(function(){
		var top = parseFloat($('#expertDialog').css('top').replace(/px/, '')) + 50;
		var link = this;
		$('#expertDialog').animate({opacity: 0, top: top}, 'slow', null, function(){
			window.location = $(link).attr('href');
		});
		return false;
	});

	
	if($('body#talk').length > 0){
		
		function Chat(element, url){
			this.data = '';
			this.interval = '';
			this.element = $(element);
			this.url = url;
			
			this.chatlog = '#chatLog';
			this.chatusers = '#chat_usersOnline';
			
			this.bindEvents();
			
			params = 'init=true';
			this.sendRequest(params);
			this.setInterval();
		}
		
		Chat.prototype.setInterval = function(){
			this.interval = setInterval(this.autoUpdate, 3000);
		}
		
		Chat.prototype.resetInterval = function(){
			var temp = this;
			window.clearInterval(temp.interval);
			this.setInterval();
		}
		
		Chat.prototype.autoUpdate = function(){
			chatObj.sendRequest();
		}
		
		Chat.prototype.updateUserList = function(){
			var temp = this;
			$(temp.chatusers).html('');
			$('users user', this.data).each(function(){
					var user = new Object;
					user.firstname = $('firstname', this).text();
					user.lastname = $('lastname', this).text();
					user.type = $('type', this).text();
					user.status = $(this).attr('status');
					user.id = $(this).attr('id');
									
					if($(temp.chatusers + ' li#user_' + user.id).length > 0){
						
					} else {
						$(temp.chatusers).append('<li id="user_' + user.id + '"><span class="name">' + user.firstname + ' ' + user.lastname + '</span></li>');
					}
			});
		}
		
		Chat.prototype.updateChatLog = function(){
			var temp = this;
			$('events event', this.data).each(function(){

				var event = new Object;
				
				event.id = $(this).attr('id');
				event.from = $('user firstname', this).text() + ' ' + $('user lastname', this).text();
				event.message = $('content', this).text();
													
				if($(temp.chatlog + ' dt#logId_' + event.id).length > 0){
					
				} else {
					$(temp.chatlog).append('<dt id="logId_' + event.id + '" style="display: none;">' + event.from + '</dt> <dd style="display: none;">' + event.message + '</dd>');
					$('#logId_' + event.id).fadeIn();
					$('#logId_' + event.id).next().fadeIn();
				}
			});
		}
		
		Chat.prototype.processResponse = function(data, textStatus){
			chatObj.data = data;
			chatObj.updateChatLog();
			chatObj.updateUserList();
			var objDiv = document.getElementById('chatLog');
			objDiv.scrollTop = objDiv.scrollHeight;
		}
		
		Chat.prototype.sendRequest = function(params){
			$.post(this.url, params, this.processResponse);
			this.resetInterval();
		}
		
		Chat.prototype.bindEvents = function(){
			temp = this;
			$(this.element).submit(function(){
				params = $(temp.element).serialize();
				chatObj.sendRequest(params);
				$('#chatMessage').val('');
				$('#chatMessage').trigger('focus');
				return false;
			});
		}
		
		var chatObj = new Chat('#chatForm', '/talk/xml/');
		
		// Bind the ajax post for this form
		


	}

	$('#module_newsArchive').each(function(){
		
		var archive = this;

		var stories = $('ul.stories', archive);
		var headers = $('h3', archive);
		
		$(stories).each(function(){
			$('li:gt(2)', this).wrapAll('<li class="toggle"><ul></ul></li>');
		});
		
		$('li.toggle', archive).slideUp('slow');
		
		$('a', headers).click(function(){
		
			var toggle = $(this).parent('h3').next('ul').children('li.toggle');

			if($(toggle).css('display') != 'block'){	
				// Hide all toggles
				$('li.toggle', archive).slideUp('slow');
				$(toggle).slideDown();
			}
			return false;
		});
		
	});
	
	
	// If the news flash exists let's do the newsflash ticker
	if($('#specialMessage ul').length > 0){
		
		var first = null;
		var current = null;
		var time = 0;
		var msPerWord = 700;
		var interval;
		var xml;
		
		function next(el){
	
			var element = {
				index: $(el).attr("index"),
				next: $(el).next("li a"),
				previous: $(el).prev("li a"),
				hasNext: $(el).next("li a").length,
				hasPrev: $(el).prev("li a").length
			};
			
			
			if(element.hasNext){
				$(el).fadeOut("slow", function(){
					text = $(element.next).text();
					$(element.next).text('');
					$(element.next).css({display: 'block'});
					type(element.next);
					 
					current = element.next;
				});
			}else{
				$(el).fadeOut("slow", function(){
					var text = $(first).text();
					$(first).text('');
					$(first).css({display: 'block'});
					type(first);
					current = first;
				});
			}

		}
		
		function type(el){

		      currentChar++
		      if (currentChar>text.length){
		      	$(el).text(text.substr(0, currentChar));
		        currentChar=1;
		        setTimeout(function(){next(el)}, 5000);
		      } else {
		      	$(el).text(text.substr(0, currentChar) + '_');
		        setTimeout(function(){type(el)}, 50);
		      }
		}
		
		function wordCount(el){
			
			text = $(el).text();
			
			wordcounter=0;
			
			for (x=0;x< text.length;x++) {
				if (text.charAt(x) == " " && text.charAt(x-1) != " ") {wordcounter++}  // Counts the spaces while ignoring double spaces, usually one in between each word.
			}
					
			return wordcounter;
		
		}
	
		function resetInterval(){
			window.clearInterval(interval);
			time = $(current).attr("time");
			interval = self.setInterval(function(){next(current)}, time);
		}
		
		$("#specialMessage ul li").each(function(i){
			
			// Get the url from the link inside
			var url = $('a', this).attr('href');
			
			$(this).click(function(){
				window.location = url;
			});
			
			
			$(this).css({position: "absolute", cursor: 'pointer'});

			$(this).css({display: 'none'});
			$(this).attr('title', i);
			if(i == 0){
				first = this;
				current = this;
			}

		});
		
		text = $(current).text();
		$(current).text('');
		$(current).css({display: 'block'});
		type(current);
		
	}
	
	if($('#module_recommend').length > 0){
		var trigger = $('#module_recommend .trigger');
		
		$(trigger).focus(function(){
			$('#module_recommend .message').fadeIn('slow');
		});
		
		$('#module_recommend :text').focus(function(){
			if (this.defaultValue == $(this).val()) {
				$(this).val('');
			}
		});
		
		$('#module_recommend :text').blur(function(){
			if ($(this).val() == '') {
				$(this).val(this.defaultValue);
			}
		});
		
	
		$('#module_recommend form').submit(function(){
			params = $(this).serialize();
			$('#module_recommend .submit').attr('disabled', 'disabled');
			$.post('/ajax/', params + '&request=sendtofriend', function(xml, code){
				var response = {
					code: $('status code', xml).text(),
					message: $('status message', xml).text()					
				};
				
				if(response.code == 200){
					$('#module_recommend form').fadeOut();
					$('#module_recommend').append('<p>Your invitation has been sent, <a href="#">click here</a> to send another.</p>').click(function(){
						$('p', this).slideUp(500, function(){
							$('#module_recommend form').slideDown('slow', function(){
								$('#module_recommend :text').each(function(){
									$(this).val(this.defaultValue);
								});
							});
							$(this).remove();
							$('#module_recommend .submit').removeAttr('disabled');
						});
						
						return false;
					});
				} else {
					$('#module_recommend form').prepend('<p class="error">' + response.message + '</p>');
				}
				
			});
			
			return false;
		});
		
	}
	
	if($('#module_advertise').length > 0){	
		
		$('#module_advertise .message').css({display: 'none'});
		
		var trigger = $('#module_advertise .trigger');
		
		$(trigger).focus(function(){
			$('#module_advertise .message').fadeIn('slow');
		});
		
		$('#module_advertise :text').focus(function(){
			if (this.defaultValue == $(this).val()) {
				$(this).val('');
			}
		});
		
		$('#module_advertise :text').blur(function(){
			if ($(this).val() == '') {
				$(this).val(this.defaultValue);
			}
		});
		
		$('#module_advertise form').submit(function(){
			params = $(this).serialize();
			$('#module_advertise .submit').attr('disabled', 'disabled');
			$.post('/ajax/', params + '&request=advertisehere', function(xml, code){
				var response = {
					code: $('status code', xml).text(),
					message: $('status message', xml).text()					
				};
				
				if(response.code == 200){
					$('#module_advertise form').fadeOut();
					$('#module_advertise').append('<p>Your request has been sent, <a href="#">click here</a> to send another.</p>').click(function(){
						$('p', this).slideUp(500, function(){
							$('#module_advertise form').slideDown('slow', function(){
								$('p', this).remove();
								$('#module_advertise :text').each(function(){
									$(this).val(this.defaultValue);
								});
							});
							$(this).remove();
							$('#module_advertise .submit').removeAttr('disabled');
						});
						return false;
					});
				} else {
					$('#module_advertise form').prepend('<p class="error">' + response.message + '</p>');
				}
				
			});
			
			return false;
		});
		
	}
	
	if($('body#propertyRegistration').length > 0){
				
		var pages = 0;
		var pageWidth = 0;
		var holderWidth = 0;
		var currentPage = 1;
		var pageArray = Array();
		
		// Set up the pages
		pages = $('#propertyRegistration #pages .page').length;
		pageWidth = $('#propertyRegistration #pages .page').width();
		holderWidth = pages * pageWidth;
		
		// Calculate page positions
		for(var i = 0; i < pages; i++){
			var index = i+1;
			pageArray[index] = 0 - (pageWidth * i);
		}
		
		// Set up the page holder
		$('#propertyRegistration #pages').css('width', holderWidth);
		// Add dialogue
		$('body').append('<div id="dialog"></div>');
				
		function bindControls(){
			// Bind controls to page numbers and next and last controls
			$('div.controls a.next').click(function(){
				if (currentPage < pages) {
					goToPage(currentPage+1);
					currentPage++;
				}
				
				return false;
			});
	
			$('div.controls a.previous').click(function(){
				if (currentPage > 1) {
					goToPage(currentPage-1);
					currentPage--;
				}
				
				return false;
			});
		}
		
		// Add information boxes
		$('fieldset label[@title]').each(function(){
			var information = $(this).attr('title');
			var label = this;
			$(this).prepend('<img src="/images/icons/information.png" alt="Information" class="information" />');
			$('img', this).css('cursor', 'pointer');
						
			// Bind controls
			$('img', this).mouseover(function(e){
				$(label).attr('title', '');
				// Clear the diaogue box and add the dialogue for this form element
				$('#dialog').text(information);
				$('#dialog').css({top: (e.pageY + 5), left: (e.pageX - 175), display: 'block'});
				
			});
			
			$('img', this).mouseout(function(e){
				$(label).attr('title', information);
				$('#dialog').css({display: 'none'});
			});
			
			
		});
		
		// Add navigation elements to the individual pages
		$('#propertyRegistration #pages .page').each(function(i){
			$(this).append('<div class="controls"></div>');
			$('h2', this).append('<span>Step ' + (i + 1) + ' of ' + $('#propertyRegistration #pages .page').length + '</span>');
			var page = i+1;
			if(1 == page){
				$('div.controls', this).append('<a href="#" class="next">Next</a>');
			} else if (page < (pages)){
				$('div.controls', this).append('<a href="#" class="previous">Previous</a>');
				$('div.controls', this).append('<a href="#" class="next">Next</a>');
			} else {
				$('div.controls', this).append('<a href="#" class="previous">Previous</a>');
			}
			
			// We want to move to the next page when the first form field on that page is focused on.
			/*
			$(':input:first', this).focus(function(){
				goToPage(page);
			});
			*/
			
		});
		
		bindControls();
		
		function goToPage(page){
			$('#propertyRegistration #pages').animate({left: pageArray[page]}, 1000);
		}
		
		// Bind individual form controls
		$(':input[@name=garagecars]').change(function(){
			if(this.checked == false){
				$('div.garagecars').slideUp("slow", function(){
					$('div.garagecars input').val(0);
				});
			} else {
				$('div.garagecars').slideDown("slow");
			} 
		});
		
		$(':input[@name=tenure]').change(function(){
			if($(this).val() == 'leasehold'){
				$('div.leasehold').slideDown("slow");
			} else {
				$('div.leasehold').slideUp("slow");
			} 
		});
		
		$('#frm_country').change(function(){
			populateCounty($(this).val());
		});
		
		$('input.file').click(function(){
			/* $(this).attr('disabled', 'disabled'); */
			$(this).after('Uploading files, this could take a while, please be patient');
		});
		
		// Counties drop down			
		function populateCounty(country){
			if(country){
				country = country.replace(/ /, '');
				var counties = eval('countyList.' + country);
				var countySelect = $('<select />');
				
				if (counties) {
					
					for (var i = 0; i < counties.length; i++) {
						option = $('<option/>').attr('value', counties[i]);
						$(option).text(counties[i]);
						
						if(i == 0){
							value = counties[i];
						}
						
						$(countySelect).append(option);
					}
				} else {
					$(countySelect).append('<option>Overseas</option>').attr('value', 'Overseas');
				}
				
				$('#frm_county').html($('option', countySelect));
				$('#frm_county').val(value);
			}
			
		}

		if($('#frm_county option').length <= 1){
			populateCounty($('#frm_country').val());
		}
	}
	
	if($('#module_expertProfiles').length > 0){

		function ExpertProfiles (element){

			this.profileHeight = 0;
			this.profiles = 0;
			this.pages = 0;
			this.profilesPerPage = 5;
			this.pageHeight = 0;
			this.element = $(element);
			this.parent = null;
			this.pageArray = Array();
			this.currentPage = 1;
						
			this.parent = $(this.element).parent('div');
			
			$(this.element).css({position: 'relative', width: '100%'});
			
			this.profiles = $('li', this.element).length;
			
			$(this.parent).css('padding', 0);
			
			this.profileHeight = this.element.find('li').outerHeight(true);
			
			this.setListHeight();
			
			this.pages = Math.ceil(this.profiles / this.profilesPerPage);
			
			this.setPageArray();
			// Check to see if there's a cookie holding this page

			if(page = readCookie('expertProfilesCurrentPage')){
					page = parseInt(page);
					this.scroll(page);
					this.currentPage = page;
			}
			
			this.addControls();
			

		}
		
		ExpertProfiles.prototype.setListHeight = function(){

			this.pageHeight = (this.profilesPerPage * this.profileHeight);
			
			$(this.element).wrap('<div id="constraint" style="position: relative; padding: 10px;"></div>');
			$(this.element).parent('div').css({height: this.pageHeight, overflow: 'hidden'});
		}
		
		ExpertProfiles.prototype.addControls = function(){
			
			var temp = this;
			
			$(this.parent).append('<div class="controls"><a class="previous" href="#">Previous</a> | <a class="next"  href="#">Next</a></div>');
			
			$('.controls .previous', temp.parent).click(function(){
				if (temp.currentPage > 1) {
					currentPage = temp.currentPage-1
					temp.scroll(currentPage);
					temp.currentPage = currentPage;
					createCookie('expertProfilesCurrentPage', currentPage, 2);
				}
				
				return false;
			});
			
			$('.controls .next', temp.parent).click(function(){
				if (temp.currentPage < temp.pages) {
					currentPage = temp.currentPage+1;
					temp.scroll(currentPage);
					temp.currentPage = currentPage;
					createCookie('expertProfilesCurrentPage', currentPage, 2);
				}
				
				return false;
			});
		}
		
		ExpertProfiles.prototype.setPageArray = function(){
			for(var i = 0; i < this.pages; i++){
				var index = i+1;
				this.pageArray[index] = 0 - (this.pageHeight * i);
			}
		}
		
		ExpertProfiles.prototype.scroll = function(page){
			var temp = this;
			$(temp.element).animate({
				top: temp.pageArray[page]
			}, 4000);

		}
		
		var experts = new ExpertProfiles('#module_expertProfiles ul');
		
	}
	
	if($('body#propertyItem').length > 0){
		
		function Gallery(element){
			
			this.dimensions = new Object;
			
			this.dimensions.gallery = new Object;
			this.dimensions.gallery.width = 0;
			this.dimensions.gallery.height = 0;
			
			this.dimensions.item = new Object;
			this.dimensions.item.width = 85;
			this.dimensions.item.height = 57;
			this.dimensions.item.marginRight = 5;
			
			this.currentItem = 1;
			
			this.positions = Array();
			
			this.element = $(element);
			
			this.images = $('ul li', this.element).length;

			$(this.element).addClass('gallery');
			
			this.dimensions.gallery.height = this.dimensions.item.height;
			this.dimensions.gallery.width = ((this.dimensions.item.width * this.images) + (this.dimensions.item.marginRight * this.images));

			this.addControls();
			
		}
		
		Gallery.prototype.addControls = function(){
			
				var temp = this;
			
				$('ul li a', this.element).click(function(){
					$('#image img').attr('src', this.href);
					return false;
				});
				
		}
		
		new Gallery('#module_PropertyGallery');
	}
	
	if($('body#propertyList').length > 0 || $('body#expertQuestions').length > 0){
	
		
		var pageHeight = 780; // 780 for 10 properties
		var pages = $('.controls span.page:last').html();
		var currentPage = 1;
		
		// Calculate page positions
		
		var pageArray = Array();
		
		for(var i = 0; i < pages; i++){
			var index = i+1;
			pageArray[index] = 0 - (pageHeight * i);
		}
				
		// Bind controls to page numbers and next and last controls
		$('.controls a.next').click(function(){
			if (currentPage < pages) {
				scrollResultSet(currentPage+1);
				currentPage++;
			}
			
			return false;
		});
		
		// Bind controls to page numbers and next and last controls
		$('.controls a.previous').click(function(){
			if (currentPage > 1) {
				scrollResultSet(currentPage-1);
				currentPage--;
			}
			
			return false;
		});
		
		$('.controls span.page').click(function(){
			var page = parseInt($(this).text());
			scrollResultSet(page);
			currentPage = page;
			
			return false;
		});
		
		$('.controls a.last').click(function(){
			scrollResultSet(pages);
			currentPage = pages;
			
			return false;
		});
		
		// Animate the scroll		
		function scrollResultSet(page){
			$('#resultSet').animate({
				top: pageArray[page]
			}, 4000, 'easeInOutBack');
			$('.controls span.page').removeClass('selected');
			$('.controls span.page:eq(' + (page - 1) + ')').addClass('selected');
		}
		
	}
	
	if($('body#myPropertyList').length > 0){
		
		var pageHeight = 390; // 780 for 10 properties
		var pages = $('.controls span.page:last').html();
		var currentPage = 1;
		
		// Calculate page positions
		
		var pageArray = Array();
		
		for(var i = 0; i < pages; i++){
			var index = i+1;
			pageArray[index] = 0 - (pageHeight * i);
		}
				
		// Bind controls to page numbers and next and last controls
		$('.controls a.next').click(function(){
			if (currentPage < pages) {
				scrollResultSet(currentPage+1);
				currentPage++;
			}
			
			return false;
		});
		
		// Bind controls to page numbers and next and last controls
		$('.controls a.previous').click(function(){
			if (currentPage > 1) {
				scrollResultSet(currentPage-1);
				currentPage--;
			}
			
			return false;
		});
		
		$('.controls span.page').click(function(){
			var page = parseInt($(this).text());
			scrollResultSet(page);
			currentPage = page;
			
			return false;
		});
		
		$('.controls a.last').click(function(){
			scrollResultSet(pages);
			currentPage = pages;
			
			return false;
		});
		
		// Animate the scroll		
		function scrollResultSet(page){
			$('#resultSet').animate({
				top: pageArray[page]
			}, 4000, 'easeInOutBack');
			$('.controls span.page').removeClass('selected');
			$('.controls span.page:eq(' + (page - 1) + ')').addClass('selected');
		}
		
	}
	
	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	
	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	function eraseCookie(name) {
		createCookie(name,"",-1);
	}
	
});