
function editCSS() {

  var width = Math.max(300,Math.min(parseInt(window.localStorage.cssEditorWidth),1000));

  var $page = 
  $('<div id="cssedit-page"></div>')
  $('body').html($page);

  var windowName = 'w'+((Math.random()*10000)|0);
  var href = location.href.split('#')[0];
  href = href + (location.href.indexOf('?') > -1 ? '&' : '?') + 'tools=mainframe';
  var $iframe = 
  $('<div id="cssedit-html"><iframe style="width:100%;height:100%" name="'+windowName+'" id="htmlframe" src="'+href+'"></iframe></div>')
  .appendTo($page);

  function _getSheets(sheet,sheets) {
    sheets.push(sheet);
    for (var i = 0; i<sheet.cssRules.length; i++) {
      var s = sheet.cssRules.item(i);
      if (s.type==3) _getSheets(s.styleSheet,sheets);
    }
  }
  
  function getSheets(doc) {
    var sheets = [];
    for (var i=0; i < doc.styleSheets.length; i++) {
      _getSheets(doc.styleSheets.item(i),sheets);
    }
    return sheets;
  }
  function removeSheets(doc,sheets) {
    for (var i=0; i<sheets.length;i++) {
      $(sheets[i].ownerNode).remove();
    }
  }
  
  function makeBoxes(doc,sheets) {
    var boxes = [];
    for (var i=0; i<sheets.length;i++) {
      boxes.push(makeBox(doc,sheets[i]));
    }
    return boxes;
  }

  function setupBox(doc,box) {
      box.$style = $('<style>' + box.$text.val() + '</style>').appendTo($('head',doc));
      box.$style.html(box.$text.val());
  }
  
  function setupBoxes(doc,boxes) {
    for (var i = 0; i<boxes.length; i++) {
      setupBox(doc,boxes[i]);
    }
  }
  
  var loaded = false;
  var boxes = [];

  $('#htmlframe').load(function () {
    var doc = frames[windowName].document;
    sheets = getSheets(doc);
    if(!loaded) boxes = makeBoxes(doc,sheets);
    removeSheets(doc,sheets);
    if (loaded) setupBoxes(doc,boxes);
    loaded = true;
  });
  
  var $editor = 
  $('<div id="cssedit-editor"></div>')
  .appendTo($page);
  
  var $tabs = 
  $('<div id="cssedit-tabs"></div>')
  .appendTo($editor);
 
  function setWidth(w) {
    width = Math.max(200,Math.min(w,1000));
    $editor.width(width);
    $iframe.css('left',width);
    window.localStorage.cssEditorWidth = width;
    
  }
  setWidth(width); 
  var $more = 
  $('<button id="cssedit-more">&gt;</button>')
  .click(function() {
    setWidth(width+100);
  })
  .appendTo($tabs);
  var $less = 
  $('<button id="cssedit-less">&lt;</button>')
  .click(function() {
    setWidth(width-100);
  })
  .appendTo($tabs);

  
  function makeBox(doc,sheet) {
    var msg = sheet.href.match( /css[/]([^?]*)/ );
    if (!msg) return;
    msg = msg[1];

    var box = {
      doc:doc,
      sheet:sheet,
      msg:msg
    }
    
    box.$box = 
    $('<div class="cssedit-box"></div>')
    .appendTo($editor);

    box.$tab =
    $('<button class="cssedit-tab">'+msg+'</button>')
    .click(function() {
      box.$box.appendTo($editor);
      $tabs.find('.cssedit-tab.selected').removeClass('selected');
      box.$tab.addClass('selected');
    })
    .appendTo($tabs);
    box.$tab.click();


    $.get(sheet.href, function(data) {
      var T = null;
      var oldtext = data;
      
      box.$textwrap= 
      $('<div class="cssedit-textwrap"></div>')
      .appendTo(box.$box);

      box.$text =
      $('<textarea class="cssedit-textarea">'+data+'</textarea>')
      .keyup(function() {
        clearTimeout(T);
        T = setTimeout(function() {
          box.$tab.text('*'+msg);
          box.$style.html(box.$text.val());
          box.$save.removeAttr('disabled');
        }, 1000)
      })
      .appendTo(box.$textwrap);

      box.$bar = 
      $('<div class="cssedit-bar"></div>')
      .appendTo(box.$box);

      box.$save =
      $('<button id="cssedit-save" class="cssedit-button">save</button>')
      .click(function() {
        box.$save.attr('disabled','disabled');
	      $.get('/w/api.php?format=json&action=query&meta=userinfo',function(data){
		      var user = data.query.userinfo.name;
		      var title = 'MediaWiki:'+msg+'.css';
		      $.get('/w/api.php?format=json&action=query&prop=info&intoken=edit&titles='+title,function(data){
			      var token;
			      for (var i in data.query.pages) {
				      token = data.query.pages[i].edittoken;
			      };
			      var args = {
				      action:'edit',
				      title: title,
				      text: box.$text.val(),
				      summary: 'from css editor',
				      token: token,
				      format: 'json'
			      };
			      $.post('/w/api.php', args, function(data) {
              box.$save.attr('disabled','disabled');
              box.$tab.text(msg);
			      });
		      },'json');
	      },'json');
      })
      .appendTo(box.$bar);

      box.$close =
      $('<button id="cssedit-close" class="cssedit-button">close</button>')
      .click(function() {
        top.location.reload(true);
      })
      .appendTo(box.$bar);
      setupBox(doc,box);
    });  
    return box;
  }
}

$(function() {
  $('a[href=#editCSS]').click(function(e) { 
    editCSS();
  });
  $('.itemlist h2').click(function(e) {
    $(this).parents('.itemlist').toggleClass('open');
  });
  
  $('article:not(.active),aside:not(.active)').live('click',function(e) {
      var $this = $(this);
      var $box = $this;
      
      var y1 = $box.offset().top;
      var st = $(window).scrollTop();
      
      $('.column, article, aside').not($this).removeClass('active');
      $this.closest('.column').andSelf().addClass('active');

      var y2 = $box.offset().top;
      
      $(window).scrollTop( Math.min(st + y2-y1, $(document).height()-$(window).height() ));
      e.stopPropagation();
  });
  $('.column:not(.active)').live('click',function(e) {
      var $this = $(this);
      $('.column, article, aside').not($this).removeClass('active');
      $this.addClass('active');
  });
  
  $('.columns a').live('click',function(e) {
      if (!this.href.match(/^(http:\/\/skica.at)?\//)) return;
      if (this.href.match(/title=/)) return;
      e.preventDefault();
      //self.history.pushState({},this.title,this.href);
      top.location = top.location.href.replace(/#.*$/,'') + '#' + this.href.replace(/^http:\/\/[^/]+/,'');
  });
  
  var $rotator = 
  $('.rotator')
  .eq(0)
  .mouseenter(rotatorStop)
  .mouseleave(rotatorStart)
  ;
  var rotatorTimeout = null;
  
  function rotatorStart() {
    rotatorTimeout = setTimeout (function() {
      var $current = $rotator.find('article.opaque')
      .removeClass('opaque')
      .eq(0);
      var $next = $current.next('article');
      if (!$next.length) $next = $current.siblings('article').eq(0);
      $next.addClass('opaque');
      rotatorStart();
    },5000);
  }
  function rotatorStop() {
    clearTimeout(rotatorTimeout);
  }
  $rotator.find('article').removeClass('opaque').eq(0).addClass('opaque');
  rotatorStart();
});