// xhr
var xhr;
// Validate the form field
function validate() {
	if($('#currency-conversion-form form').validate({rules:{'amount':{min: 1}, message: 'test'}}).form()) {
		$('#amount').HideAllBubblePopups();
		return true;
	} else {
		popup();
		$('#amount').focus();
	}
}
// show the error message bubble
function popup() {
	var errorText = $('label.error').text().trim();
	if($('.jquerybubblepopup').text().trim() !== errorText) {
		$('input.error').RemoveBubblePopup();
		$('input.error').CreateBubblePopup({
			position : 'top',
			align	 : 'center',
			innerHtml: errorText,
			innerHtmlStyle: {
				'color': '#000',
				'font-size': '1.3em',
				'font-weight': 'bold',
				'text-align':'center'
			},
			themeName: 	'orange',
			themePath: 	'/images/jquerybubblepopup-theme'
		});
		$('input.error').ShowBubblePopup();
	}
	if($('#amount').hasClass('valid')) {
		$('#amount').RemoveBubblePopup();
	}
}
// choose your currency
function chooseCurrency() {
	$('#amount').RemoveBubblePopup();
	if(!$('#friendly-select').hasClass('open')) {
		$('#friendly-select').addClass('open');
		// resize the cover, and position it correctly
		$('#cover-up').css('height', $(document).height());
		$('#cover-up').css('width', $(document).width());
		$('#cover-up').css('left', (0 - $('#container').offset().left));
		$('#cover-up').fadeIn();
		$('#friendly-select li:not(.suggest)').each(function(i) {
			$(this).unbind('click');
			$(this).click(function() {
				$('#currency').val($(this).text());
				$('#friendly-select li').removeClass('selected');
				$(this).addClass('selected');
				$('#friendly-select').removeClass('open');
				$('#cover-up').fadeOut();
				$(this).unbind('click');
				return false;
			});
		});
	} else {
		$('#friendly-select').removeClass('open');
		$('#cover-up').fadeOut();
		$('#friendly-select li').unbind('click');
	}
}
// get results
function getResults(url, popped, currency) {
	$('#submit-item').hide();
	$('fieldset').css('width', '555px');
	if(xhr) {
		xhr.abort();
	}
	var amount = $('#amount').val();
	// ajax
	$('#currency-conversion-results table tbody').empty();
	$('#no-rates').hide();
	$('#error').hide();
	$('#loading').show();
	$('#currency-conversion-results').hide();
	// ajax
	xhr = $.ajax({
		cache: false,
		dataType: 'JSON',
		// error
		error: function(XMLHttpRequest, textStatus, errorThrown){
			$('#no-rates').hide();
			$('#error').show();
			$('#loading').hide();
			$('#currency-conversion-results').hide();
		},
		// status code
		statusCode: {
			404: function() {
				$('#no-rates').hide();
				$('#error').show();
				$('#loading').hide();
				$('#currency-conversion-results').hide();
			}
		},
		// success
		success: function(data) {
			var rates = '';
			if($(data.results).size() > 0) {
				$(data.results).each(function(i) {
					rates = rates + '<tr id="result-'+i+'" class="result"><td>'+this.company+'</td><td class="center highlight-column"><strong>'+this.amount+'</strong> '+currency+'<!--<br /><small>last updated '+this.date_added+'</small>--></td><td class="center rates-cell">'+this.rates.current+'</td><td class="center buy-cell"><a href="'+this.company_url+'">Buy &raquo;</a><ul class="services">';
					if(this.cash == 'y') {
						rates = rates + '<li><img src="/assets/images/coins.png" alt="Foreign currency" title="Foreign currency" /></li>';
					}
					if(this.travellers_cheques == 'y') {
						rates = rates + '<li><img src="/assets/images/money.png" alt="Travellers cheques" title="Travellers cheques" /></li>';
					}
					if(this.money_card == 'y') {
						rates = rates + '<li><img src="/assets/images/creditcards.png" alt="Cash/credit card" title="Cash/credit card" /></li>';
					}
					if(this.money_transfer == 'y') {
						rates = rates + '<li><img src="/assets/images/world_go.png" alt="Money transfer" title="Money transfer" /></li>';
					}
					rates = rates + '</ul></td></tr>';
				});
				$('#no-rates').hide();
				$('#error').hide();
				$('#loading').hide();
				$('#currency-conversion-results, #revenue-container').show();
			} else {
				$('#no-rates').show();
				$('#error').hide();
				$('#loading').hide();
				$('#currency-conversion-results, #revenue-container').hide();
			}
			$('#currency-conversion-results table tbody').append(rates);
			positionServices();
			trackClicks();
			scrollDown();
			if(popped) {
				history.pushState(url, '&pound;'+amount+' in '+currency, url);
				document.title = '£'+amount+' in '+currency+' - Currency conversion website - receeve.it';
				$('h1').text('The best rates for converting '+amount+' GBP into '+currency);
				_gaq.push(['_setAccount', 'UA-6996256-1']);
				_gaq.push(['_trackPageview', url]);
			}
		},
		type: 'GET',
		url: url+'/json'
	});
}
//track clicks
function trackClicks() {
	$('.buy-cell a').each(function(i) {
		$(this).click(function() {
			_gaq.push(['_setAccount', 'UA-6996256-1']);
			_gaq.push(['_trackPageview', '/EXTERNAL/'+$(this).attr('href')]);
		});
	});
}
// scroll down
function scrollDown() {
	$('html, body').animate({scrollTop: $('#currency-conversion-form').offset().top - 10}, 1000);
}
// scroll up
function scrollUp() {
	$('html, body').animate({scrollTop: 0}, 400);
}
// position service icons
function positionServices() {
	$('.services').each(function() {
		$(this).css('right', (-15 - ($('li', $(this)).size() * 31)) + 'px');
	});
}

// for history APIs
window.onpopstate = function(event){
	// draw the right results
	var loc = window.location.href.split('/');
	if(event.state) {
		var splitState = event.state.split('/');
		var currency = splitState[3];
		var amount = splitState[4];
		$('#currency').val($('#friendly-select li.selected').text());
		$('#friendly-select li').removeClass('selected');
		$('#friendly-select li').each(function(i) {
			if($(this).text() == currency) {
				$(this).addClass('selected');
			}
		});
		$('#amount').val(amount);
		getResults('/convert/currency/'+currency+'/'+amount, false, currency);
		document.title = '£'+amount+' in '+currency+' - Currency conversion website - receeve.it';
		return false;
	} else {
		if(loc && !loc[3]) {
			$('#currency-conversion-results').hide();
			document.title = 'Currency conversion website - receeve.it';
		} else {
			var currency = loc[5];
			var amount = loc[6];
			$('#revenue-container').show();
			document.title = '£'+amount+' in '+currency+' - Currency conversion website - receeve.it';
			scrollDown();
		}
		$('#friendly-select li').removeClass('selected');
		if(loc[5]) {
			$('#friendly-select li#currency-'+loc[5]).addClass('selected');
		} else {
			$('#friendly-select li:first-child').addClass('selected');
		}
	}
	trackClicks();
};

// twitter bootstrap functionality
function liveTwipsy() {
	$("img[rel=twipsy]").twipsy({
		live: true,
		offset: 15,
		placement: 'above',
		trigger: 'hover'
	});
}

// when the document is ready
$(document).ready(function() {
	$('#container').append('<div id="cover-up"></div>');
	$('#friendly-select, #cover-up').click(function() {
		chooseCurrency();
	});
	// on keyup, validate
	$('#amount').keyup(function() {
		validate();
	});
	// create the js friendly select
	var fSelect = '';
	$('#currency option').each(function(i) {
		if(!$(this).attr('selected')) {
			fSelect = fSelect + '<li><span>'+$(this).val()+'</span></li>';
		} else {
			fSelect = fSelect + '<li class="selected" id="currency-'+$(this).val()+'"><span>'+$(this).val()+'</span></li>';
		}
	});
	$('#friendly-select').append(fSelect);
	// add a tab index for the currency form
	$('#friendly-select').attr('tabindex', 2);
	var selectedCurrency = $('#currency').val();
	$('#currency').remove();
	$('#conversion-form').append('<input type="hidden" name="currency" id="currency" value="'+selectedCurrency+'" />');
	// submit if you hit enter, even on the friendly select menue
	$('#friendly-select').keypress(function(e) {
		if(e.which == 13) {
			$('#currency-conversion-form form').submit();
		}
	});
	// on form submission
	$('#currency-conversion-form form').submit(function() {
		var amount = $('#amount').val();
		var currency = $('#currency').val();
		// validate
		if(validate()) {
			$('#revenue-container').hide();
			getResults('/convert/currency/'+currency+'/'+amount, true, currency);
		}
		return false;
	});
	// show a scroll top top button if necassary
	$(document).scroll(function() {
		if($(document).scrollTop() > 225) {
			$('#go-to-top').fadeIn('slow');
		} else {
			$('#go-to-top').fadeOut('fast');
		}
	});
	// go to top of page when the button is clicked
	$('#go-to-top').click(function() {
		$('html, body').animate({scrollTop: 0}, 500);
	});
	// if you interact with the form, scroll back to the top
	$('#friendly-select, #amount').click(function() {
		scrollUp();
	});
	$('#amount').keydown(function() {
		scrollUp();
	});
	$('fieldset').click(function() {
		$('fieldset').css('width', '655px');
		$('#submit-item').show();
	});
	//position icons appropriately
	positionServices();
	//show popups when necassary
	liveTwipsy();
});
