var $service = null;
var $pdf = null;
var $video = null;

$(".photogallery .home_slideshow img:first").css('display','block');

$(window).load(function() {
  if( $('.slidetabs').length > 0 ) {
    $('.slidetabs').tabs('.home_slideshow > img', {
      effect: 'fade',
      fadeOutSpeed: 'slow',
      rotate: true
      }).slideshow({interval:10000,autoplay:true});
  }

  if( $('.slidetabs_about') ) {
    $('.slidetabs_about').tabs('.about_slideshow > img', {
      effect: 'fade',
      fadeOutSpeed: 'slow',
      rotate: true
      }).slideshow({interval:6000,autoplay:true});
  }
  
  //document.title = "PBS " + section_name + " ";
  
})
$(document).ready(function() {

  if( $('.scrollable .items .service_wrapper').length > 6 ) {
    // initialize scrollable with mousewheel support
    $("#services_outer #actions .next").css('display', 'block');
    $(".scrollable").scrollable({ vertical: true, mousewheel: true });
  }

  $(".service_wrapper").click( function() {
    service = $(this).attr('id').replace("service_","");
    window.location.href = ('#' + service);
  });
  
  function startService(service_id){
    if( $service == null || $service.attr('id') != service_id ) {
      new_service = $('#'+service_id);
      if( $('#see_more').is(':visible') ) {
        new_service = $('#'+service_id);
        $('#see_more').slideUp('fast', function() {
          toggleService(new_service);
        });
      } else {
        toggleService(new_service);
      }
    }
  }

var service_name = null;

  function toggleService(new_service) {
    if ( $service != null ) $service.removeClass('active');
    $service = $(new_service);
    $service.addClass('active');
    $pdf = null;
    
    $video = null;
    var link_id = $service.attr('id').split('_')[1];
    var link="http://pbs.es/" + locale + "/#" + link_id;

    service_name = $('div.see_more .title', $service).text();

    var motto = $('div.see_more .motto', $service).text();
    if (motto != undefined) {
      service_name += ": " + motto;
    }

    var email_texts = {
      subject: escape(service_name + "|" + link)//,
      //template: "{0}"
    };

    $.each( { video: $('div.media a.video', $service), pdf: $('div.media a.pdf', $service) }, function( media_type, element) {
      if( element[0]) {
        eval("$" + media_type +" = $(element)");
      }
    });

    $('#see_more').html( $('div.see_more', $service).html() );
    
    if(locale!='cn')Cufon.replace('#see_more p', { fontFamily: 'helvetica-regular'});

    if(locale!='cn')Cufon.replace('#see_more p strong', { fontFamily: 'helvetica-neue-bold'});
        
    $('#see_more .content').removeClass('hidden');

    $('#big_container').html( function() {
      var player_container = '<div id="player" class="media_content"></div>';
      var pdf_link = null;
      if ($pdf) {
        pdf_link = '<a href=' + $pdf.attr('href') + ' id="download_pdf">' + $pdf.html() + '</a>';
      } else {
        pdf_link = ''; 
      }
      var see_more_link = '<a href="#" id="see_more_link">' + see_more_text + '<span></span></a>';
      var big_container_footer = '<div id="player_footer" class="media_footer"><div id="media_footer_inner">' + pdf_link + see_more_link + '</div><div id="bottom_bar"></div></div>';
      return player_container + big_container_footer;
    });


    //document.title = "PBS " + section_name + " ";

    
    if(send_email_texts != undefined){
      for (attrname in send_email_texts) { email_texts[attrname] = send_email_texts[attrname]; }  
    }

    if (locale == 'es') {
      var email_notices = {
        fill_required: 'Por favor, rellene los campos requeridos!',
        sending_email: 'Enviando email...',
        error_sending: 'Error enviando email',
        error_token: 'Error solicitando token',
        invalid_from_email: 'E-mail remitente inválido',
        invalid_to_email: 'E-mail destinatario inválido'
      };
    } else {
      var email_notices = {
        fill_required: 'Please fill in required fields!',
        sending_email: 'Sending email...',
        error_sending: 'Error sending email',
        error_token: 'Error requesting token',
        invalid_from_email: 'Sender e-mail is invalid',
        invalid_to_email: 'Receiver e-mail is invalid'
      };
    }
    var player=document.getElementById('player');
    var videoid=null;
    switch($service.attr('id').replace("service_","")){
      case 'atc':
        if(locale=='en')videoid='25967403';
        if(locale=='es')videoid='25944471';
        if(locale=='de')videoid='30897442';
        if(locale=='fr')videoid='30895417';
        if(locale=='pt')videoid='30893408';
        if(locale=='cn')videoid='31012644';
        break;
      case 'payroll':
        if(locale=='en')videoid='25944056';
        if(locale=='es')videoid='26010709';
        if(locale=='de')videoid='30901365';
        if(locale=='fr')videoid='30896461';
        if(locale=='pt')videoid='30894912';
        if(locale=='cn')videoid='31013796';
        break;
      case 'iwa':
        if(locale=='en')videoid='25943761';
        if(locale=='es')videoid='25944910';
        if(locale=='de')videoid='30899969';
        if(locale=='fr')videoid='30896050';
        if(locale=='pt')videoid='30894722';
        if(locale=='cn')videoid='31013213';
        break;
      case 'tps':
        if(locale=='en')videoid='25944162';
        if(locale=='es')videoid='26011001';
        if(locale=='de')videoid='30901924';
        if(locale=='fr')videoid='30896681';
        if(locale=='pt')videoid='30895070';
        if(locale=='cn')videoid='31013935';
        break;
      case 'iis':
        if(locale=='en')videoid='25943392';
        if(locale=='es')videoid='25944746';
        if(locale=='de')videoid='30899601';
        if(locale=='fr')videoid='30895823';
        if(locale=='pt')videoid='30894450';
        if(locale=='cn')videoid='31013075';
        break;
      case 'cso':
        if(locale=='en')videoid='31020346';
        if(locale=='es')videoid='25944618';
        if(locale=='de')videoid='30899028';
        if(locale=='fr')videoid='30895568';
        if(locale=='pt')videoid='30894145';
        if(locale=='cn')videoid='31012829';
        break;
    }
    if(videoid!=null)player.innerHTML='<iframe src="http://player.vimeo.com/video/'+videoid+'?autoplay=true" width="639" height="360" frameborder="0"></iframe>';
    if( $video && videoid==null ) {
      flowplayer('player', {
        src:'/swf/flowplayer-skinned.swf', 
        wmode: 'transparent'
      }, 
      {
        canvas: {
          backgroundGradient: 'none' 
        },
        clip: {
          url: $video.attr('href'), 
          scaling: 'fit', 
          autoPlay: false, 
          autoBuffering: true,
          bufferLength: 1,

		// track start event for this clip
		onResume: function(clip) {
		  _gaq.push(['_trackEvent', locale, 'Play', service_name]);
		},

		// track pause event for this clip. time (in seconds) is also tracked
		onPause: function(clip) {
		  //_gaq.push(['_trackEvent', locale, 'Pause', clip.url, parseInt(this.getTime())]);
		},

		// track stop event for this clip. time is also tracked
		onStart: function(clip) {
			_gaq.push(['_trackEvent', locale, 'Load', service_name]);
		},

		// track finish event for this clip
		onFinish: function(clip) {
			_gaq.push(['_trackEvent', locale, 'Finish', service_name]);
		}
        },	
        key: "#$06523228bc67fef5723",
        play: {
          label:null,
          replayLabel:null
        },
      	plugins: {
          controls: {
            bottom:5
          },
      		viral: {
      			// load the viral videos plugin
      			url: 'flowplayer.viralvideos-enhanced.swf',
      			embed: false,
      			/*share: {
      			  livespaces: false,
      			  myspace: false,
      			  digg: false,
      			  orkut: false,
      			  stubmbleupon: false,
      			  bebo:false
      			},*/
      			share: false,
      			email: {
      			  script: '/send_by_email?locale='+locale,
      			  texts: email_texts,
      			  notices: email_notices,
      			  required: ["name","email","to","subject"]
      			},
            canvas: {
              '.success' : {
                color: '#88ff88',
                fontSize:14
              },
              '.error' : {
                color: '#ff8888',
                fontSize:14
              }
            }
          }
      	}
      });
    }
  }

  $('#see_more_link').live('click', function() {
    if(locale!='cn')Cufon.replace('#see_more .content_header', { fontFamily: 'helvetica-neue-light' });
    if(locale!='cn')Cufon.replace('#see_more .content_header .title', { fontFamily: 'helvetica-neue-black' });
    $('#see_more').slideToggle();
    $("#bottom_bar").toggleClass('active');
    $(this).toggleClass('active');
    if($(this).hasClass('active')){
      _gaq.push(['_trackEvent', locale, 'See More', service_name]);
    }
    return false;
  });

  $('#see_more_link').live('hover', function() {
    $("#bottom_bar").toggleClass('hover');
  });

  $('.directions_wrapper a.directions').hover(function() {
    $(".directions_wrapper").toggleClass('hover');
  });

  $('.bottom .submit').hover(function() {
    $(this).toggleClass('hover');
  });

  $(".services .items .service_wrapper").hover(function(){
    $(this).addClass('hover');
  }, function (){
    $(this).removeClass('hover');
  });
  $("#footer #links li").hover(function(){
    $(this).addClass('hover');
  }, function (){
    $(this).removeClass('hover');
  });

  $('#see_more a.questions').live('hover', function() {
    $("#see_more").toggleClass('questions_hover');
  });

  $('#dkv_text #close_text').live('hover', function() {
    $("#dkv_text").toggleClass('close_hover');
  });
  
  $(window).bind( 'hashchange', function(e) {
    var service = $.param.fragment();
    if(service != ""){
      var servurl = "http://pbs.es/" + locale + "/#" + service;
      if (link != undefined) {
        var link = servurl;
      } else {
        link = servurl  ;
      }
      startService("service_"+service);      
    }
  });
  
  $('#languages a').click(function(){
    if($service!=null){
      window.location.href = $(this).attr('href')+'#'+$service.attr('id').replace("service_","");
      return false;
    }
  });
  
  $(window).trigger( 'hashchange' );

  $("#mailer .bottom .submit").click(function() {
    if ($("#mailer .bottom #accept").is(':checked')) {

    } else {
      $("#mailer .bottom span label").addClass('warn');
      return false;
    }
  });

  /*if ($('body.home').text() != '' && (locale =='es' || locale =='en')) {
    $(" #banners").load("/banners?locale=" + locale);
    //banner_nis snipped instead of banner extension
  }*/

  $('#download_pdf').live('click',function(){
    _gaq.push(['_trackEvent', locale, 'Download PDF', service_name]);
  });

  $('a.contact_link').live('click',function(){
    _gaq.push(['_trackEvent', locale, 'info@pbs.es', 'Contact']);
  });

});


