/* Author: Robert Weber

*/

// Gallery handler
jQuery(document).ready(function($) {
  if($('.other-images').length) {
    $('.other-images img').each(function(){
      $(this).css({'cursor':'pointer'});
      $(this).bind('click', function(){
        $('#content b.keyvisual img:first').get(0).src = this.src;
      });
    });    
  }  
});

// function to adjust the viewport
(function(win,doc){
  window.adjustViewport = function( property, value ) {
    var
    $viewport = $('meta[name=viewport]'),
    currently = $viewport.attr('content'),
    o_props   = currently.split(/\s,\s?/),
    n_props   = [],
    i         = o_props.length,
    set       = false;
    while ( i-- ) {
      o_props[i] = o_props[i].split(/\s?=\s?/);
      if ( o_props[i][0] == property ) {
        if ( value !== false ) {
          o_props[i][1] = value;
          n_props.push( o_props[i].join('=') );
        }
        set = true;
      } else {
        n_props.push( o_props[i].join('=') );
      }
    }
    
    if ( ! set ) {
      n_props.push(property+'='+value);
    }
    
    n_props = n_props.join(',');
    $viewport.attr('content',n_props);
  };
})(window);


(function(win){
  var 
  showing = 'old',
  $window = $(window),
  $mob_nav = $('<select />'),
  $option = $('<option>-- Navigation --</option>').appendTo($mob_nav),
  $old_nav = $('#sub-navigation ul'),
  timer = null;
  
  $('#main-navigation > ol > li, #sub-navigation > ul > li').each(function(){
     var $a = $(this).find('a:first');
     var $new_opt = $option.clone().attr('value', $a.attr('href')).text($a.text()).appendTo($mob_nav);
     if($a.hasClass('current')) $new_opt.get(0).selected = true;
     if($(this).find('li').length){
          $(this).find('li').each(function(){
              var $a = $(this).find('a:first');
              var $new_opt = $option.clone().attr('value', $a.attr('href')).text("--- "+$a.text()).appendTo($mob_nav);
              if($a.hasClass('current')) $new_opt.get(0).selected = true;
          });
     }
  });

  $mob_nav.bind('change', function(){
    location.href = this.value;
  });

  function toggleDisplay() {
    var width = $window.width();
    if ( showing == 'old' && width <= 659 ) {
      $old_nav.replaceWith($mob_nav);
      showing = 'new';
      $('#main-navigation').hide();
      adjustViewport('user-scalable','no');
    } else if ( showing == 'new' && width > 659 ) {
      $mob_nav.replaceWith($old_nav);
      showing = 'old';
      $('#main-navigation').show();
      adjustViewport('user-scalable',false);
    }
    
    if($("table.gadget iframe:first").length && width > 800) {
      $("table.gadget iframe:first").get(0).scrolling = "yes";
    }
  }

  toggleDisplay();

  $window.resize(function(){
    if ( timer ) {
      clearTimeout(timer);
    }
    timer = setTimeout(toggleDisplay,100);
  });
	
})(window);
