$(document).ready(function () {
  getLatestStats(); 
  getRetailers();
  $('#stats').corner('10px');
  $('#sign-up-input-background').corner('6px');
  $('.retailers-tab-active').corner('top');
  $('.retailers-tab-inactive').corner('top');
  $('#sign-up-button').mouseover(function() {$(this).css('background-position', '0 -29px')});
  $('#sign-up-button').mouseout(function() {$(this).css('background-position', '0 0')});
  $('.retailers-tab').click(function() { homepageTabClick(this) })
  $('#overall-countries-number').text($('.retailers-tab').length);
  $('#slideshow').data('position', 1);
  if ($('#stats').length == 0) {
    $('#logo').css('cursor', 'pointer');
    $('#logo').click(function() {document.location = 'http://www.getinvisiblehand.com/'})
  }
  $('#slideshow').data('intervalId', setInterval("advanceSlideshow ()", 10000));  
  $(".bulletpoint").click(bulletpointClick);
  $(".current-language").removeAttr('href');
  $(".current-language").css('cursor', 'default');
  
  var source = window.location.href.match(/adwords_../)
  source = (source == null ? '' : source)
  $("#firefox-version").click(function() {
    $('#download-button').attr('href', 'http://www.getinvisiblehand.com/redirect/firefox/' + source);
    $('#download-button').css('background-image', 'url(http://www.getinvisiblehand.com/images/button-download-' + currentLanguage() + '.png)')
  });
  $("#chrome-version").click(function() {
    $('#download-button').attr('href', 'http://www.getinvisiblehand.com/redirect/chrome/' + source);
    $('#download-button').css('background-image', 'url(http://www.getinvisiblehand.com/images/button-chrome-download-' + currentLanguage() + '.png)');    
  });
  $("#ie-version").click(function() {
    $('#download-button').attr('href', 'http://www.getinvisiblehand.com/redirect/ie/' + source);
    $('#download-button').css('background-image', 'url(http://www.getinvisiblehand.com/images/button-ie-download-' + currentLanguage() + '.png)');    
  });
  $("#safari-version").click(function() {
    $('#download-button').attr('href', 'http://www.getinvisiblehand.com/safari.html');
    $('#download-button').css('background-image', 'url(http://www.getinvisiblehand.com/images/button-safari-download-' + currentLanguage() + '.png)');    
  });
  
  if (navigator.userAgent.toLowerCase().indexOf('msie') > -1)
    $("#ie-version").click();
  if (navigator.userAgent.toLowerCase().indexOf('safari') > -1)
    $("#safari-version").click();
  // make sure this one goes AFTER safari check since Chrome identifies itself as Safari
  if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
    $("#chrome-version").click();
});

function currentLanguage() {
  switch($('a.current-language').text()) {
    case 'English': return 'en'; break;
    case 'Deutsch': return 'de'; break;
    default: return 'en'
  }  
}

function bulletpointClick() {
  if ($(this).hasClass('bulletpoint-current')) {
    return;    
  }
  clearInterval($('#slideshow').data('intervalId'));
  var newPos = $(this).prevAll().length + 1;
  advanceSlideshow(newPos);
}

function advanceSlideshow(nextPos) {
  var pos = $('#slideshow').data('position');
  var country = currentCountry();
  if (!nextPos)
    nextPos = (pos < 3) ? pos + 1 : 1;
  $('#slideshow').data('position', nextPos);
  var offset = (-387 * (nextPos - 1)).toString() + 'px'; 
  $('#slideshow').animate({backgroundPosition: '0 ' + offset}, 500, function() {
    $(bulletpoints[nextPos-1]).addClass('bulletpoint-current');  
    $(slidetexts[nextPos-1]).removeClass('invisible');    
  });  
  var bulletpoints = $('#bulletpoints').children();
  var slidetexts = $('#slide-container').children('.slide-text');
  $(bulletpoints[pos-1]).removeClass('bulletpoint-current');
  $(slidetexts[pos-1]).addClass('invisible');
}

function getLatestStats() {
  var code_fields = $('.retailers-tab').children('input');
  for (var i=0; i < code_fields.length; i++) {
    var code = $(code_fields[i]).attr('country');
    if (code == 'GB') code = 'uk'; // I should have thought about this. Ugly.
    // var address = 'http://' + code + '.invisiblehand.co.uk/stats/savings?callback=?';
    var address = 'http://rep.invisiblehand.co.uk/stats/savings?country=' + code + '&callback=?';
    var doAjax = function(c) {
      $.getJSON(address, {}, function(data) {                
        if (c == 'uk') c = 'GB'; // Very ugly. What I was thinking about?
        $('#stats').data('stats' + c, data);
        updateStats();
        })
    }
    doAjax(code);
  }
}

function getRetailers() {
  var address = 'https://lb.invisiblehand.co.uk/retailers/images?callback=?'
  $.getJSON(address, {}, function(data) {        
    $('#retailers').data('retailers', data.retailers);
    $('#overall-retailers-number').text(data.retailers.length);
    var counters = {};
    for (var i=0; i< data.retailers.length; i++) {
      var region = data.retailers[i].region;
      if (region == 'UK')
        region = 'GB'; // No, I can't write code like that... it's impossible...
      counters[region] = (counters[region] |= 0) + 1;
    }
    var retailersTabs = $('.retailers-tab');
    for (i = 0; i < retailersTabs.length; i++) {      
      var country = $(retailersTabs[i]).children("input[type='hidden']").attr('country');      
      $($('#retailers-logos-' + country)).find('.retailers-in-country').text((counters[country] || '') + ' ');
    }
    if ($('#supported-retailers').length > 0) {
      var original_div = $($('.retailer-logo')[0]);
      var div = original_div.clone();
      $('.retailer-logo').remove();
      for (var i=0; i < data.retailers.length; i++) {
        var region = data.retailers[i].region;
        if (region == 'UK')
          region = 'GB'; // Aaaaaaaaaaaaaaah!        
        var newdiv = div.clone();
        var imageTag = $('<img />');
        imageTag.attr('src', 'http://lb.invisiblehand.co.uk' + data.retailers[i].image);
        $('img', newdiv).replaceWith(imageTag);
        $('a', newdiv).attr('href', data.retailers[i].url);        
        var doUpdate = function(r, d) {
          setTimeout(function() {$('#retailers-logos-' + r + ' .more-retailers').before(d)}, 500);
        }
        doUpdate(region, newdiv);
      }
    }
  });
}

function updateStats() {
  var country = currentCountry();
  var data = $('#stats').data('stats' + country);
  if (data == undefined)
    return; 
  // using innerHTML or jQuery somehow interferes with rounded corners that get screwed up after innerHtml modification
  // so we're replacing the element as a hack
  replaceHtml('total-savings-figure', commaFormatted(data.total, 10));
  replaceHtml('average-saving-figure', commaFormatted(data.average, 3, true));
}

// (c) http://ajaxian.com/archives/replacehtml-for-when-innerhtml-dogs-you-down
function replaceHtml(el, html) {
  var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
  var newEl = document.createElement(oldEl.nodeName);
  // Preserve the element's id and class (other properties are lost)
  newEl.id = oldEl.id;
  newEl.className = oldEl.className;
  // Replace the old with the new
  newEl.innerHTML = html;
  oldEl.parentNode.replaceChild(newEl, oldEl);
  /* Since we just removed the old element from the DOM, return a reference
  to the new element, which can be used to restore variable references. */
  return newEl;
}; 

// http://www.web-source.net/web_development/currency_formatting.htm
// modified by E. Shadchnev
function commaFormatted(amount, fieldSize, decimals) {
	var delimiter = ","; // replace comma if desired 
	if (decimals)
	  var i = Math.round(amount * 100) / 100;
	else
	  var i = Math.round(amount);
	if(isNaN(i)) { return ''; }
	i = Math.abs(i);
	if (decimals) {
	  var res = i.toString();
	  if (res.match(/\.\d$/)) { res = res + '0'};
	  return currency() + res;
  }
	var n = new String(i);
	var a = [];
	while(n.length > 3)
	{
		var nn = n.substr(n.length-3);
		a.unshift(nn);
		n = n.substr(0,n.length-3);
	}
	if(n.length > 0) { a.unshift(n); }
	n = currency() + a.join(delimiter);
	return n;
}

function currency() {
  switch (currentCountry()) 
  {
    case 'US':
      return '$';
    case 'GB':
      return '&pound;';
    case 'DE':
      return '&euro;'
    default:
      return '?'
  }    
}

function currentCountry() {
  return $('.retailers-tab-active').children("input[type='hidden']").attr('country');
}

function homepageTabClick(tab) {
  $(tab).siblings('.retailers-tab').removeClass('retailers-tab-active');
  $(tab).siblings('.retailers-tab').addClass('retailers-tab-inactive');
  $(tab).removeClass('retailers-tab-inactive');
  $(tab).addClass('retailers-tab-active');
  var country = currentCountry();
  $('#retailers-logos-' + country).removeClass('invisible');
  $('#retailers-logos-' + country).siblings().addClass('invisible');
  updateStats();
  /*
  The following lines work around an IE7 bug which causes #retailers-summary to not to be drawn
  after a tab is clicked. Anything that forces IE7 to rerender the element (e.g. css update) helps.
  I hate Internet Explorer.  
  */
  $('#retailers-summary').css('overflow', 'hidden');
  $('#supported-retailers h2').css('overflow', 'hidden');
}

function submitEmail() {
  var email = $('#sign-up-input').val();
  if (email == ''){
    $.prompt("Please enter your e-mail address in the box on the left");
    return;
  }
    
  if (isValidEmail(email)) {
    $.getJSON('http://us.invisiblehand.co.uk/early_adopters/create?callback=?', {email: email})    
    $.prompt("Thank you!");
  } else {
    $.prompt("Sorry, '" + email + "' does not look like a valid e-mail. Typo?");
  }
  
}

function isValidEmail(email) {
	return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
}

