/***********************************************
 *** safe init for jQuery
 *** use the $ namespace for variables if needed (timeout etc)
 ***********************************************/
$(window).load(function () {


  $('.langNavi > ul > li').hover(function () {

      $(this).children('ul').fadeIn();

   }, function () {

      $(this).children('ul').fadeOut();

   });
  
  /***********************************************
    *** DYNAMIC SWF REPLACEMENT
    ***********************************************/
   $(".flashElement").each(function () {
      var target = $(this);
      var data = target.attr("rel").split(",");
      $(this).flash({
         swf: data[0],
         width: data[1],
         height: data[2],
         flashvars: {
            myXml: data[3]
         },
         hasVersion: 9,
         hasVersionFail: function (options) {
            return false;
         }
      });
   });
  
  
  
   /***********************************************
    *** IE PNG FIX
    ***********************************************/

   if ($.browser.msie && parseInt($.browser.version, 10) == 6) {
      DD_belatedPNG.fix('.logo, .homeImg, .w, .e, .s, .n, .se, .sw, .top01, .top02, .title, .content, .sign-in, .submit, .search, .subnavigation-active ul, .subnavigation, #solutions-main, #solutions-main li, #solutions-main img, #solutions-items li, #solutions-items .separator, #solutions-items .item, #solutions-items img, #solutions-customers img, #solutions-customers .item, #stories-main, #stories-main img, #stories-main .browse, .quotebox, blockquote, #stories-main .close, .option .dot, .option .active, #stories-browser .item, #stories-browser .item img, #stories-browser .active, #stories-browser .first, #notfound-main, #notfound-main img, #notfound-search form, #search-search form, .pagination a, #search-results .item, #notfound-results .item, .column02, .share img, #fancybox-close, #events .frame, .column02 .button');
   }

   /***********************************************
    *** CUFON
    ***********************************************/

   Cufon.replace('h1, h2, h3, h4, #lift .item, #numbers .item span, a.h2', {
      hover: true
   });
   Cufon.replace('#navigation span', {
      hover: true
   });
  
  Cufon.replace('#footer .column01 h2,#footer .column02 h2, #now .browse a,  #stories-main .browse a', {fontFamily:"neosansblack",
      hover: true
   });
  
   /***********************************************
    *** utc time to relate something = UTC, 11 is about 14 in finland
    ***********************************************/
   var offset = new Date().clearTime();

   var dayobjects = {};
   dayobjects["monday"] = Date.today().next().monday().add(2).week()
   dayobjects["wednesday"] = Date.today().next().wednesday().add(2).week()
   dayobjects["thursday"] = Date.today().next().thursday().add(2).week()

   offset.setUTCHours(7);
   dayobjects["monday"].addHours(offset.getHours());

   offset.setUTCHours(11);
   dayobjects["wednesday"].addHours(offset.getHours());

   offset.setUTCHours(10);
   dayobjects["thursday"].addHours(offset.getHours());

   // add dates for online reqi
   $("#onlinePresentation label").each(function () {
      var target = $(this);
      if (typeof translations[target.html().toLowerCase()] != "undefined") {
         var oldhtml = target.html();
         if (typeof dayobjects[target.html().toLowerCase()] != "undefined") {
            target.html(dayobjects[target.html().toLowerCase()].toString(Date.CultureInfo.formatPatterns.longDate + " " + Date.CultureInfo.formatPatterns.shortTime));
            target.addClass(translations[target.html().toLowerCase()]);
            //add change event    
            $("#" + target.attr("for")).change(function () {
               if (typeof $(this).attr("checked") != "undefined") {
                  if (oldhtml.toLowerCase() != "other") {
                     $(".formCalculatedDate_li input").attr("value", dayobjects[oldhtml.toLowerCase()].toString());
                  } else {
                     $(".formCalculatedDate_li input").attr("value", "manual request. look at 'other' field");
                  }
               }
            })
         } else {
            $("#" + target.attr("for")).change(function () {
               if (typeof $(this).attr("checked") != "undefined") {
                  if (oldhtml.toLowerCase() != "other") {
                     $(".formCalculatedDate_li input").attr("value", dayobjects[oldhtml.toLowerCase()].toString());
                  } else {
                     $(".formCalculatedDate_li input").attr("value", "manual request. look at 'other' field");
                  }
               }
            });
         }
      }
   });
   /***********************************************
    *** JS TRANSLATION LOOP if needed
    ***********************************************/
   $(".iFrameForm label").each(function () {
    
      var target = $(this);
      if (typeof translations[target.html().toLowerCase()] != "undefined") {
         target.html(translations[target.html().toLowerCase()]);
         target.addClass(translations[target.html().toLowerCase()]);
      }
   })
  
   $(".iFrameForm option").each(function () {
    var target = $(this);
    if (typeof translations[target.html().toLowerCase()] != "undefined") {
         target.html(translations[target.html().toLowerCase()]);
         target.addClass(translations[target.html().toLowerCase()]);
      }
   })



   /***********************************************
    *** FAKE THE HTML5 FORMS
    ***********************************************/

   // manages elements that we exclude
   var exclusionlist = {
      cssClass: ["formCountry_li","formInterestedIn_li"],
      type: ["radio", "table"]
   };

   function excludeItem(target) {
    
      exclude = false;
      if (typeof exclusionlist.cssClass != 'undefined') {
         $.each(exclusionlist.cssClass, function (index, value) {
        
            //test does the target has it
            if (target.hasClass(value)) {
               exclude = true;
            }
            // test is there a parent that has it
            if (target.parents("." + value).length) {
               exclude = true;

            }
            // test is there a child that has it
            if (target.find("." + value).length) {
               exclude = true;

            }
         });
      }


      //exit if we had something allready
      if (exclude) {
         return true;
      }


      // test for labels target type or tagname
      if (typeof exclusionlist.type != 'undefined') {
         var targetInput = $("#" + target.attr("for"));
         var domEl = targetInput.get(0);

         if (typeof domEl != "undefined") {
            if ($.inArray(domEl.tagName.toLowerCase(), exclusionlist.type) > -1) {
               exclude = true;

            }
         }

         if ($.inArray(targetInput.attr("type"), exclusionlist.type) > -1) {

            exclude = true;
         }

      }


      //exit if we had something allready
      if (exclude) {
         return true;
      } else {
         return false;
      }
   }

   function html5labels() {
      var target = $(this);
      if (excludeItem(target)) {

      } else {
         target.parent().find("input").attr("placeholder", $(this).text());
         target.parent().find("textarea").attr("placeholder", $(this).text());
         target.remove();
      }
   }

   function fakedHtml5labels() {
      var target = $(this);

      if (excludeItem(target)) {
         return;
      }

      var hoverable = target.parent();
      var input = target.next();



      target.addClass("fakeplaceholder");
    
    input.focus(function(){
      target.css("display", "none");
    });
    
    input.blur(function(){
      if (input.val() == "") {
           target.css("display", "block");
      } else {
        target.css("display", "none");
      }
    });
    
      //check did we have a value in the input
      if (input.val() == "") {
         target.css("display", "block");
      } else {
         target.css("display", "none");
      }

      //add the hover script to the input first
      hoverable.hover(

      function () {
         target.css("display", "none");
      }, function () {

         if (input.val() == "") {
            target.css("display", "block");
         } else {
            target.css("display", "none");
         }
      })
      //add the hover also to the label
      target.hover(

      function () {
         target.css("display", "none");
      })

   }

   if (typeof window.Modernizr != 'undefined') {

      if (Modernizr.input.placeholder) {
         $(".iFrameForm label").each(html5labels);
      } else {
         $(".iFrameForm label").each(fakedHtml5labels);
      }
   }

   /***********************************************
    *** VALIDATION SUMMARY SCRIPTS
    ***********************************************/
   $(".vsummary").click(function () {
      $(".vsummary").hide();
   });

  


  
  /******************
  career person click
  ***************/
    $('#careers-person .item:first').show();    
   $("#careers-people .item").bind("click", function (event) {
      var id = $(this).attr('id');
      //remove current active
      $("#careers-people .item div.active").removeClass('active');
      //add active to this
      $(this).find("div").addClass('active');
      //load content
    $('#careers-person .item').hide();    
    $('#careers-person .' + id).show();    
      //id = id.replace('person_', '');
      //$('#careers-person').load('/' + id + '.aspx');
   });


   /***********************************************
    *** NICE FORMS
    ***********************************************/
   if (typeof $.fn.jqTransform != 'undefined') {
      $('#contactform form').jqTransform();
      $('.iFrameForm').jqTransform();
   }

   if ($.browser.msie && (parseInt($.browser.version, 10) == 6 || parseInt($.browser.version, 10) == 7 || parseInt($.browser.version, 10) == 8)) {} else {

      $('#participate .simpleimage .middleColumn').append('<div class="fake">&nbsp;</div>');
      $('#participate .simpleimage > .middleColumn > .simpleimage > input').change(function () {
         $('.fake').html($(this).val());
      });

   }

   /***********************************************
    *** BANNERS
    ***********************************************/

   carousel('lift');
   carousel('testimonial');

   /***********************************************
    *** NEWS & POSITIONS CAROUSEL
    ***********************************************/

   $('#news-events .item:first').css({
      top: '0px'
   });
   if ($('#news-events .item').length > 1) setTimeout('scrollingCarousel("news-events")', 5000);
   $('#positions-carousel .item:first').css({
      top: '0px'
   });
   if ($('#positions-carousel .item').length > 1) setTimeout('scrollingCarousel("positions-carousel")', 5000);

   /***********************************************
    *** COMPANY
    ***********************************************/

   $('#company-history .item:first').css({
      'left': 0
   }).addClass('show');

   var pos = 0;

   $('#company-history .arrow-left').click(function () {

      if (pos == 1) $(this).css({
         'visibility': 'hidden'
      });
      $('#company-history .arrow-right').css({
         'visibility': 'visible'
      });
      companyHistoryRotateBack();
      pos--;

   }).css({
      'visibility': 'hidden'
   });

   $('#company-history .arrow-right').click(function () {

      if (pos == ($('#company-history .item').length - 2)) $(this).css({
         'visibility': 'hidden'
      });
      $('#company-history .arrow-left').css({
         'visibility': 'visible'
      });
      companyHistoryRotate();
      pos++;

   });

   var i = 1;
   var rowFirst = 1;
   var length = $('#company-partners .item').length - 4;

   $('#company-partners .item').each(function () {

      $(this).attr('pos', i);

      if (i == 1) {

         $(this).css({
            'width': '144px'
         });
         rowFirst = rowFirst + 5;

      } else if (!(i % 5)) $(this).css({
         'width': '150px',
         'left': '-4px'
      });
      else if (i == rowFirst) {

         $(this).css({
            'width': '144px'
         });
         rowFirst = rowFirst + 5;
      }

      if (i < 6) $(this).css({
         'height': '108px'
      });

      if (i == length) {

         $(this).css({
            'height': '114px'
         });
         length++;

      }

      i++;

   });

   $('#company-videos .video:first').show();

   $('#company-videos .video').hover(function () {

      $(this).children('a').fadeIn();

   }, function () {

      $(this).children('a').fadeOut();

   });

   $('#company-videos .video').each(function () {

      $(this).children('img:first').show();
      $('#company-videos .navi').append('<a href="javascript:;">' + $(this).attr('title') + '</a>');

   });

   $('#company-videos .navi a:first').addClass('active');

   $('#company-videos .navi').append('<div class="clear">&nbsp;</div>');

   $('#company-videos .navi a').click(function (event) {
    event.preventDefault();
    
    
    
    
    
      $('#company-videos .navi a').removeClass('active');
      $(this).addClass('active');

      var title = $(this).html();

      $('#company-videos .video').fadeOut();

      $('#company-videos .video').each(function () {

         if ($(this).attr('title') == title) $(this).fadeIn();

      });

   });

   $('#company-videos .video a').click(function (event) {
    
    event.preventDefault();
    
    if (typeof pageTracker != 'undefined') {
      pageTracker._trackEvent('Videos', 'Play', 'url: ' + $(this).attr('href'));
    }
    
      $.fancybox({
         'padding': 0,
         'autoScale': false,
         'transitionIn': 'none',
         'transitionOut': 'none',
         'title': this.title,
         'width': 680,
         'height': 495,
         'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
         'type': 'swf',
         'swf': {
            'wmode': 'transparent',
            'allowfullscreen': 'true'
         }
      });

   });


   /***********************************************
    *** SOLUTIONS BIG PICTURE
    ***********************************************/
  if($(".big-picture").length !== 0){
    $('.big-picture').append('<div class="imagecontent"></div>');
    
    var currentPage = "";
    var attr = $('#solutions-cashflow').attr('class');
    
    // need to hilite the right element
    if (typeof attr !== 'undefined' && attr !== false) {
      currentPage = attr.replace("/solutions/","");
    }  
    
    currentPage = currentPage.replace("/","");
    
    $('.big-picture .bigBigtureItem').children('img').each(
      function () {
        
        if($(this).attr('title') == currentPage) {
          var url = $(this).attr('src').replace('.png', '-hover.png');
          $('.big-picture .imagecontent').html('<img src="' + url + '" alt="" />');
        }    
      }
    );
    
    $('.big-picture .links span').mouseenter(function () {
  
      var title = $(this).attr('class');
  
      $('.big-picture .' + title).children('img').each(function () {
  
        $(this).attr('src', $(this).attr('src').replace('.png', '-hover.png'));
  
      });
      
      $('.big-picture div.' + title).show();
  
    });
  
    $('.big-picture .links span').mouseleave(function () {
  
      var title = $(this).attr('class');
  
      $('.big-picture .' + title).children('img').each(function () {
  
        $(this).attr('src', $(this).attr('src').replace('-hover.png', '.png'));
  
      });
  
      $('.big-picture div.' + title).hide();
  
    });
  
    $('.big-picture a').mouseenter(function () {
      
      $(this).hide();
  
      $('.big-picture .infobox').fadeOut();
      
  
      $('.big-picture .imagecontent').html('');
  
      var application = $(this);
      var pic = $(this).attr('class');
  
      var i = 0;
  
      $('.big-picture img').each(function () {
  
        if ($(this).attr('title') == pic) $('.big-picture .imagecontent').html('<img src="' + $(this).attr('src').replace('.png', '-hover.png') + '" alt="" />');
  
      });
      
      var i = 0;
  
      $(this).parent('div').siblings('.infobox').each(function () {
  
        if ($(this).hasClass(pic)) {
  
          var top = parseInt(application.css('top').replace('px', '')) + 10;
          var left = parseInt(application.css('left').replace('px', ''));
  
          var title = $(this).children('.title');
  
          if (title.width() < 220) title.width(220);
  
          var content = title.siblings('.content');
  
          content.width(title.width() - 9);
  
          var content = title.siblings('.content').children('.text').html();
  
          $(this).css({
            'top': top + 'px',
            'left': left + 'px',
            'position': 'absolute',
            'z-index': 980,
            'height': application.height() + 'px',
            'width': (title.width() + 77) + 'px'
          });
  
          $(this).fadeIn(500).mouseleave(function () {
  
            $(this).fadeOut(100, function () {
              $(this).children('.content').hide();
            });
  
          $('.big-picture .imagecontent').html('');
          
          var t = setTimeout(function() { application.show(); },150);
  
  
          });
  
          var ti = setTimeout(function () {
            title.siblings('.content').slideDown(200, function () {
              $(this).children('.text').html(content);
            });
          }, 150);
  
          i++;
  
        }
  
      });
  
      if (i == 0) {
  
        application.mouseleave(function () {
  
        $('.big-picture .imagecontent').html('');
        
        i = 0;
  
        });
  
      }
  
    });
  }
   /***********************************************
    *** SOLUTIONS ITEMS
    ***********************************************/

   var i = 0;

   $('#solutions-items li').each(function () {

      if (i == 0) $(this).addClass('first-active');

      $(this).attr('pos', i);

      i++;

   });

   var i = 0;

   $('#solutions-items .item').each(function () {

      if (i == 0) $(this).show();

      $(this).attr('pos', i);

      i++;

   });

   $('#solutions-items li').click(function () {

      $('#solutions-items li').each(function () {

         if ($(this).hasClass('first')) $(this).removeClass('first-active');
         $(this).removeClass('active');

      });

      if ($(this).hasClass('first')) $(this).addClass('first-active');
      else $(this).addClass('active');

      var pos = $(this).attr('pos');

      $('#solutions-items .item').each(function () {

         $(this).fadeOut(500);
         if ($(this).attr('pos') == pos) $(this).fadeIn(500);

      });

   });

   /***********************************************
    *** SOLUTIONS CUSTOMERS
    ***********************************************/

  if ($("#solutions-customers .item").length !== 0) {
    var itemWidth = $('#solutions-customers .item').width();
    var scounter = 1;
    var solutionItems = $('#solutions-customers .item').length;
    if( solutionItems < 4) {
      
      $('#solutions-customers .item').addClass('big');
      itemWidth = 924;
      $('#solutions-customers .content').css(
        {
          'width': (solutionItems * itemWidth) + 'px', 'height' : '252px'
        });   
      $('#solutions-customers .customers').css({'height':'252px'});
      $('#solutions-customers .customers .text').hide();
      $('#solutions-customers .customers .long').show();
      $('#solutions-customers .arrow-left').css({'margin':'50px 0 0 0'});
      $('#solutions-customers .arrow-right').css({'margin':'50px 0 0 0'});
      
      var spages = solutionItems;
        
    } else {
      $('#solutions-customers .content').css(
        {
          'width': (solutionItems * itemWidth) + 'px'
        });  
      itemWidth = itemWidth * 4;
      var spages = Math.ceil(solutionItems / 4);
  
    }
  
    $('#solutions-customers .arrow-left').click(function () {
      if ($(this).hasClass('stop')) {
      
      } else {
        $('#solutions-customers .arrow-right').css({'visibility': 'visible'});
        
        var pos = parseInt($('#solutions-customers .content').css('left').replace('px', ''));
        scounter -= 1;
        
        if (pos < 0) {
          $('#solutions-customers .content').animate({'left': (pos + itemWidth) + 'px'}, 500);
        } 
        if(scounter == 1){
          $(this).css({'visibility': 'hidden'});
        }
  
      }  
    
      $(this).addClass('stop');
      
      var t = setTimeout(function () {$('#solutions-customers .arrow-left').removeClass('stop');}, 600);
      
    }).css({'visibility': 'hidden'}); // left click end
      
    $('#solutions-customers .arrow-right').click(function () {
      
      if ($(this).hasClass('stop')) {
        
      } else {
      
      $('#solutions-customers .arrow-left').css({
      'visibility': 'visible'
      });
      
      var pos = parseInt($('#solutions-customers .content').css('left').replace('px', ''));
      scounter += 1;
      if (scounter <= spages) {  
        $('#solutions-customers .content').animate(
          {'left': (pos - itemWidth) + 'px'}
          , 500);    
        }
        if(scounter >= spages) {
          $(this).css(
            {'visibility': 'hidden'}
          );
        }
      }
      
      $(this).addClass('stop');
      
      var t = setTimeout(function () {$('#solutions-customers .arrow-right').removeClass('stop');}, 600);  
    });
    
    if (solutionItems <= 4){
      $('#solutions-customers .arrow-right').hide();
    }
    
    $('#solutions-customers b').each(function () {
        $(this).parent('div').height($(this).height());
      });
  
    if(solutionItems > 3) {
      $('#solutions-customers .item').hover(function () {
            $(this).children('.text').animate({'height': ($(this).children('.text').children('b').height() + $(this).children('.text').children('p').height() + 5) + 'px' }, 250);
          }, function () {
            $(this).children('.text').animate({'height': ($(this).children('.text').children('b').height()) + 'px'}, 250);
        });
  
    }
  }
   /***********************************************
    *** SOLUTIONS VIDEOS
    ***********************************************/

   $('#solutions-videos .video:first').show();

   $('#solutions-videos .video').hover(function () {

      $(this).children('a').fadeIn();

   }, function () {

      $(this).children('a').fadeOut();

   });

   $('#solutions-videos .video').each(function () {

      $('#solutions-videos .navi').append('<a href="javascript:;">' + $(this).attr('title') + '</a>');

   });

   $('#solutions-videos .navi a:first').addClass('active');

   $('#solutions-videos .navi').append('<div class="clear">&nbsp;</div>');

   $('#solutions-videos .navi a').click(function (event) {
    event.preventDefault();
    
      $('#solutions-videos .navi a').removeClass('active');
      $(this).addClass('active');

      var title = $(this).html();

      $('#solutions-videos .video').fadeOut();

      $('#solutions-videos .video').each(function () {

         if ($(this).attr('title') == title) $(this).fadeIn();

      });

   });

   $('#solutions-videos .video a').click(function (event) {
    event.preventDefault();
    
    if (typeof pageTracker != 'undefined') {
      pageTracker._trackEvent('Videos', 'Play', 'url: ' + $(this).attr('href'));
    }
    
      if ($(this).hasClass('vidType-66')) {

         $.fancybox({
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'title': this.title,
            'width': 680,
            'height': 495,
            'href': this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
            'type': 'swf',
            'swf': {
               'wmode': 'transparent',
               'allowfullscreen': 'true'
            }
         });
      } else {

         $.fancybox({
            'padding': 0,
            'autoScale': false,
            'transitionIn': 'none',
            'transitionOut': 'none',
            'title': this.title,
            'width': 400,
            'height': 265,
            'href': this.href.replace(new RegExp("([0-9])", "i"), 'moogaloop.swf?clip_id=$1'),
            'type': 'swf'
         });

      }

   });

   /***********************************************
    *** SUCCESS STORIES
    ***********************************************/

   $('#stories-main .close').click(function () {

      $('#stories-main').parent('div').slideUp(500);

   });

   $('#stories-options .option').click(function () {

      $('#stories-options .option').children('.dot').removeClass('active');
      $(this).children('.dot').addClass('active');

   });

   $('#stories-browser b').each(function () {

      $(this).parent('a').parent('div').height($(this).height());

   });

   $('#stories-browser .item').hover(function () {

      $(this).children('.text').animate({
         'height': ($(this).children('.text').children('a').children('b').height() + $(this).children('.text').children('p').height() + 5) + 'px'
      }, 250);

   }, function () {

      $(this).children('.text').animate({
         'height': ($(this).children('.text').children('a').children('b').height()) + 'px'
      }, 250);

   });

   var items = Math.ceil($('#stories-browser .item').length / 12);

   if (items > 1) {

      for (var i = 1; i <= items; i++) {

         if (i == 1) $('#stories-browser .pagination').append('<span class="page first"><a href="javascript:;" class="active">' + i + '</a></span>');
         else $('#stories-browser .pagination').append('<span class="page"><a href="javascript:;">' + i + '</a></span>');

      }

   }

   $('#stories-browser .pagination a').click(function () {

      $('#stories-browser .pagination a').removeClass('active');
      $(this).addClass('active');

      var browser = $('#stories-browser .content');

      var newPos = parseInt('-' + (((parseInt($(this).html()) - 1) * 3) * browser.children('div').height()));

      browser.fadeOut(500, function () {
         $(this).css({
            'top': newPos + 'px'
         });
      }).fadeIn(500);

   });

   /***********************************************
    *** SOLUTIONS VIDEOS
    ***********************************************/

   $('#solutions-videos .navi a').click(function (event) {
    event.preventDefault();
    
    if (typeof pageTracker != 'undefined') {
      pageTracker._trackEvent('Videos', 'Play', 'url: ' + $(this).attr('href'));
    }
    
      var src = $(this).attr('href');
    
    if (swfobject.hasFlashPlayerVersion("9.0.0")) {

         flowplayer('videoPlayer', 'http://releases.flowplayer.org/swf/flowplayer-3.2.7.swf', {
            clip: {
               url: src,
               autoPlay: true,
               scaling: 'orig'
            }
         });

      } else {

         $('#noflash').show();

      }
    
   });

   /***********************************************
    *** NOW
    ***********************************************/


   $('.evenheights').each(function () {

      var height = 0;

      $(this).children('.evenheight').each(function () {

         if (height < $(this).height()) height = $(this).height();

      });

      $(this).children('.evenheight').height(height);

   });

   var i = 0;


   $('#now-articles .option-menu .option').click(function () {

      if ($(this).children('.dot').hasClass('active')) {

         $(this).children('.dot').removeClass('active');
         $('#now-articles .option-menu-list').slideUp(500).removeClass('active');

      } else {

         $(this).children('.dot').addClass('active');
         $('#now-articles .option-menu-list').slideDown(500).addClass('active');

      }

   });

   $('#now .newsletter-month b').click(function () {

      if ($(this).parent('div').hasClass('active')) {

         $(this).parent('div').removeClass('active');
         $(this).siblings('div').slideUp();

      } else {

         $(this).parent('div').addClass('active');
         $(this).siblings('div').slideDown();

      }

   });

   var width = 0;
  var journalItems =  $('#now-journals-browser .item').length;
  
  if ($('#now-journals-browser .item').length !== 0) {
    width = (246*journalItems);
  
    // hide arrows 
    if ($('#now-journals-browser .item').length < 5){
      $('#now-journals-browser .arrow-right').css("visibility", "hidden");
    }
    $('#now-journals-browser .arrow-left').css("visibility", "hidden");
    
  
    $('#now-journals-browser .content').width(width);
  
    var counter = 4;
  
    $('#now-journals-browser .arrow-right').click(function () {
  
      if ($(this).hasClass('stop')) {} else {
  
        if (counter < $('#now-journals-browser .item').length) {
  
          $('#now-journals-browser .content').animate({
            'left': parseInt($('#now-journals-browser .content').css('left').replace('px', '')) - 246 + 'px'
          }, 500);
          counter += 1;
          
        }
        
        if(counter >= journalItems){
          $('#now-journals-browser .arrow-right').css("visibility", "hidden");
        }
        
        if(counter > 4){
          $('#now-journals-browser .arrow-left').css("visibility", "visible");
        }
      }
  
      $(this).addClass('stop');
  
      var t = setTimeout(function () {
        $('#now-journals-browser .arrow-right').removeClass('stop');
      }, 600);
  
    });
  
    $('#now-journals-browser .arrow-left').click(function () {
  
      if ($(this).hasClass('stop')) {} else {
  
        if (counter > 4) {
  
          $('#now-journals-browser .content').animate({
            'left': parseInt($('#now-journals-browser .content').css('left').replace('px', '')) + 246 + 'px'
          }, 500);
          counter -= 1;
  
        }
        
        
        if(counter >= 3){
          $('#now-journals-browser .arrow-right').css("visibility", "visible");
        }
        
        if(counter <= 4){
          $('#now-journals-browser .arrow-left').css("visibility", "hidden");
        }
  
      }
  
      $(this).addClass('stop');
  
      var t = setTimeout(function () {
        $('#now-journals-browser .arrow-left').removeClass('stop');
      }, 600);
  
    });
   }
  var itemsPerPage = 5;
   var pages = Math.ceil($('#now .column02 .event').length / itemsPerPage) + 1;

   if (pages > 2) {

      var pos = 1;

      $('#now .column02 .event').hide();
    
    // activate the right page
    var activeItem = $('#now .column02 .event .active').parents(".event");
    var activePage = Math.ceil(activeItem.parent().children().index(activeItem) / itemsPerPage);
   for (i = ((activePage * itemsPerPage) - itemsPerPage); i <= ((activePage * itemsPerPage) - 1); i++) {

            $('#now .column02 .event').eq(i).show();

         }

      for (var i = 1; i < pages; i++) {

         if (i == activePage) $('#now .column02 .event').siblings('.pagination').append('<span class="page first"><a href="javascript:;" class="active">' + i + '</a></span>');
         else $('#now .column02 .event').siblings('.pagination').append('<span class="page"><a href="javascript:;">' + i + '</a></span>');

      }

      $('#now .column02 .pagination span a').click(function () {

         $('#now .column02 .pagination span a').removeClass('active');
         $(this).addClass('active');

         var pos = parseInt($(this).html());

         $('#now .column02 .event').hide();

         for (i = ((pos * itemsPerPage) - itemsPerPage); i <= ((pos * itemsPerPage) - 1); i++) {

            $('#now .column02 .event').eq(i).show();

         }

      });

   }

   var newsletter = $('#now .column02 .newsletter-month');
  var itemsPerPage = 5;
   var pages = Math.ceil(newsletter.length / itemsPerPage) + 1;

   if (pages > 2) {

      var pos = 1;
      newsletter.hide();
    
    // activate the right page
    var activeItem = $('#now .column02 .newsletter-month.active');
    var activePage = Math.ceil(activeItem.parent().children().index(activeItem) / itemsPerPage);
    

      for (i = ((activePage * itemsPerPage) - itemsPerPage); i <= ((activePage * itemsPerPage) - 1); i++) {

            newsletter.eq(i).show();

         }

      for (var i = 1; i < pages; i++) {

         if (i == activePage) newsletter.siblings('.pagination').append('<span class="page first"><a href="javascript:;" class="active">' + i + '</a></span>');
         else newsletter.siblings('.pagination').append('<span class="page"><a href="javascript:;">' + i + '</a></span>');

      }

      $('#now .column02 .pagination span a').click(function () {

         $('#now .column02 .pagination span a').removeClass('active');
         $(this).addClass('active');

         var pos = parseInt($(this).html());

         newsletter.hide();

         for (i = ((pos * itemsPerPage) - itemsPerPage); i <= ((pos * itemsPerPage) - 1); i++) {

            newsletter.eq(i).show();

         }

      });

   }

   var results = $('#notfound-results .item');

   var pages = Math.ceil(results.length / 6) + 1;

   if (pages > 2) {

      var pos = 1;

      results.hide();

      for (var i = 0; i < 6; i++) {

         results.eq(i).show();

      }

      for (var i = 1; i < pages; i++) {

         if (i == 1) results.siblings('.pagination').append('<span class="page first"><a href="javascript:;" class="active">' + i + '</a></span>');
         else results.siblings('.pagination').append('<span class="page"><a href="javascript:;">' + i + '</a></span>');

      }

      $('#notfound-results .pagination span a').click(function () {

         $('#notfound-results .pagination span a').removeClass('active');
         $(this).addClass('active');

         var pos = parseInt($(this).html());

         results.hide();

         for (i = ((pos * 6) - 6); i <= ((pos * 6) - 1); i++) {

            results.eq(i).show();

         }

      });

   }
  
  // ARTICLES PAGINATION
  
  var nowArticlesItems = $('#now-articles .column02 .item');
  var itemsPerPage = 5;
   var pages = Math.ceil(nowArticlesItems.length / itemsPerPage) + 1;
  
  if (pages > 2) {

      var pos = 1;
    nowArticlesItems.hide();
    
    // activate the right page
    var activeItem = $('#now-articles .column02 .item .active').parents(".item");
    var activePage = Math.ceil(activeItem.parent().children().index(activeItem) / itemsPerPage);
    
    for (i = ((activePage * itemsPerPage) - itemsPerPage); i <= ((activePage * itemsPerPage) - 1); i++) {
       nowArticlesItems.eq(i).show();
    }

      for (var i = 1; i < pages; i++) {
      if (i == activePage){
        nowArticlesItems.siblings('.pagination').append('<span class="page first"><a href="javascript:;" class="active">' + i + '</a></span>');
      }else{
        nowArticlesItems.siblings('.pagination').append('<span class="page"><a href="javascript:;">' + i + '</a></span>');
      }
      }

      $('#now-articles .column02 .pagination span a').click(function () {

         $('#now-articles .column02 .pagination span a').removeClass('active');
         $(this).addClass('active');

         var pos = parseInt($(this).html());

         nowArticlesItems.hide();

         for (i = ((pos * itemsPerPage) - itemsPerPage); i <= ((pos * itemsPerPage) - 1); i++) {
            nowArticlesItems.eq(i).show();
         }

      });
    
    
    

   }
  


   /***********************************************
    *** EVENTS
    ***********************************************/

   if ($('#events').hasClass('active')) {

      if (typeof $.fn.fancybox != 'undefined') {

         $('.fullsizeMap').fancybox({
            'overlayOpacity': 0.7,
            'overlayColor': '#000',
            'padding': 0
         });

      }

      geocoder = new google.maps.Geocoder();

      init('Helsinki');

   }
   /***********************************************
    *** SHARRE http://www.linkedin.com/shareArticle?mini=true&url={articleUrl}&title={articleTitle}&summary={articleSummary}&source={articleSource}
    ***********************************************/
   
   
   
   $(".linkedInBtn").click(function(event){
     event.preventDefault();
     window.open("http://www.linkedin.com/shareArticle?mini=true&url="+encodeURIComponent( document.location.href) + "&source="+encodeURIComponent("OpusCapita"));
    
   });
   
   $(".twitter-share-button").click(function(event){
     event.preventDefault();
     window.open("http://twitter.com/share?url="+encodeURIComponent( document.location.href));
   });
   
    $(".printBtn").click(function(event){
     event.preventDefault();
      window.print() ;
   });
  
   /***********************************************
    *** NEWSLETTERFORM NEEEDS TO BE AFTER JQTRANSFORM!!!!
    ***********************************************/ 
  
  $("#pf_redir").attr("value", "http://" + window.location.hostname + "/thank-you/");
  var realButton = $('<input id="real" type="submit" name="Submit" style="display:none;" value="Real"/>');
  $("#newsletterform").append(realButton);
  
  $("#fakedform").submit(function(){
      $("#real").click();
      return false;
  });
  
   /***********************************************
    *** CONTACT
    ***********************************************/

   if (typeof $.fn.fancybox != 'undefined') {
    var popUrls = {};
    popUrls["#contactform"]  =  '/contact-us/';    
      popUrls["#onlinePresentation"]  =  '/online-presentation/';
      popUrls["#feasibilityForm"]  =  '/feasibility-study/';    
      popUrls["#newsletterForm"]  =  '/join-newsletter/';
      popUrls["#partnerForm"]  =  '/partner-network/';
      popUrls["#magasineForm"]  =  '/customer-magasine/'; 
    
    $("#events-columns h4 a").fancybox({
      'overlayOpacity': 0.7,
    'overlayColor': '#000',
    'padding': 0,
    'height': 680,
    'width': 630,
    'type': 'iframe',
    'titleShow': false,
    'centerOnScroll': true
    });
    
    //find all buttons that want to open an frame
    $(".openPopupForm").each(function(){
      var targetButton = $(this);
      //needed to fix the issue with fancybox
      
      
      
      var contactformurl = $(targetButton);
      
      var test = function(){
      }  
      
      targetButton.fancybox({
        'overlayOpacity': 0.7,
        'overlayColor': '#000',
        'padding': 0,
        'onStart': function () {
          if (typeof pageTracker != 'undefined') {
            pageTracker._trackEvent("popup", "open", contactformurl.attr("href"));
          }
          //alert("opening form" + contactformurl.attr("href"));
          $(contactformurl.attr("href")).find("iframe").attr("src", "http://" + window.location.hostname + popUrls[contactformurl.attr("href")]);
        }
      });    
      
      
        
    }).click(function(event) {
      event.preventDefault();
      $('.map-offices .item').hide();
      
    });
   }

   $('.map-offices .item').each(function () {

      var title = $(this).children('.title').html();
      var content = $(this).children('.content');

      $('#footer .office b').each(function () {

         if ($(this).html() == title) content.html($(this).siblings('div').html());

      });

   });

   $('.map-offices .dot').mouseover(function () {

      var location = $(this).html();

      $(this).siblings('.item').each(function () {

         if ($(this).hasClass(location)) {

            $(this).fadeIn(500).mouseleave(function () {
               $(this).fadeOut(500, function () {
                  $(this).children('.content').hide();
               });
            });

            var title = $(this).children('.title');

            var content = title.siblings('.content').html();

            var t = setTimeout(function () {
               title.siblings('.content').html('').slideDown(500, function () {
                  $(this).html(content);
               });
            }, 300);

         }

      });

   });
  
  
   /***********************************************
    *** HOMEPAGE Banner rotator
    ***********************************************/
  
  $('#bannerList').anythingSlider({
      // Appearance
      theme               : "default", // Theme name
      expand              : false,     // If true, the entire slider will expand to fit the parent element
      resizeContents      : true,      // If true, solitary images/objects in the panel will expand to fit the viewport
      vertical            : false,     // If true, all panels will slide vertically; they slide horizontally otherwise
      showMultiple        : false,     // Set this value to a number and it will show that many slides at once
      easing              : "swing",   // Anything other than "linear" or "swing" requires the easing plugin or jQuery UI
    
      buildArrows         : false,      // If true, builds the forwards and backwards buttons
      buildNavigation     : false,      // If true, builds a list of anchor links to link to each panel
      buildStartStop      : false,      // If true, builds the start/stop button
    
      appendForwardTo     : null,      // Append forward arrow to a HTML element (jQuery Object, selector or HTMLNode), if not null
      appendBackTo        : null,      // Append back arrow to a HTML element (jQuery Object, selector or HTMLNode), if not null
      appendControlsTo    : null,      // Append controls (navigation + start-stop) to a HTML element (jQuery Object, selector or HTMLNode), if not null
      appendNavigationTo  : null,      // Append navigation buttons to a HTML element (jQuery Object, selector or HTMLNode), if not null
      appendStartStopTo   : null,      // Append start-stop button to a HTML element (jQuery Object, selector or HTMLNode), if not null
    
      toggleArrows        : false,     // If true, side navigation arrows will slide out on hovering & hide @ other times
      toggleControls      : false,     // if true, slide in controls (navigation + play/stop button) on hover and slide change, hide @ other times
    
      startText           : "Start",   // Start button text
      stopText            : "Stop",    // Stop button text
      forwardText         : "&raquo;", // Link text used to move the slider forward (hidden by CSS, replaced with arrow image)
      backText            : "&laquo;", // Link text used to move the slider back (hidden by CSS, replace with arrow image)
      tooltipClass        : "tooltip", // Class added to navigation & start/stop button (text copied to title if it is hidden by a negative text indent)
    
      // Function
      enableArrows        : true,      // if false, arrows will be visible, but not clickable.
      enableNavigation    : true,      // if false, navigation links will still be visible, but not clickable.
      enableStartStop     : true,      // if false, the play/stop button will still be visible, but not clickable. Previously "enablePlay"
      enableKeyboard      : true,      // if false, keyboard arrow keys will not work for this slider.
    
      // Navigation
      startPanel          : 1,         // This sets the initial panel
      changeBy            : 1,         // Amount to go forward or back when changing panels.
      hashTags            : true,      // Should links change the hashtag in the URL?
      infiniteSlides      : true,      // if false, the slider will not wrap & not clone any panels
      navigationFormatter : null,      // Details at the top of the file on this use (advanced use)
      navigationSize      : false,     // Set this to the maximum number of visible navigation tabs; false to disable
    
      // Slideshow options
      autoPlay            : true,     // If true, the slideshow will start running; replaces "startStopped" option
      autoPlayLocked      : true,     // If true, user changing slides will not stop the slideshow
      autoPlayDelayed     : false,     // If true, starting a slideshow will delay advancing slides; if false, the slider will immediately advance to the next slide when slideshow starts
      pauseOnHover        : false,      // If true & the slideshow is active, the slideshow will pause on hover
      stopAtEnd           : false,     // If true & the slideshow is active, the slideshow will stop on the last page. This also stops the rewind effect when infiniteSlides is false.
      playRtl             : false,     // If true, the slideshow will move right-to-left
    
      // Times
      delay               : 10000,      // How long between slideshow transitions in AutoPlay mode (in milliseconds)
      resumeDelay         : 15000,     // Resume slideshow after user interaction, only if autoplayLocked is true (in milliseconds).
      animationTime       : 600,       // How long the slideshow transition takes (in milliseconds)
      delayBeforeAnimate  : 0,         // How long to pause slide animation before going to the desired slide (used if you want your "out" FX to show).
    
      // Callbacks
      onBeforeInitialize  : function(e, slider) {}, // Callback before the plugin initializes
      onInitialized       : function(e, slider) {}, // Callback when the plugin finished initializing
      onShowStart         : function(e, slider) {}, // Callback on slideshow start
      onShowStop          : function(e, slider) {}, // Callback after slideshow stops
      onShowPause         : function(e, slider) {}, // Callback when slideshow pauses
      onShowUnpause       : function(e, slider) {}, // Callback when slideshow unpauses - may not trigger properly if user clicks on any controls
      onSlideInit         : function(e, slider) {}, // Callback when slide initiates, before control animation
      onSlideBegin        : function(e, slider) {}, // Callback before slide animates
      onSlideComplete     : function(slider) {},    // Callback when slide completes; this is the only callback without an event "e" variable
    
      // Interactivity
      clickForwardArrow   : "click",         // Event used to activate forward arrow functionality (e.g. add jQuery mobile's "swiperight")
      clickBackArrow      : "click",         // Event used to activate back arrow functionality (e.g. add jQuery mobile's "swipeleft")
      clickControls       : "click focusin", // Events used to activate navigation control functionality
      clickSlideshow      : "click"         // Event used to activate slideshow play/stop button
    
      /* Video
      resumeOnVideoEnd    : true,      // If true & the slideshow is active & a supported video is playing, it will pause the autoplay until the video is complete
      addWmodeToObject    : "opaque",  // If your slider has an embedded object, the script will automatically add a wmode parameter with this setting
      isVideoPlaying      : function(base){ return false; } // return true if video is playing or false if not - used by video extension
      */
    });
    /*
     .anythingSliderFx({
  '.panel' : [ 'fade', 1000, 'easeOutCirc' ] // target the entire panel and fade will take 1000ms
 });*/
 
   
  /***********************************************
    *** pagetracker
    ***********************************************/
   $("a[href$='.pdf']").click(function(){
    var target = $(this);
    
    try{
      pageTracker._trackEvent("pdf", "open", "url: " + target.attr("href"));
    }catch(error){
    
    }
    
  });
  
  $("a[href$='.PDF']").click(function(){
    var target = $(this);
    
    try{
      pageTracker._trackEvent("pdf", "open", "url: " + target.attr("href"));
    }catch(error){
    
    }
    
  });
 
  
  /***********************************************
    *** DYNAMIC SWF REPLACEMENT FOR BANNERS
    ***********************************************/
   $(".bannerFlash").each(function () {
      var target = $(this);
      var data = target.attr("rel").split(",");
      $(this).flash({
         swf: data[0],
         width: data[1],
         height: data[2],
         flashvars: {
            myXml: data[3],
        pauseData:data[4],
        continueData: data[5],
        myLink:data[6]
         },
         hasVersion: 9,
         hasVersionFail: function (options) {
            return false;
         }
      });
   });
  
   
});

function pauseAutoPlay(data){
   $('#bannerList').data('AnythingSlider').startStop(false);
   return false;
}


function continueAutoPlay(data){
   $('#bannerList').data('AnythingSlider').startStop(true);   
   $('#bannerList').data('AnythingSlider').goForward(true);
}

function carousel(target) {

   var targets = $('#' + target + ' .item').length;
   var width = Math.floor($('#' + target + '-bar').width() / targets);

   var i = 0;

   $('#' + target + ' .arrow-left').hover(function () {

      $(this).addClass($(this).attr('class') + '-active');

   }, function () {

      $(this).attr('class', $(this).attr('class').replace('-active', ''));

   }).click(function () {

      initRotatorReverse(target);

   });

   $('#' + target + ' .arrow-right').hover(function () {

      $(this).addClass($(this).attr('class') + '-active');

   }, function () {

      $(this).attr('class', $(this).attr('class').replace('-active', ''));

   }).click(function () {

      initRotator(target, '');

   });

   $('#' + target + ' .item').each(function () {

      if (i == 0) $(this).show();
      $(this).attr('pos', i);
      i++;

   });

   var itemsWidth = 0;

   for (var i = 0; i < targets; i++) {

      if (i % 2) var color = "url('/images/bg_bar-item-transparent.png')";
      else var color = "#adafaf";

      if (i == 0) var active = " active";
      else var active = "";

      var content = '&nbsp;';

      $('#testimonial > .item').each(function () {

         if (parseInt($(this).attr('pos')) == i) content = $(this).attr('title');

      });

      $('#' + target + '-bar').append('<div pos="' + i + '" class="item' + active + '" style="background: ' + color + '; width:' + width + 'px;left:' + itemsWidth + 'px;cursor:pointer;" onClick="javascript:initRotator(\'' + target + '\',\'' + i + '\');">' + content + '</div>');

      itemsWidth += width;

   }

   $('#' + target + '-bar').append('<div class="clear">&nbsp;</div>');

   var diff = $('#' + target + '-bar').width() - itemsWidth;

   if (diff != 0) {

      $('#' + target + '-bar > .item:last').width((diff + width));

   }

}

function initRotator(target, position) {

   var current = ($('#' + target + ' > .item').hasClass('show') ? $('#' + target + ' > .show') : $('#' + target + ' > .item:first'));

   if (position != '') {

      var next = $('#' + target + ' > .item:eq(' + position + ')');

      $('#' + target + '-bar .item').removeClass('active');
      $('#' + target + '-bar .item:eq(' + position + ')').addClass('active');

   } else {

      var next = ((current.next().hasClass('item')) ? ((current.next().hasClass('show')) ? $('#' + target + ' > .item:first') : current.next()) : $('#' + target + ' > .item:first'));

      $('#' + target + '-bar .item').each(function () {

         if ($(this).attr('pos') == next.attr('pos')) $(this).addClass('active');
         else $(this).removeClass('active');

      });

   }

   next.hide().addClass('show').fadeIn(500);

   current.fadeOut(500).removeClass('show');

}

function initRotatorReverse(target) {

   var current = ($('#' + target + ' > .item').hasClass('show') ? $('#' + target + ' > .show') : $('#' + target + ' > .item:first'));

   var prev = ((current.prev().hasClass('item')) ? ((current.prev().hasClass('show')) ? $('#' + target + ' > .item:last') : current.prev()) : $('#' + target + ' > .item:last'));

   $('#' + target + '-bar .item').each(function () {

      if ($(this).attr('pos') == prev.attr('pos')) $(this).addClass('active');
      else $(this).removeClass('active');

   });

   prev.hide().addClass('show').fadeIn(500);

   current.fadeOut(500).removeClass('show');

}

function scrollingCarousel(target, position) {

   var current = ($('#' + target + ' .item').hasClass('show') ? $('#' + target + ' .show') : $('#' + target + ' .item:first'));

   var next = ((current.next().hasClass('item')) ? ((current.next().hasClass('show')) ? $('#' + target + ' .item:first') : current.next()) : $('#' + target + ' .item:first'));
   next.css({
      top: '44px'
   }).addClass('show').animate({
      top: '0'
   }, 500);

   current.animate({
      top: '-44px'
   }, 500,
  null,
  function(e){
    setTimeout('scrollingCarousel("' +target + '")', 5000)
  }).removeClass('show');

}

function companyHistoryRotate() {

   var current = ($('#company-history .item').hasClass('show') ? $('#company-history .show') : $('#company-history .item:first'));

   if (current.next().hasClass('item')) {} else return;

   var next = ((current.next().hasClass('item')) ? ((current.next().hasClass('show')) ? $('#company-history .item:first') : current.next()) : $('#company-history .item:first'));

   next.css({
      left: next.width() + 'px'
   }).addClass('show').animate({
      left: 0
   }, 500);

   current.animate({
      left: '-' + current.width() + 'px'
   }, 500).removeClass('show').css({
      'left': current.width() + 'px'
   });

}

function companyHistoryRotateBack() {

   var current = ($('#company-history .item').hasClass('show') ? $('#company-history .show') : $('#company-history .item:last'));

   if (current.prev().hasClass('item')) {} else return;

   var prev = ((current.prev().hasClass('item')) ? ((current.prev().hasClass('show')) ? $('#company-history .item:last') : current.prev()) : $('#company-history .item:last'));

   prev.css({
      left: '-' + prev.width() + 'px'
   }).addClass('show').animate({
      left: 0
   }, 500);

   current.animate({
      left: current.width() + 'px'
   }, 500).removeClass('show').css({
      'left': current.width() + 'px'
   });

}

function showMap(lat, lng) {
   var latlng = new google.maps.LatLng(lat, lng);
   var options = {
      zoom: 12,
      center: latlng,
      mapTypeId: google.maps.MapTypeId.ROADMAP
   };

   var map = new google.maps.Map(document.getElementById("map"), options);
}

function init(address) {

   geocoder.geocode({
      'address': address
   }, function (results, status) {

      if (status == google.maps.GeocoderStatus.OK) {

         var lat = results[0].geometry.location.lat();
         var lng = results[0].geometry.location.lng();

         showMap(lat, lng);

      }

   });

}

function openFeasibilityStudyForm(){
  $("#flashPopup").trigger('click');
}
