var sitePath = (document.domain == "eu.web") ?'/eu':'';
var currentPage = 'homepage';
$(document).ready(function(){
    if (jQuery.browser.opera) {// css fixed for opera
     $('body').addClass('opera');
    }
    var theframes = document.getElementsByTagName('iframe'); // iframe transparent
	for(var i = 0; i < theframes.length; i++)
	{
		theframes[i].setAttribute("allowTransparency","true");
	}

    //button style
    $('.vignettebutton').wrap('<div class="buttonWrap">');
    $('.buttonWrap').prepend('<div class="front buttonSprite"></div>')
         .append('<div class="back buttonSprite"></div><div class="clear"></div>');
    //roll over effect
    $('.button,.buttonWrap,.navigation .wp-paginate a').hover(function(){$(this).css('opacity','0.8')}, function(){$(this).css('opacity','1')});
    //image roll over
    $('.goto-map,.goto-list').css('opacity','0.7');
    $('.goto-map,.goto-list').hover(function(){$(this).css('opacity','1')}, function(){$(this).css('opacity','0.7')});
    
    $('.field').wrap('<div class="fieldWrapper">');
    $('.fieldWrapper').prepend('<div class="leftc buttonSprite"></span>').append('<div class="rightc buttonSprite"></div><div class="clear"></div>');
    $('.box').wrapInner('<div class="body">').prepend('<div class="leftc bar"></div>').append('<div class="rightc bar"></div><div class="clear"></div>');

    $('.buttonWrap').has('.buttonWrap .vignettebutton.left').addClass('left');
    $('.buttonWrap').has('.buttonWrap .vignettebutton.right').addClass('right');
    if($('.fieldWrapper .field').hasClass('left')) $('.fieldWrapper').addClass('left');
    
    /*What's In It For me dropdown menu*/
    $('.page-item-8 ul:first').addClass('close for-me-list');
    $('.top-nav .page-item-8 ul ul,.top-nav .page-item-10 ul ul,.carousel').show();
    $(".page-item-8").hoverIntent({
        sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
        interval: 50,   // number = milliseconds for onMouseOver polling interval
        over: show,     // function = onMouseOver callback (required)
        timeout: 300,   // number = milliseconds delay before onMouseOut
        out: hide       // function = onMouseOut callback (required)
    });

    /*The EU near me navigation*/
    $('.page-item-10 ul:first').addClass('close');
    $('.page-item-10 ul:first').addClass('near-me-list');
    $(".page-item-10").hoverIntent({
        sensitivity: 1, // number = sensitivity threshold (must be 1 or higher)
        interval: 50,   // number = milliseconds for onMouseOver polling interval
        over: show,     // function = onMouseOver callback (required)
        timeout: 300,   // number = milliseconds delay before onMouseOut
        out: hide       // function = onMouseOut callback (required)
    });

    /*What's In It For me subpage navigation*/
    $('.color-nav li').hover(
        function(){
            pageClass = $(this).attr('class').split(" ");
            $('.map-nav li.'+ pageClass[1]+ ' a').trigger('mouseover');
            
        },function(){
            $('.map-nav li.'+ pageClass[1]+ ' a').trigger('mouseout');
        }        
    );
    /*What's In It For me map*/
    simple_tooltip(".map-nav a","tooltip");
    $('.map-nav li:not(.current_page_item) a').mouseover( function() {
        $(this).addClass('hover');
            
    });
    $('.map-nav li:not(.current_page_item) a').mouseout( function() {

            $(this).removeClass('hover');
            
    });
    /* postcode search form */
    $('#near_form').submit(function(){
        search_postCode();
        return false;
    });
   
    /* news categories icons*/
    $('<span class="sprite"></span>').insertBefore('.news-categories .cat-item a');

//remember font size
    var originalFontSize = $('#container').css('font-size');

    if($.cookie('FontScale')){
        FontScale = $.cookie('FontScale');
    }else{
        FontScale = 1;
        $.cookie("FontScale", FontScale,{path: sitePath});
    }

   changeFontSize(FontScale,originalFontSize);
   
// Reset Font Size  
  $(".medieumFont").click(function(){changeFontSize(1,originalFontSize);});  
  $(".largeFont").click(function(){changeFontSize(1.1,originalFontSize);});
  $(".smallFont").click(function(){changeFontSize(0.9,originalFontSize);});

  $(".carousel").jCarouselLite({
       btnNext: ".euNews .next, .euCaseStudies .next",
       btnPrev: ".euNews .prev, .euCaseStudies .prev",
       visible: 1
  });
  $(".carousel2").jCarouselLite({
       btnNext: ".euMyths .next,.another",
       visible: 1
  });
  $(".carousel3").jCarouselLite({
       btnNext: ".car-ui .next",
       btnPrev: ".car-ui .prev",
       visible: 1
  });
  $('.prefilled').each(function(e){
     
      $(this).focus(function(e){
          if ($(this).val()==$(this).attr('title')) $(this).val('');
      });
      $(this).blur(function(e){
          if ($(this).val()=='') $(this).val($(this).attr('title'));
      });
  });
  $('.color-nav .page_item:last').css('margin-bottom', '0');

  $('#page_id').change(function(){
      var url = $('#page_id').select().val();
      if(url.length > 0){
          $('#selectRegionForm').submit();
      }
  });
  
  $('#page_id_1').change(function(){
      var url = $('#page_id_1').select().val();
      if(url.length > 0){
          $('#for_me_form').submit();
      }
  });
  
  $('#submit-full-region-list').click(function(){
        var url = document.getElementById('combobox-full-region-list').value;
        window.open(url);
  });

  $('#myth-filter-date').change(function(){
      var url = $('#myth-filter-date').select().val();
      if(url.length > 0){
        $('#myth-filter-date-n-cat').submit();
      }
  });
  $('#myth-filter-cat').change(function(){
      var url = $('#myth-filter-cat').select().val();
      if(url.length > 0){
        $('#myth-filter-date-n-cat').submit();
      }
  });

  /* toggler on your story page*/
    $('.toggler .title').click(function() {
        $(this).next('.text').toggle('fast');
        $(this).toggleClass('opened');
        if ($(this).hasClass('opened'))
            $(this).children('.right').children('.toggler-txt').text('Hide');
        else
            $(this).children('.right').children('.toggler-txt').text('Show');
        
        return false;
    });

    /* submit your story form validation */
    $(".wpcf7-form").validate({
		rules: {
			terms:{
				required: true
			}
		},
		messages: {			
			terms: "Please accept our Terms & Conditions."
		},
        errorPlacement: function(error, element) {
            element.parent().append(error);
        },
        errorClass: "error-msg",
        validClass: "valid",
        success: "check-ico",
        errorElement:'div'


    });

    /* sitemap */
    $('<span class="buttonSprite"></span>').insertBefore('.site-map li a');
    if ($("#map_canvas").length){
        initialize();
    }
	/* what's for me main page tube map google tracking code*/
	$('.tube-list a').click(function(){		
		_gaq.push(['_trackEvent','tube map','travel and working',$(this).attr('title')]);
	});

    
});

function changeFontSize(FontScale,originalFontSize)
{   
    
    var currentFontSizeNum = parseFloat(originalFontSize, 10);
    var newFontSize = currentFontSizeNum*FontScale;
    //alert(FontScale);
    
    $('.fontScale a').removeClass('currentFont');
    if (FontScale==0.9)
        $('.smallFont').addClass('currentFont');
    else if (FontScale==1)
        $('.medieumFont').addClass('currentFont');
    else 
        $('.largeFont').addClass('currentFont');
    
    $('#container').css('font-size', newFontSize);
    $.cookie("FontScale", FontScale,{path: sitePath});
    return false;
  
}


function show() {
    var menu = $(this);
    menu.children("ul:first").slideDown();
}

function hide() {
    var menu = $(this);
    menu.children("ul:first").slideUp();
    
}

function initialize(){
    var map = new GMap2(document.getElementById("google-map"));
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(51.595842,-1.881409), 8);
    var point = new GLatLng(51.595842,-1.881409);
    var marker = new GMarker(point);
    map.addOverlay(marker);
    GEvent.addListener(marker, "click", function()
    {marker.openInfoWindowHtml("Marker #<b>" +  + "</b>");});
}

(function ($) {
// VERTICALLY ALIGN FUNCTION
$.fn.vAlign = function() {
    return this.each(function(i){
    var ah = $(this).height();
    var ph = $(this).parent().height();
    var mh = (ph - ah) / 2;    
    $(this).css('padding-top', mh);
    
    });
};
})(jQuery);
function simple_tooltip(target_items, name){
$('.page-item-46 a').attr('title','Mobile');
$(target_items).each(function(i){        
		$("body").append("<div class='"+name+"' id='"+name+i+"'><div class='tooltip-text'><p>"+$(this).attr('title')+"</p></div></div>");
		var my_tooltip = $("#"+name+i);

		if($(this).attr("title") != "" && $(this).attr("title") != "undefined" ){
			$(this).click(function(){_gaq.push(['_trackEvent','map', currentPage ,my_tooltip.find('.tooltip-text p').text()]);});
                    var left_pos;
                    var top_pos;
                    var offset = -10;
                    top_pos =  $(this).offset().top;
                    left_pos = $(this).offset().left;

                    top_pos  -= my_tooltip.outerHeight() - offset;
                    left_pos += $(this).outerWidth() + offset;

                    // adjust Y
                    var height = my_tooltip.outerHeight() + $(this).outerHeight();
                    top_pos += height;

                    // adjust X
                    var width = my_tooltip.outerWidth() + $(this).outerWidth();
                    left_pos -= width / 2;

                    if($(this).parent().hasClass('current_page_item')){
                        $(this).removeAttr("title");
                        my_tooltip.css({display:"block", top:top_pos,left:left_pos});
                        my_tooltip.addClass('tooltip-current');
                        my_tooltip.find('.tooltip-text p').vAlign();
                    }else{
                        $(this).removeAttr("title").mouseover(function(){
                                my_tooltip.css({display:"block", top:top_pos,left:left_pos}).fadeIn(400);
                                my_tooltip.find('.tooltip-text p').vAlign();

                        }).mouseout(function(){
                                my_tooltip.css({display:"none"});
                        });
                    }
                }
	});

}

function search_postCode(){
    $('.errorMessage_postcode').fadeOut();
    $.ajax({
        type: "GET",
        cache : true,
        async: true,
        url: sitePath+"/ajax/postcode_check.php?postcode=" + $('#postcode').val(),
        beforeSend: function () {

        },
        success: function(data) 
        {
            if (data)
            {
                if (data.length == 1)
                {
                    if (data == 1) {
                        var message1 = 'Enter at least the 3 first characters of your postcode.';
                        $('#errorMessage_postcode').html(message1);
                        $('.errorMessage_postcode').fadeIn('slow');
                    } else if (data == 2) {
                        var message2 = 'Enter at least the 4 first characters of your postcode.';
                        $('#errorMessage_postcode').html(message2);
                        $('.errorMessage_postcode').fadeIn('slow');
                    } else if (data == 3) {
                        var message3 = 'Your postcode is invalid.';
                        $('#errorMessage_postcode').html(message3);
                        $('.errorMessage_postcode').fadeIn('slow');
                    } else if (data == 4) {
                        var message4 = 'Enter at least the 2 first characters of your postcode.';
                        $('#errorMessage_postcode').html(message4);
                        $('.errorMessage_postcode').fadeIn('slow');
                    }
                }
                else
                {
                    // DEBUG
                    //var message1 = data;
                    //$('#errorMessage_postcode').html(message1);
                    //$('.errorMessage_postcode').fadeIn('slow');

                    document.location.href = data;
                }
            }
        }
    });
}

/** twitter feed  **/
function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
      return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<span>'+status+'</span>');
    twittTime = ' <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a>';
  }
  document.getElementById('twitter_update').innerHTML = statusHTML.join('');
  document.getElementById('tiwtter_time').innerHTML = twittTime;
}
function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  delta = delta + (relative_to.getTimezoneOffset() * 60);

  if (delta < 60) {
    return 'less than a minute ago';
  } else if(delta < 120) {
    return 'about a minute ago';
  } else if(delta < (60*60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if(delta < (120*60)) {
    return 'about an hour ago';
  } else if(delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if(delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}


function initialize() {
    var map;
    var geoXml;
  if (GBrowserIsCompatible()) {
    geoXml = new GGeoXml("http://life.lifevideos.eu/environment/life/countries/kml/uk.kml");
    map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(55.378051,-3.435973), 5);
    map.setMapType(G_PHYSICAL_MAP);
    map.addControl(new GSmallMapControl());
    map.addOverlay(geoXml);
  }
}



