
Cufon.replace('#campaign-tabs .campaign-tab-titles A', { fontFamily: 'Wendy LP Std', fontSize: '30px' });

var CAMPAIGN_ANIMATION_STOP_ON_SCROLL = true;
var CAMPAIGN_ANIMATION_TRANSITION_MSECS = 750;
var CAMPAIGN_ANIMATION_DELAY_MSECS = 4000;


$(function() {

  if ($.browser.msie && $.browser.version < 7) {
    $(':first-child').addClass('first-child');
    $(':last-child').addClass('last-child');
  }
  
  $('#campaign-tabs .campaign-tab-titles A').click(function(e) {
    e.preventDefault();
    var li = $(this.parentNode);
    li.addClass('active').siblings().removeClass('active');
    Cufon.refresh('#campaign-tabs .campaign-tab-titles A');
    var index = li.prevAll().length;
    var tab = $('#campaign-tabs .campaign-tab-contents > .tab-content').eq(index);
    tab.show().siblings().hide();
    if (tab.hasClass('unloaded')) {
      var url = window.location.href;
      var params = url.indexOf('?') > -1 ? url.substr(url.indexOf('?')) : '';
      tab.load($(this).attr('href') + params, function() {
        tab.removeClass('unloaded');
        $('FORM.ajax', tab).submit(send_ajax_form);
      });
    }
  }).eq(0).click();
  
  $('#campaign-tabs .campaign-subtab-titles LI').live('click', function(e) {
    $(this).addClass('active').siblings().removeClass('active');
    var index = $(this).prevAll().length;
    var tab = $('#campaign-tabs .campaign-subtab-contents .subtab-content').eq(index);
    tab.show().siblings().hide();
  });

  /*  
  $('A[href$="/svenska"]').each(function() {
    $(this).css('color', '#ccc').css('cursor', 'default');
  }).click(function(e) {
    e.preventDefault();
    alert('Svenska sidor öppnas snart.');
  });*/

  $('.tab-header A').click(function(e) {
    $(this).parent().addClass('selected')
      .siblings().removeClass('selected');
    $($(this).attr('href')).addClass('tab-selected')
      .siblings().removeClass('tab-selected');
  }).each(function() {
    var re = new RegExp($(this).attr('href') + '$');
    if (window.location.href.match(re)) {
      $(this).click();
    }
  });
  
  $('.tab-container').each(function() {
    $('.tab .empty', this).each(function() {
      var tab_id = $(this).parents('.tab:first')
        .removeClass('tab-selected')
        .attr('id');
      $('.tab-header A[href$="' + tab_id + '"]').parent().hide();
      var count = $('.tab-header LI:visible').length;
      $('.tab-header LI').width(99 / count + '%');
    });
  });
  
  if ($('.tab-header LI.selected:visible').length == 0) {
    $('.tab-header LI:visible:first A').click();
  }
  
  $('#header .search .submit').click(function() {
    $(this).parents('FORM:first').submit();
  });
  
  // Show the "Buy" splash if the product has "Buy" tab enabled
  if ($('#buy.tab .empty').length == 0) {
    $('#product-info .buy-splash').show();
  }

  $('#product-info A[href$=#buy]').click(function(e) {
    //e.preventDefault();
    $('.tab-header A[href$="#buy"]').click();
  });
      
  $('#product-meta #comments FORM').submit(function() {
    var form = this;
    
    if (! validate_form(form)) return false;
    
    if ($('.disclaimer INPUT:checked', form).length == 0) {
      window.alert($('.disclaimer .hidden').text());
      return false;
    }
    
    var tab = $(form).parents('.tab:first');
    tab.css('minHeight', tab.height());

    $(form).fadeOut('fast', function() {
      $('.sending', tab).fadeIn('fast');
    });

    // Pseudo-ajax submission / file upload using iframe
    $(form).ajaxSubmit({ success: function(response, status) {
      form_success(response, form, 3000);
    }, error: function(xhr, status, error) {
      form_error(form);
    } }).find('[type=submit]').attr('disabled', true);
  
    return false;
  });
  
  $('FORM.ajax').submit(function() {
    var form = this;

    if (! validate_form(form)) return false;

    var container = $(form).parents('.container:first');
    container.css('minHeight', container.height());

    $(form).fadeOut('fast', function() {
      $('.sending', container).fadeIn('fast');
    });

    $.ajax({
      url: $(this).attr('action'),
      data: form_params(form),
      type: 'POST',
      success: function(response, status) {
        form_success(response, form);
      },
      error: function(xhr, status, error) {
        form_error(form);
      }
    });
    return false;
  });

  // Form input "autoclear" functionality
  $('FORM .autoclear').focus(function () {
    if ($(this).hasClass('autoclear-default')) {
      $(this).removeClass('autoclear-default');
      $(this).addClass('autoclear-edited');
      $(this).val('');
    }
  }).blur(function () {
    if ($(this).val() == '') {
      $(this).addClass('autoclear-default');
      $(this).removeClass('autoclear-edited');
      $(this).val($(this).attr('default_value'));
    }
  }).each(function() {
    $(this).attr('default_value', $(this).val()); 
  });
  
  $('FORM.validate').submit(function() {
    return validate_form(this);
  });
  
  // Open external links into new window
  $('A[href^="http://"]').attr('target', '_blank').addClass('external');
  $('A[href^="https://"]').attr('target', '_blank').addClass('external');
  
  $('.googlemap').each(function() {
    var map = new GMap2(this, { mapTypes: [G_HYBRID_MAP] });
    var location =  new GLatLng(
      $(this).class_attr('lat').replace(/\-/, '.'),
      $(this).class_attr('lng').replace(/\-/, '.'));
    map.setUIToDefault();
    //map.addControl(new GSmallZoomControl());
    map.setCenter(location, parseInt($(this).class_attr('zoom')));
    map.addOverlay(new GMarker(location));
  });

  // De-obfuscate emails (contact page)
  $('.people A[href^="mailto:etunimi.sukunimi"]').each(function() {
    var name = $(this).parents('LI:first').find('H2').text();
    if (name!= '') {
      var userpart = name.replace(/ /g, '.').toLowerCase().replace(/[åä]/g, 'a').replace('/ö/g', 'o');
      $(this).attr('href', $(this).attr('href').replace(/etunimi\.sukunimi/, userpart))
        .text($(this).attr('href').substr(7))
        .addClass('replaced');
    }
  });

  $('#popup').each(function() {
    if ($.cookie('ad_seenx') != $(this).attr('id')) {
      popup_open(this);
      init_flowplayer($('.flowplayer', this));
    }
  });

  
  $('#animated-campaigns').each(function() {
    
    var stopped = false;
    var list = $(this);
    var first = list.find('LI.campaign:first-child');
    $('.related-products', first).show();
    init_flowplayer($('.flowplayer', first));

    $('#campaign-links LI').click(function(e) {
      e.preventDefault();
      stopped = true;     
      var campaign = $('#' + $(this).attr('id').replace(/\-link/, ''));
      if (campaign.prevAll().length > 0) {
        campaign.insertAfter($('LI.campaign:first-child', list))
          .removeClass('hidden').next().addClass('hidden');
        animate();
      }
    }).eq(0).addClass('selected');

    $('.related-products', this).each(function() {
      var count = $('.products LI', this).length;
      $('H1 .count', this).text(count);
    });
    
    $('.flowplayer', this).click(function() { stopped = true; });

    var animate = function() {
      $('.related-products', first).fadeOut('fast', function() {
        first.animate({'marginLeft': first.outerWidth() * -1}, CAMPAIGN_ANIMATION_TRANSITION_MSECS, 'swing', function() {
          $(this).addClass('hidden').appendTo(this.parentNode).css('marginLeft', 0)
            .find('.related-products').addClass('hidden');
          first = list.find('LI.campaign:first-child');
          $('.related-products', first).fadeIn('fast');
          $('#campaign-link-' + first.attr('id').substr(9))
            .addClass('selected').siblings().removeClass('selected');
          first.next().removeClass('hidden');
          if ($('.flowplayer object', first).length == 0) {
            init_flowplayer($('.flowplayer', first));
          }
        });
      });
    }
    
    if (list.find('LI.campaign').length < 2) return;
    
    window.setInterval(function() {
      if (! stopped && ! (CAMPAIGN_ANIMATION_STOP_ON_SCROLL && $(window).scrollTop() > 0)) {
        animate();
      }
    }, CAMPAIGN_ANIMATION_DELAY_MSECS);
  });

  $("img.hoverImg").mousemove( 
    function (e) 
    {
      if (!$(".hoverImage").length)
      {
        $(this).after(
          $(document.createElement("img"))
            .attr("src", $(this).attr("rel"))
            .addClass("hoverImage")
            .css({
              "border": "3px solid black",
              "position": "absolute",
              "z-index": 999,
              "top": e.pageY + 10,
              "left": e.pageX + 10
            })
        );
      }
      else
      {
        $(".hoverImage").css({
          "top": e.pageY + 20,
          "left": e.pageX + 20
        });
      }
      // setTimeout( function () { $(".hoverImage").remove() }, 1000 );
    }
  );

  $("img.hoverImg").hover(
    function () {},
    function () 
    {
      $(".hoverImage").remove();
    }
  );
  
  //$('.flowplayer').click(function(e) { e.preventDefault(); init_flowplayer(this); alert('error'); });
});

jQuery.fn.extend({
  class_attr: function(attr) {
    if (this[0]) {
      var m = this[0].className.match(new RegExp(attr + '-([^ ]+)'));
      if (m && m[1]) return m[1];
    }
    return false;
  }
});

function validate_form(form) {
  $('.required:input', form).each(function() {
    var invalid = $(this).val() == ''
      || $(this).hasClass('autoclear-default')
      || ($(this).hasClass('email') && $(this).val().indexOf('@') == -1)
    $(this)[invalid ? 'addClass' : 'removeClass']('invalid');
  });
  if ($('.invalid', form).length > 0) {
    $('.invalid:first', form).focus();
    return false;
  } else {
    $('<input type="hidden" name="ngform_on" value="1" />').appendTo(form);
  }
  return true;
}

function form_success(response, form, delay) {
  delay = delay || 1000;
  var container = $(form).parents('.container:first');
  $(form).find('[type=submit]').attr('disabled', false);
  window.setTimeout(function() {
    var new_item = $(response)
      .hide()
      .addClass('preview')
      .appendTo($('.items', container));
    $('.sending', container).fadeOut('fast', function() {
      new_item[$.browser.msie ? 'show' : 'fadeIn']();
      $('.thanks', container).fadeIn('fast');
    });
  }, delay);  // wait 3 sec for thumbnail generation
}

function form_error(response, form) {
  $(form).find('[type=submit]').attr('disabled', false);
  window.alert('Sending failed. Please try again.');
}

function form_params(form) {
  var params = {};
  $(':input', form).each(function() {
    params[$(this).attr('name')] = $(this).val();
  });
  return params;
}

function send_ajax_form(e) {
  var form = $(e.target);
  var params = {};
  $(':input', form).each(function() {
    if (! ($(this).attr('type').toLowerCase() == 'checkbox' && ! this.checked)) {
      if ($(this).attr('name') != '')
        params[$(this).attr('name')] = $(this).val();
    }
  });
  $.post(form.attr('action'), params, function(text, status, xhr) {
    if (text.indexOf('FORM ERROR') == -1) {
      form.parent()
        .height(form.parent().height())
        .html(text);
    } else {
      window.alert(text.split("\n")[1]);
    }
  });
  return false;
}

function popup_open(elem) {
  var shadow = $('<div id="popup-shadow"></div>').css('height', $('body').height()).appendTo('body').show();
  var popup = $(elem);
  popup.css('left', ($(window).width() - popup.outerWidth()) / 2);
  popup.css('top', ($(window).height() - $(window).scrollTop() - popup.outerHeight()) / 2);
  $('.close', popup).click(function() {
    popup.hide();
    shadow.remove();
    popup_seen($(elem).attr('href'));
  });
  $(window).keyup(function(e) {
    if (e.keyCode == 27) $('.close', popup).click();
  });
  popup.show();
}

function popup_seen(video_id) {
  $.cookie('ad_seen', video_id, { expires: 180, path: '/' });
}

// Load flowplayer
function init_flowplayer(container) {
  //if ($('object', container).length > 0) return false;
  var conf = {
        key : '003ea14a4a5dcf95ee3',
        logo: { opacity: 0 },
        clip : {
            scaling : 'fit',
            autoBuffering : true,
            autoPlay : $(container).hasClass('autoplay')
        },
        play: { replayLabel : '' },
        canvas: {
          backgroundGradient : 'low'
        },
        plugins: {
          audio: { url : "/cm-static/flowplayer/flowplayer.audio-3.0.4.swf" },
          controls: {
            autoHide: 'never',
            fullscreen : false,
            stop : false,
            play : true,
            scrubber : true,
            volume : true,
            mute : true,
            playlist : true,
  
            backgroundGradient : 'low'
          },
          logo: null
        },
        onLoad: function() {
          this.setVolume(50);
        },
        onFinish: function() {
          if ($(container).parent().attr('id') == 'popup') {
            var popup = $('#popup');
            var margin_top = (parseInt(popup.css('top')) + popup.outerHeight() + 100) * -1;
            popup.animate({ marginTop: margin_top }, 500, null, function() {
              popup_seen($(container).attr('href'));
              $(this).hide();
              $('#popup-shadow').fadeOut(500, function() { $(this).remove() });
            });
          }
        }
    }

  return flowplayer($(container).attr('id'), {
      'src' : '/cm-static/flowplayer/flowplayer.crasman-3.0.7.swf',
      'width' : $(container).hasClass('custom-size') ? $(container).width() : '320',
      'height' : $(container).hasClass('custom-size') ? $(container).height() : '240',
      'wmode' : 'transparent'
  }, conf);
}

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(a,b,c){if(typeof b!='undefined'){c=c||{};if(b===null){b='';c.expires=-1}var d='';if(c.expires&&(typeof c.expires=='number'||c.expires.toUTCString)){var e;if(typeof c.expires=='number'){e=new Date();e.setTime(e.getTime()+(c.expires*24*60*60*1000))}else{e=c.expires}d='; expires='+e.toUTCString()}var f=c.path?'; path='+(c.path):'';var g=c.domain?'; domain='+(c.domain):'';var h=c.secure?'; secure':'';document.cookie=[a,'=',encodeURIComponent(b),d,f,g,h].join('')}else{var j=null;if(document.cookie&&document.cookie!=''){var k=document.cookie.split(';');for(var i=0;i<k.length;i++){var l=jQuery.trim(k[i]);if(l.substring(0,a.length+1)==(a+'=')){j=decodeURIComponent(l.substring(a.length+1));break}}}return j}};
