$(document).ready(function()
{
  $('.expandable .title').click(function()
  {
    var n = $(this).attr('id').split('-')[1];

    $('.expandable article').slideUp('fast');
    $('.expandable .title img').each (function()
    {
      $(this).attr('src', '/resources/images/arrow-right.png');
    });

    $('.expandable article.a-' + n).slideToggle('fast', function()
    {
      if ($(this).css('display') == 'none')
        $('#t-' + n + ' img').attr('src', '/resources/images/arrow-right.png');
      else
        $('#t-' + n + ' img').attr('src', '/resources/images/arrow-down.png');
    });
  });

  $('.item-box').click(function()
  {
    location.href = $(this).find('a').attr('href');
  });

  $('ul.highlight-selected li').each(function()
  {
    //var title = $('#middle h1.top').html();
    var path = window.location.pathname;
    var link = $(this).find('a').attr('href');
    if (path == link)
    {
      $(this).addClass('highlight');
    }
  });

  $('button.products').each(function()
  {
    var path = window.location.pathname;

    if (path.indexOf('modules') >= 0)
      $(this).html('Go to Products')
    else
      $(this).html('Go to Modules')
  });

  var popup_contents = {'hidensity': '<h3>HI-DENSITY</h3><ul><li>Up to 16 modules in one chassis</li><li>Less space</li><li>Less power/cooling</li><li>Green Footprint</li></ul>',
                        'modular'  : '<h3>MODULAR </h3><ul><li>Flexible system design: Every function has its own module </li><li>Easy to expand with additional services and functionality</li></ul>',
                        'hotswap'  : '<h3>HOT-SWAP (4RU)</h3><ul><li>Hot-swappable modules, power supplies and (independent) fans</li><li>Individual modules can be serviced or replaced while system is live</li></ul>'}

  $('#atvicons li')
  .hover(function(e) {
    this.hoverx = this.hoverx || $(this).offset().left - 80;
    this.hovery = this.hovery || $(this).offset().top  - 150;
    var popup_content = '<div class="close"></div>' + popup_contents[this.id];
    $('#hover_box').html(popup_content).css({left:this.hoverx,top:this.hovery}).clearQueue().fadeIn('fast');
  },function() {
    $('#hover_box').delay(500).fadeOut('fast');
  });

  // $('#left ul.box').addClass('upper-header');

  $('button.products').click(function()
  {
    var path = window.location.pathname;

    if (path.indexOf('modules') >= 0)
      location.href = '/products';
    else
      location.href = '/modules';
  });

  $('button').click(function()
  {
    var link = $(this).find('a');
    if (link.length > 0)
    {
      location.href = $(link).attr('href');
    }
  });

  $('.carousel').carousel({mode:'circle', auto: 10, transition: .7, tickbox: true});
  $('.page_slider .tickbox').css('margin-left', ($('.page_slider').width() - $('.page_slider .tickbox').width()) / 2);

  $('.tabs li').click(function()
  {
    var contents = $('#tab-output .content');
    var id = $(this).index();

    // highlight tabs
    $(this).parent().find('li').each(function() { $(this).removeClass('active'); });
    $(this).addClass('active');

    // show content
    $(contents).each(function() { $(this).hide(); });
    $(contents[id]).fadeIn('fast');
  });

  if(this.location.pathname && this.location.pathname.indexOf("/products") == 0) {
    $('.tabs li').last().trigger('click');
  } else {
    $('.tabs li').first().trigger('click');
  }

  $('#news-box li').click(function()
  {
    window.location = $(this).find('a').attr('href');
  });

  $('.datasheet').live('click', function()
  {
    if(!sessionStorage || (sessionStorage && !sessionStorage.getItem("gotUserData"))) {
      $('#dark-screen').width($(document).width());
      $('#dark-screen').height($(document).height());
      $('#dark-screen').fadeTo('fast', 0.6);
      $('#datasheet-popup').fadeIn('fast');
    } else {
      if($("input", this) && $("input", this).val()) { location.href = $("input", this).val(); }
    }
  });

  $('#ds-email').live('change',validate_email);
  $('#ds-name,#ds-company').live('change',validate_required);

  $('#datasheet-popup .close').live('click',datasheet_close);
});

function datasheet_close()
{
  $('#datasheet-popup').fadeOut('fast');
  $('#dark-screen').fadeOut('fast');
}

function datasheet_submit(form)
{
  var j_email = $('#ds-email');
  
  if (validate_required.call($('#ds-name'))
    && validate_required.call($('#ds-company'))
    && validate_email.call(j_email))
  {
      window.open ($('#ds-url').val(), 'ds_dl');
      ajaxform.submit(form, false);
      if(sessionStorage) { sessionStorage.setItem("gotUserData","true"); };
      datasheet_close();
      // var out = '<div style="text-align: center"><a href="' + $('#ds-url').val() + '">Download datasheet</a></div>';
      // $('#datasheet-popup').html(out);
      // $('#datasheet-popup').height(20);
      return true;
  }

  return false;
}

function validate_email()
{
    var isValidEmail = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;   
    var j_email = $(this);
    if (isValidEmail.test(j_email.val())) {
        j_email.css('background-color','transparent');
        return true;
    }
    j_email.css('background-color','#FF8888');
    return false;
}

function validate_required()
{
    var j_input = $(this);
    if (j_input.val().trim().length) {
        j_input.css('background-color','transparent');
        return true;
    }
    j_input.css('background-color','#FF8888');
    return false;
}
/*
function newsletter_submit(form)
{
  form.submit();
  // form.reset();
  // alert('Thank you for signing up for our newsletter.');
}
function form_submit(form)
{
  forms.submit(form);
}
*/

$.fn.serializeObject = function()
{
  var o = {};
  var a = this.serializeArray();

  $.each(a, function()
  {
    if (o[this.name])
    {
      if (!o[this.name].push) o[this.name] = [o[this.name]];
      o[this.name].push(this.value || '');
    }
    else
    {
      o[this.name] = this.value || '';
    }
  });
  return o;
};


var ajaxform =
{
  submit : function(id, msg)
  {
    if (typeof(msg) == 'undefined') msg = true;
    //var data = {"toJSON":"1", "form_id":id};
    var form = $('#' + id );
    var data = form.serializeObject();
    data['form_id'] = id;
    $.post (data.source, data, function(data) { ajaxform.response(data, msg) });
  },
  
  response : function(data, msg)
  {
    d = JSON.parse(data);
    if (d['mail_sent'] == 1)
    {
      if (msg)
      {
        alert('Your message has been sent.');
        //alert("Din henvendelse er mottatt");
        $('#' + d['form_id'])[0].reset();
      }
    }
  }
};

