
$(document).ready(function(){

  var fader;

  function animateSplash () {

    var images = $('#splash li');
    var cur = 0;
    var next = 0;

    for(var i = 0; i < images.length; i++) {
      if($(images[i]).css('opacity') > 0) {
        cur = i;
      } else {
        $(images[i]).css('opacity', 0);
      }
    }

    if(cur != images.length - 1) {
      next = cur + 1;
    }

    $(images[cur]).animate({
      opacity: 0
    }).removeClass('active');

    $(images[next]).animate({
      opacity: 1
    }).addClass('active');

  };

  function getCookies () {
    var cookies = { };
    if (document.cookie && document.cookie != '') {
      var split = document.cookie.split(';');
      for (var i = 0; i < split.length; i++) {
        var name_value = split[i].split("=");
        name_value[0] = name_value[0].replace(/^ /, '');
        cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
      }
    }
    return cookies;
  }

  // Needs to be before js-active to calculate un-hidden height
  if($('form div').length) {
    var h = 0;
    $('form div').each(function(e) {
      if($(this).height() > h) {
        h = $(this).height();
      }
    });
    $('#contentarea section').css('height', (h+100)+'px');
  }

  $('body').addClass('js-active');

  if($('body').hasClass('products')) {
    var orig = $('#series-intro').clone(true),
        intro = $('#series-intro');
    $('nav.serie a').mouseover(function(e) {
      $(intro).find('*').remove();
      $(intro).append('<h2>'+$(this).attr('title')+'</h2>');
    });
    $('nav.serie a').mouseout(function(e) {
      $(intro).find('*').remove();
      $(orig).children().each(function(e) {
        $(intro).append($(this).clone(true));
      });
    });
  }

  if($('#contentarea').hasClass('form')) {

    if($('form > div.active').length) {
      $('form > div').removeClass('hidden').addClass('disabled').find('ol').hide();
      $('form > div.active').removeClass('disabled').find('ol').show();
    } else {
      $('form > div ol').hide().first().show();
      $('form > div').removeClass('hidden').first().addClass('active');
      $('form > div').addClass('disabled').first().removeClass('disabled');
    }

    $('form .button.hidden').removeClass('hidden');
    $('form .button .next').each(function() {
      if($(this).data('next')) {
        $(this).val($(this).data('next'));
      }
    });

    $('form#application input').each(function() {
       if($('#review-'+this.name).length) {
         $('#review-'+this.name).find('em').html($(this).val());
       }
     });
    
     $('form#application .add').removeClass('hidden');
     $('form#application .special').hide();
    
     $('form#application input').change(function(e) {
       if($('#review-'+this.name).length) {
         $('#review-'+this.name).find('em').html($(this).val());
       }
     });
    
     $('form#application .add').click(function(e) {
       $(this).parents('li').next().removeClass('hide');
       $(this).parents('li').next().find('.add.hide').removeClass('hide');
       $(this).addClass('hide');
     });
    
     $('form#application h2, form#inquiry h2').click(function(e) {
       e.stopPropagation();
       if(!$(this).parent().hasClass('disabled')) {
         $('form > div').removeClass('active');
         $('form > div ol').hide();
         $(this).parent().addClass('active').find('ol').show();
       }
     });
    
     $('form#inquiry .headline').click(function(e) {
       e.stopPropagation();
       if($(this).data('section') && !$(this).data('on')) {
         $('form .'+$(this).data('section')).show();
         $(this).data('on', true);
         $(this).addClass('open');
       } else {
         $('form .'+$(this).data('section')).hide();
         $(this).data('on', false);
         $(this).removeClass('open');
       }
     });

     $('form#application .next').click(function(e) {
       e.preventDefault();
       e.stopPropagation();
       var errors = false,
           next = false, 
           submit = false,
           required = [],
           form = $('#application')
           ;
       $('form > div ol').hide().each(function() {
         if($(this).parent().hasClass('active')) {
           $(this).parent().find('input').each(function() {
             if($(this).parent().hasClass('required')) {
               if(this.name =='email' && this.value && !$(this).parent().hasClass('special')) {
                 var re = new RegExp(/^.+@.+\..+$/);
                 if(!this.value.match(re)) {
                   errors = true;
                   $(this).prev().addClass('error');
                 }
               } else if(!this.value && !$(this).parent().hasClass('special')) {
                 $(this).prev().addClass('error');
                 errors = true;
               } else {
                 $(this).prev().removeClass('error');
               }
             }
           });
           if(!errors) {
             next = true;
             submit = true;
           }
         }
         if(next && !errors && $(this).parent().next().length) {
           submit = false;
           $('form > div').removeClass('active');
           $(this).parent().next().removeClass('disabled').addClass('active');
           return false; // break
         }
       });
       if(submit && !errors) {
         $('form > div ol').last().show();
         $(this.form).submit();
       } else {
         $('form > div.active').find('ol').show();
       }
     });

     $('form#inquiry .next').click(function(e) {
       e.preventDefault();
       e.stopPropagation();
       var next, submit = false;
       $('form > div ol').hide().each(function() {
         if($(this).parent().hasClass('active')) {
           next = true;
           submit = true;
         } else if(next) {
           submit = false;
           $('form > div').removeClass('active');
           $(this).show();
           $(this).parent().removeClass('disabled').addClass('active');
           return false;
         }
       });
       if(submit) {
         $('form > div ol').last().show();
         $(this.form).submit();
       }
     });

     $('form#application').submit(function(e) {
       e.preventDefault();
       var errors = false, first, required = [
         'name',
         'email',
         'phone',
         'as',
         'begin',
         'cover',
         'cv'
       ];
       for (var i=0; i < required.length; i++) {
         if(!this[required[i]].value) {
           $(this[required[i]]).parent().find('label').addClass('error');
           if(!first) {
             first = required[i];
           }
           errors = true;
         } else {
           $(this[required[i]]).parent().find('label').removeClass('error');
         }
       };
       var re = new RegExp(/^.+@.+\..+$/);
       if(!this['email'].value.match(re)) {
         errors = true;
         first = 'email';
         $(this['email']).parent().find('label').addClass('error');
       }
       if(!errors) {
         $('#contentarea form').get(0).submit();
       } else if(first == 'name' || first == 'email' || first == 'phone') {
         $('form > div ol').hide();
         $('form > div').removeClass('active').addClass('disabled');
         $('form > div').first().addClass('active').removeClass('disabled');
         $('form > div').first().find('ol').show();
       }
     });

     $('form#inquiry').submit(function(e) {
       e.preventDefault();
       var errors = false, required = [
         'courtesy',
         'name',
         'company',
         'address',
         'email',
         'country'
       ];
       for (var i=0; i < required.length; i++) {
         if(!this[required[i]].value) {
           $(this[required[i]]).parent().find('label').addClass('error');
           errors = true;
         } else {
           $(this[required[i]]).parent().find('label').removeClass('error');
         }
       };
       var re = new RegExp(/^.+@.+\..+$/);
       if(!this['email'].value.match(re)) {
         errors = true;
         $(this['email']).parent().find('label').addClass('error');
       }
       if(!errors) {
         $('#contentarea form').get(0).submit();
       }
     });

     $('form#inquiry .subtract').live('click', function(e) {
       var c = $(this).parent().parent().attr('id').slice(3);
       $.cookie(c, null, { path: '/' });
       $(this).parent().parent().remove();
     });

     $('form#inquiry input.amount').live('keyup', function(e) {
       var c = $(this).prev('input').get(0).value;
       $.cookie(c, this.value, { path: '/' });
     });

     $('form#inquiry .remember').keyup(function(e) {
       $.cookie(this.name, this.value, { path: '/' });
     });

     if($("#add_article").length) {
       $("#add_article").autocomplete({
         source: $("#add_article").data('src'),
         minLength: 2,
         select: function(e, ui) {
           $("#add_article").parent().before('<li class="display" id="id-'+ui.item.value+'"><label><span class="subtract"></span></label> <input class="text" type="text" name="article[]" value="'+ui.item.value+'" disabled><a class="tip" href="'+$("#add_article").data('src')+'?q='+ui.item.value+'">'+ui.item.title+'</a></li>');
           $('#contentarea section').css('height', ($('#contentarea section').height()+50)+'px');
           $("#add_article").val('');
           $.cookie(ui.item.value, true, { path: '/' });
           if(ui.item.value.slice(0,1) == 4) {
             $('form .headline').addClass('warning');
             $('form#inquiry .headline').trigger('click');
           }
           return false;
         }
       });
     }
 
  }

  var articles = $('#articles table.articles');

  if(articles.length) {
    var sids = $(articles).find('tr'),
        c;
    for (var i=0; i < sids.length; i++) {
      c = $(sids[i]).attr('id').slice(3);
      if($.cookie(c)) {
        $(sids[i]).find('td.add img').get(0).src = '/assets/i/minus.png';
      }
    };
    $(articles).find('td.add img').click(function(e) {
      var sid = $(this).parent().parent().attr('id').slice(3);
      if($.cookie(sid)) {
        $.cookie(sid, null, { path: '/' });
        $(this).get(0).src = '/assets/i/plus.png';
      } else {
        $.cookie(sid, true, { expires: 7, path: '/' });
        $(this).get(0).src = '/assets/i/minus.png';
      }
    });
  }

  var $inquiry = $('#inquiry');

  if($inquiry.length) {
    // console.log(getCookies());
  }

  $('footer nav').show(function(e) {
    // $(this).find('h1').css('cursor', 'pointer').click(function(e) {
    //   $('footer nav ul').toggleClass('hidden');
    // });
    // $(this).find('ul').addClass('hidden');
  });

  if($('#contentarea.map').length) {

    function showLoc() {
      $('#contentarea.map h1').removeClass('selected');
      if($('#show').length) {
        $('#show').remove();
      }
      var sid = $(this).parent().attr('class').slice(0, 2);
          articles = $('article.'+sid);
      $('article.'+sid+' h1').addClass('selected');
      $('#secondary').append('<div id="show"></div>');
      for (var i=0; i < articles.length; i++) {
        $(articles[i]).children().each(function(e) {
          $('#show').append($(this).clone());
        });
      };
    }

    $('#contentarea.map h1').click(showLoc);
    showLoc.apply($('#contentarea.map .selected'));

  }


  if($('#technical-details').length) {
    $('#technical-details').hide();
    $('.illustrations').hide();
    $('#technical-details-toggle').click(function(e) {
      if($('#articles').is(':visible')) {
        $('#articles').hide();
        $('#technical-details').show();
        $('.illustrations').show();
        $(this).html($(this).data('articles'));
        $(this).attr('class', 'back');
      } else {
        $('#articles').show();
        $('#technical-details').hide();
        $('.illustrations').hide();
        $(this).html($(this).data('techdetails'));
        $(this).attr('class', '');
      }
      // if($('#articles').hasClass('hidden') && $('#main-img').data('technical')) {
      //   $('#main-img').get(0).src = $('#main-img').data('technical');
      // } else {
      //   $('#main-img').get(0).src = $('#main-img').data('detail');
      // }
    });
  }
  if($('body').hasClass('home')) {

    if($('.home section#splash').length) {
      var g = $('.home section#splash')[0];
      var paper = new Raphael(g, g.width, g.height);
      var els = {
        1:  { w:  57, h: 62, sx: -100, sy: -100, ex:   0, ey:  87 },
        2:  { w:  35, h: 22, sx: -100, sy: -100, ex:  64, ey: 145 },
        3:  { w:  50, h: 36, sx: -100, sy: -100, ex: 117, ey: 114 },
        4:  { w:  17, h: 13, sx: -100, sy: -100, ex: 158, ey:  99 },
        5:  { w:  23, h: 19, sx: -100, sy: -100, ex: 123, ey: 171 },
        6:  { w:  59, h: 56, sx: -100, sy: -100, ex:  31, ey: 185 },
        7:  { w:  39, h: 50, sx: -100, sy: -100, ex: 135, ey: 195 },
        8:  { w:  31, h: 19, sx: 1000, sy:  100, ex: 875, ey: 107 },
        9:  { w:  28, h: 28, sx: 1000, sy:  100, ex: 826, ey: 133 },
        10: { w:  18, h:  8, sx: 1000, sy:  100, ex: 859, ey: 162 },
        11: { w:  45, h: 28, sx: 1000, sy:  100, ex: 887, ey: 185 },
        12: { w: 109, h: 89, sx: 1000, sy:  100, ex: 823, ey: 204 }
      };
      for(el in els) {
        paper.image('/assets/i/intro/'+el+'.png', els[el].sx, els[el].sy, els[el].w, els[el].h).animate({
          x: els[el].ex,
          y: els[el].ey,
          rotation: 360
        }, 1000, false);
      }
    }

    var images = $('#splash li'),
        start = Math.floor(Math.random() * images.length);

    $(images).css('opacity', 0);
    $(images[start]).css('opacity', 1).addClass('active');

    fader = setInterval(animateSplash, 4000); 

  }

  if($('table').length) {
    var c = 0;
    $('table tr').each(function(e) {
      if(c % 2 != 0) {
        $(this).addClass('even');
      }
      c++;
    });
  }

  if($('table.chart').length) {
    var chartCount = 0;
    $('table.chart').each(function(e) {
      chartCount++;
      var sid = 'chart-'+chartCount,
          container = $(this).after('<div id="'+sid+'"></div>'),
          chart, data = [], keys, xValues = [0], records = {}, row, cells, id;
      $(this).css('display', 'none');
      $(container).css('padding', '100px 0px');
      $(container).css('width', '520px');

      keys = $(this).data('values').split(';');
      rows = $(this).find('tbody tr');

      for (var i=0; i < keys.length; i++) {
        records[keys[i]] = {
          name: keys[i],
          data: [0]
        };
      }

      for (var i=0; i < rows.length; i++) {
        cells = $(rows[i]).find('td');
        id = $(cells[0]).html();
        if(cells.length && records[id]) {
          if($(cells[2]).html()) {
            records[id].data.push(parseFloat($(cells[2]).html()));
          } else {
            records[id].data.push(null);
          }
        }
        if(jQuery.inArray($(cells[1]).html(), xValues) < 0) {
          xValues.push(parseFloat($(cells[1]).html()));
        }
      }

      for(var k in records) {
        data.push(records[k]);
      }

      chart = new Highcharts.Chart({
        chart: {
          renderTo: sid,
          defaultSeriesType: 'line',
          marginRight: 30,
          marginBottom: 50,
          backgroundColor: '#fff',
          borderRadius: 0,
          plotBackgroundColor: '#d7d8d6',
          plotBorderColor: '#fff',
          plotBorderWidth: 1,
          gridLineWidth: 1
        },
        series: data,
        colors: [
          '#fff104',
          '#00a3da',
          '#802c7c',
          '#d8207e',
          '#4db848'
        ],
        title: {
          style: { color: '#000' },
          text: $(this).find('caption').html(),
          x: 10 //center
        },
        xAxis: {
          title: {
            style: { color: '#000' },
            text: $(this).find('th.x').html()
          },
          gridLineColor: '#fff',
          gridLineWidth: 1,
          min: 0,
          startOnTick: true,
          tickmarkPlacement: 'on',
          lineWidth: 0,
          categories: xValues
        },
        yAxis: {
          min: 0,
          title: {
            style: { color: '#000' },
            text: $(this).find('th.y').html()
          },
          labels: {
            formatter: function() {
              return this.value;
            }
          },
          gridLineColor: '#fff'
        },
        tooltip: {
          enabled: false
        },
        plotOptions: {
          line: {
            animation: false,
            pointStart: 0,
            states: {
              hover: {
                enabled: false
              }
            }
          },
          series: {
            marker: { enabled: false },
            shadow: false
          }
        },
        legend: {
          layout: 'vertical',
          align: 'right',
          verticalAlign: 'top',
          x: -10,
          y: 100,
          borderWidth: 0
        },
        credits: {
          enabled: false
        }
      });

    });
  }

  var t = $('#articles table');

  if(t.length) {
    var th = $(this).find('th.filter'),
        options = {},
        col = null;

    // Set fixed width for all cols (prevent the table from changing
    // sizes as data is hidden/displayed)
    $('#articles table.articles th').each(function() {
      $(this).css('width', ($(this).width()+0)+'px');
    });

    $('#articles').data('filter', '');

    $('#articles table.articles th.reset').click(function(e) {
      e.preventDefault();
      e.stopPropagation();
      $('#articles').data('filter', {});
      $('#articles tr.row').show().removeClass('even');
      var c = 0;
      $('#articles tr.row').each(function(e) {
        if($(this).is(':visible')) {
          if(c % 2 == 0) {
            $(this).addClass('even');
          }
          c++;
        }
      });
      $('#articles table.articles th.reset img').hide();
    });

    for (var i=0; i < th.length; i++) {
      col = $(th[i]).data('col');
      options[col] = [];
      $(this).find('td.'+col).each(function(){
        var val = $.trim($(this).html());
        if($.inArray(val, options[col]) < 0) {
          options[col].push(val);
        }
        $(this).parent().addClass('val-'+col+'-'+$.inArray(val, options[col]));
      });
      if(options[col].length) {
        $('#wrap').append('<ul id="filter-'+col+'" class="options"></ul>');
        for (var j=0; j < options[col].length; j++) {
          $('#filter-'+col+'').append('<li>'+options[col][j]+'</li>');
        };
        $(th[i]).addClass('enabled').click(function(e) {
          e.preventDefault();
          var filter = $('#filter-'+$(this).data('col'));

          // $('#articles tr.row').show().removeClass('even');
          // var c = 0;
          // $('#articles table tr').each(function(e) {
          //   if(c % 2 != 0) {
          //     $(this).addClass('even');
          //   }
          //   c++;
          // });

          if($(filter).is(':visible')) {
            $(filter).hide();
          } else {
            var pos = $(this).offset(),
                pos2 = $('#articles').offset();
            $('ul.options').hide();
            $(filter).show().css({
              'left': (pos.left-pos2.left+220)+'px',
              'top': (pos.top-pos2.top+700)+'px'
            });
          }
        });
        $('ul.options').hide();
      }
    };

    $('ul.options li').click(function(e) {
      var col, val, opts = $(this).parent().find('li');
      col = $(this).parent().attr('id').slice(7);
      for (var i=0; i < opts.length; i++) {
        if(opts[i] == this) {
          break;
        }
      };
      val = i;

      var className = '',
          filters = {};
      if($('#articles').data('filter')) {
        filters = $('#articles').data('filter');
      }

      filters[col] = val;
      $('#articles').data('filter', filters);

      for(var f in filters) {
        className += '.val-'+f+'-'+filters[f];
      }

      $('#articles table.articles th.reset img').show().css('cursor', 'pointer');

      $(this).parent().hide();
      $('#articles tr.row').hide().removeClass('even');
      $('#articles tr.row'+className).show();

      var c = 0;
      $('#articles tr.row').each(function(e) {
        if($(this).is(':visible')) {
          if(c % 2 == 0) {
            $(this).addClass('even');
          }
          c++;
        }
      });

    });
  }

  $('#stage img').load(function(e) {
    if(!$('body').hasClass('products')) {
      $(this).css('marginTop', '0px');
      if(this.height != 380) {
        $(this).css('marginTop', ((380-this.height)/2)+'px');
      }
      $(this).animate().fadeIn(200);
      var images = $('#gallery a');
      for (var i=0; i < images.length; i++) {
        if($(images[i]).get(0).href == $(this).get(0).src) {
          $('#pos').get(0).innerHTML = i+1;
          if($(images[i]).attr('title')) {
            $('#stage .caption').get(0).innerHTML = $(images[i]).attr('title').replace('**em**', '<strong>em</strong>');
          } else {
            $('#stage .caption').get(0).innerHTML = $(images[i]).find('img').attr('title').replace('**em**', '<strong>em</strong>');
          }
          if($('#pos').get(0).innerHTML.length == 1) {
            $('#pos').get(0).innerHTML = '0'+$('#pos').get(0).innerHTML;
          }
        }
      };
    }
  });
  $('#gallery a').click(function(e) {
    e.preventDefault();
    var href = this.href;
    var title = this.title;
    if($('#stage img')[0].src == href) {
      return;
    }
    $('#stage img').animate().fadeOut(200, function(e) {
      $('#stage img')[0].src = href;
      $('#stage .caption')[0].text = title;
    });
    $('#gallery li').removeClass('selected');
    $(this.parentNode).addClass('selected');
  });
  $("#stage nav").delegate('li', 'click', function(e){
    var els = $('#gallery a'),
        img = $('#stage img')[0],
        c,n;
    for (var i=0; i < els.length; i++) {
      if(els[i].href == img.src) {
        c = els[i];
        break;
      }
    };
    if($(this).hasClass('next') && els[i+1]) {
      n = i+1;
    } else if($(this).hasClass('prev') && els[i-1]) {
      n = i-1;
    }
    if(n >= 0) {
      $(img).animate().fadeOut(function(e) {
        img.src = els[n].href;
      });
      $('#gallery li').removeClass('selected');
      $(els[n].parentNode).addClass('selected');
    }
    return false;
  });
});
