$.extend({
  decodeEntities: function(value) {
    return $('<div/>').html(value).text();
  }
});

var GB = {};

// On page scripts can store URLs in here before document ready
GB.urls = {};

GB.languageSelector = function() {
  $('.languageSelector').hover(function(){
    $(this).children('div').toggleClass('hover');
  });
}

GB.userMenu = function() {
  var $userMenu = $('.widget.userMenu'),
      userData = ($.cookie('userLoggedIn') || '').split('_');

  if (userData[0] == 'true') {
    // Logged in
    $userMenu.children('ul').html([
      '<li>Welcome <a href="' + GB.urls.account + '">' + $.trim(userData[1]) + '</a></li>',
      '<li><a href="' + GB.urls.editAccount + '">Edit profile</a></li>',
      '<li class="last"><a href="' + GB.urls.logout + '">Log-out</a></li>'
    ].join(''));
  } else {
    $userMenu.find('li:first').remove();
  }

  // Test
  // $.cookie('userLoggedIn', 'true_Richard');
}


/*****new function for drop-down ********/
GB.navigationDropdown = function (classname, index) {
	   
  var divLocator = '#navigation ' + classname;
  var liLocator = '#navigation .menu.horizontal>ul>li:eq(' + index + ')';
   
   if (!$(divLocator).length) return;

   $(divLocator).remove().appendTo(liLocator);
   $(liLocator)
   .addClass('parent')
   .hover(
   function () {
   $(this).addClass('hover');
   },
   function () {
   $(this).removeClass('hover');

   }
   );
}

GB.trailersWithOverlay = function() {
  $('.trailersWithOverlay').each(function() {
    var $this = $(this);
    $this.addClass('trailersWithOverlayJS');
    $this.find('.trailer').each(function() {
      var titleH = $(this).children('h5').remove();
      if(titleH.size()==0) {
    	  titleH = $(this).find('.article h3').remove();
      }
      var href = $(this).find('a').attr('href');
      $(this).find('p.summary').wrap('<div class="overlay"></div>');
      $(this).find('.overlay').prepend(titleH);
      $(this).find('p.summary').hide();
      $(this).prepend('<a href="' + href + '" class="blocker"></a>');
    });
    $this.find('.trailer').hover(
      function() {
        $(this).find('p.summary').slideDown('fast');
      },
      function() {
        $(this).find('p.summary').slideUp('fast');
      }
    );
  });
}

GB.shoppingSearch = function() {
  if ($('.shoppingLocatorForm').length == 0) return;

  var $searchString = $('.shoppingLocatorForm input[name="searchStringShoppingTmp"]');
  var w = $searchString.outerWidth() - parseInt($searchString.css('border-left-width').replace('px', '')) - parseInt($searchString.css('border-right-width').replace('px', ''));
  $searchString.autocomplete(GB.urls.brandsAutocomplete, {maxItemsToShow: 10, width: w});
  var searchStringDisplay = '';
  $('.shoppingLocatorForm form').submit(function(event) {
        //alert($(this).find('select[name="citySelect"] option:selected').length);
    var $this = $(this),
        articleType = 'GlobalBlueBrandListing',
        brand = $.trim($this.find('input[name="searchStringShoppingTmp"]').val()),
        city = $.trim($this.find('select[name="citySelect"]').val()),
        area = $.trim($this.find('select[name="areaSelect"]').val()),
        product = $.trim($this.find('select[name="productSelect"]').val()),


        citySelectDisplay = $.trim($this.find('select[name="citySelect"] option:selected').text()),
        productSelectDisplay = $.trim($this.find('select[name="productSelect"] option:selected').text());



    if (brand + city + area + product == '') {
      event.preventDefault();
      return;
    }

    $this.find('input[name="articleType"]').remove();

    if (brand != '' && city + area == ''){
        articleType = 'GlobalBlueBrandWrapper';
    }

    if (brand != ''){
    	product = '';
    	productSelectDisplay = '';
        citySelectDisplay = ', ' + citySelectDisplay;
        if(area != '') area = ', ' + area;
    }

    if (city != ''){
    	city = 'section: (' + city + ')';
        if(area != '') area = ', ' + area;
    }
    if (city == ''){
    	citySelectDisplay = '';
    }

    if (product != '') {
    	product = 'section: (' + product + ')';
        if(city != '') productSelectDisplay = ', ' + productSelectDisplay;
   	}

    if (product == '') {
    	productSelectDisplay = '';
   	}

    var values = [];
    $([brand, city, area, product]).each(function(i, value) {
      if (value != '') values.push(value);
    });

    $('.shoppingLocatorForm input[name="searchString"]').val(values.join(', '));
    $this.append('<input type="hidden" name="articleType" value="' + articleType + '">');
    $this.append('<input type="hidden" name="searchStringDisplay" value="' + brand + citySelectDisplay + area + productSelectDisplay  + '">');
  });

  $('.shoppingLocatorForm select[name="citySelect"]').change(function() {
    if ($(this).val() != '') {
      var cityId = $(this).val();
      $('.shoppingLocatorForm select[name="areaSelect"]').attr('disabled', 'true').find('option[value!=""]').remove();
      $.ajax({
        url: GB.urls.areas,
        dataType: 'json',
        data: {citySectionId: cityId},
        success: function(data) {
          var optionsHtml = [];
          for (var i = 0; i < data.length; i++) {
            optionsHtml.push('<option value="'+ data[i] +'">'+ data[i] +'</option>');
          }
          $('.shoppingLocatorForm select[name="areaSelect"]').removeAttr('disabled').append(optionsHtml.join(''));
        }
      });
    } else {
      $('.shoppingLocatorForm select[name="areaSelect"]').attr('disabled', 'true').find('option[value!=""]').remove();
    }
  });
}

GB.shoppingSearchPlaceholders = function() {
  $('.shoppingLocatorForm input.field').each(function() {
    var placeholder = $('label[for|="' + $(this).attr('name') + '"]').text();
    $(this).val(placeholder).addClass('blurred').data('placeholder', placeholder);
    $(this)
      .focus(function() {
        if ($(this).val() == $(this).data('placeholder')) $(this).val('');
        $(this).removeClass('blurred');
      })
      .blur(function() {
        if ($.trim($(this).val()) == '') {
          $(this).val($(this).data('placeholder')).addClass('blurred');
        }
      });
  });

  function clearPlaceholders() {
    $('.shoppingLocatorForm input.field').each(function() {
      if ($(this).val() == $(this).data('placeholder')) $(this).val('');
    });
  }

  $('form').submit(clearPlaceholders);
  $(window).unload(clearPlaceholders);
  window.onbeforeunload = clearPlaceholders;
}

GB.brandsList = function() {
  var $brandsList = $('.brandsList');
  if (!$brandsList.length) return;

  $brandsList.addClass('brandsListJS').prepend('<ul class="nav"></ul>');

  for (var i = 0; i <= 26; i ++) {
    var id = (i == 26) ? '123' : String.fromCharCode(65 + i);
    if ($('#brands' + id).length) {
      $brandsList.children('ul.nav').append('<li><a href="#brands' + id + '">' + id + '</a></li>');
    } else {
      $brandsList.children('ul.nav').append('<li><span>' + id + '</span></li>');
    }
  }

  $('.brandsList ul.nav a')
    .click(function(event) {
      event.preventDefault();
      var id = $(this).attr('href').split('#')[1];
      $('#' + id).css('display', 'block').siblings(':not(.nav)').css('display', 'none');
      $(this).parent().addClass('current').siblings('.current').removeClass('current');
    })
    .eq(0).click();
}

GB.createMap = function(mapId, markers) {
  if (!GBrowserIsCompatible()) return;

  var defaultIcon = new GIcon(G_DEFAULT_ICON);
  defaultIcon.image = GB.urls.skin + 'images/map-marker-unspecified.png';
  defaultIcon.shadow = GB.urls.skin + 'images/map-marker-shadow.png';
  defaultIcon.transparent = GB.urls.skin + 'images/map-marker-transparent.png';
  defaultIcon.iconSize = new GSize(25,34);
  defaultIcon.iconAnchor = new GPoint(12,34);
  defaultIcon.shadowSize = new GSize(41,34);
  defaultIcon.infoWindowAnchor = new GPoint(13,0);
  defaultIcon.imageMap = [16,0,18,1,20,2,21,3,21,4,22,5,23,6,23,7,23,8,24,9,24,10,24,11,24,12,24,13,24,14,23,15,23,16,23,17,22,18,21,19,21,20,20,21,19,22,19,23,18,24,18,25,17,26,16,27,16,28,15,29,14,30,14,31,13,32,11,32,10,31,9,30,9,29,8,28,7,27,7,26,6,25,5,24,5,23,4,22,3,21,3,20,2,19,2,18,1,17,1,16,0,15,0,14,0,13,0,12,0,11,0,10,0,9,0,8,1,7,1,6,2,5,2,4,3,3,4,2,5,1,7,0];

  var bounds = new GLatLngBounds(),
      icons = {},
      map = new GMap2(document.getElementById(mapId));

  $.each(markers, function(i, value) {
    var point = new GLatLng(value.lat, value.lng);

    bounds.extend(point);

    var type = ($.trim(value.type) !== '') ? value.type : 'unspecified';
    if (icons[type]) {
      var icon = icons[type];
    } else {
      var icon = new GIcon(defaultIcon, GB.urls.skin + 'images/map-marker-' + type + '.png');
      icons[type] = icon;
    }

    var html = '',
        leadtext = $.trim($.decodeEntities(value.leadtext)),
        title = $.trim($.decodeEntities(value.title));

    if (value.url !== window.location.href) {
      title = '<a href="' + value.url + '">' + title + '</a>';
    }
    html += '<p class="title">' + title + '</p>';
    if (leadtext != '') html += '<p class="leadtext">' + leadtext + '</p>';

    var marker = new GMarker(point, {icon: icon});
    GEvent.addListener(marker, 'click', function() {
      if (html != '') marker.openInfoWindowHtml('<div class="infoWindow">' + html + '</div>', {maxWidth: 220});
    });

    map.addOverlay(marker);
  });

  map.setCenter(bounds.getCenter(), Math.min(15, map.getBoundsZoomLevel(bounds) - 1));
  map.addControl(new GSmallZoomControl3D());

  $(document).unload(function() {
    GUnload();
  });
}

GB.pageTools = function() {
  if ($('.gbPageTools').length == 0) return;
  GB.pageToolsFontSizes();
  GB.pageToolsClippings();
}

GB.pageToolsFontSizes = function() {
  var fontSizes = {s: 75, m: 100, l: 125};
  function setFontSize(size) {
    if (size == null) return;
    $('.storyContent .body').css('font-size', fontSizes[size] + '%');
    $('.gbPageTools .textSize .' + size).addClass('current').siblings().removeClass('current');
    $.cookie('fontSize', size);
  }

  $('.gbPageTools .textSize a').click(function(event) {
    event.preventDefault();
    setFontSize($(this)[0].className.split(' ')[0]);
  });

  setFontSize($.cookie('fontSize'));
}

GB.pageToolsClippings = function() {
  if ($('.gbPageTools .clipthis').length == 0) return;

  var html = '',
      userData = ($.cookie('userLoggedIn') || '').split('_');

  if (userData[0] == 'true') {
    // Logged in
    var clippedArticles = ($.cookie('clippings') || '').split(encodeURIComponent(','));
    if ($.inArray(GB.articleId, clippedArticles) >= 0) {
      // Article already clipped
      html += '<h2>Clipped</h2><p>You’ve already clipped this page.<br /><a href="' + GB.urls.clippings + '">View all your clippings</a>.</p>';
      $('.gbPageTools .clipthis a').replaceWith('<span class="clipthis_button">Clipped</span>');
    } else {
      html += '<h2>Clip this</h2><p>Save this page to your account for printing, sharing or future reference.<br /><a href="' + GB.urls.clippings + '">View all your clippings</a>.</p>';
    }
  } else {
    html += '<h2>Clip this</h2><p>Save this page to your account for printing, sharing or future reference.<br /><a href="' + GB.urls.login + '">Log in</a> or <a href="' + GB.urls.register + '">register</a> to get started.</p>';
  }

  html = '<div class="clippingsBubble"><div class="clippingsBubbleWrapper">' + html + '</div></div>';

  $('.gbPageTools .clipthis')
    .prepend(html)
    .hover(
      function() {
        var $self = $(this);
        if ($self.data('timeout') !== undefined) {
          window.clearTimeout($self.data('timeout'));
        }
        $self.addClass('hover');
        $('#at15s').css('display', 'none');
      },
      function() {
        var $self = $(this);
        var timeout = window.setTimeout(function() {
          $self.removeClass('hover').removeData('timeout');
        }, 500);
        $self.data('timeout', timeout);
      }
    );

  $('.gbPageTools .addthis_button').mouseenter(function() {
    $('.gbPageTools .clipthis').removeClass('hover');
  });

  // Test
  // $.cookie('clippings', '1');
}

GB.clippingsForm = function() {
  if ($('.clippingsForm').length == 0) return;

  // Filter
  var $currentFilterOption = $('.clippingsForm .filter option:selected');
  $('.clippingsForm .filter')
    .find('input[type="submit"]').css('display', 'none')
    .end()
    .find('select').change(function(event) {
      $('.clippingsForm .filter form').submit();
    });

  // Select all
  $('.clippings input#select_all').click(function() {
    if ($(this).is(':checked')) {
      $('.clippings input[type="checkbox"]').attr('checked', 'checked');
    } else {
      $('.clippings input[type="checkbox"]').removeAttr('checked');
    }
  });
}

$(document).ready(function() {
  GB.languageSelector();
  GB.trailersWithOverlay();
  GB.shoppingSearchPlaceholders();
  GB.shoppingSearch();
  GB.brandsList();
  GB.pageTools();
  GB.clippingsForm();
  addTrackingToMailToLink();
  setEvent();
});

//$(document).ready( function() { addTrackingToMailToLink() });

function addTrackingToMailToLink()
{
    $("a").each( function(index) {
        if(this.href.indexOf("mailto:") != -1) {
            //add onlcick event handler
            $(this).click(function() {emailSentTracking($(this).attr("href").substring(7))});
        }
    });
}

function emailSentTracking(emailAddress)
{
        _gaq.push(['_trackPageview', '/mailto/' + emailAddress], ['b._trackPageview', '/mailto/' + emailAddress]);
}

function loggedinUserTracking()
{
    _gaq.push(['_setCustomVar', 2,	'User Type', 'Registered',	 2	], ['b._setCustomVar', 2,	'User Type', 'Registered',	 2	]);
}

var aPos='global-blue.com';
var bPos='secure.global-blue.com';
var oDiv;

function setEvent(){
	oDiv = document.getElementsByTagName("a");
	for (var i = 0;i < oDiv.length; i++) {
	   if(oDiv[i].onclick !=null)
	   {
	       var oldFunction = oDiv[i].onclick;
	       oDiv[i].onclick=function(){
	       oldFunction();
	       return checkGoogle(this.href);
	       }
	       continue;
	   }
	 
	 oDiv[i].onclick=function(){
	  return checkGoogle(this.href);
	 }
	}
	}



function checkGoogle(aURL){

	aURL = (typeof aURL == 'undefined') ? '' : aURL;

	//check if URL has http: in it
	if(aURL.indexOf('http:') > -1){

		//if it does, then check against first URL
		if((aURL.indexOf(aPos) == -1) && (aURL.indexOf(bPos) == -1)){

			//if there is no index, then run Google analytics

					_gaq.push(['_trackPageview','/outbound/'+aURL], ['b._trackPageview','/outbound/'+aURL]);
			
		}


		//otherwise, it is an internal link, so just redirect
		
	}

	//if it doesnt have http:// then just redirect
	
}


$(document).ready(function(){
  $('.close-link').click(function(){
       window.close();
       return false;
   });
  $(".navimages").live("click",function(){
    var mpuHeight ="250";
    var mpuWidth = "300";
    $("#mpuAd").html("");
    
    $("#mpuAd").append("<iframe src='/add.html' scrolling='no' marginwidth='0' margineheight='0' height='"+mpuHeight+"' width='"+mpuWidth+"' frameBorder='0' style='overflow:hidden;'></iframe>");
    
    
  });
});


