function setBackground(bg, width, height) {
  $('#background').html('<img src="'+bg+'" alt="" />');
  backgroundw = width;
  backgroundh = height;
  backgroundratio = width/height;
  resizeBackground();
}

function resizeBackground() {
  if (backgroundratio > windowsizeratio) {
    $('#background img').css('height', '100%');
    $('#background img').css('width', 'auto');
  } else {
    $('#background img').css('height', 'auto');
    $('#background img').css('width', '100%');
  }
}
 
function showNextTaskbarIcon(id) {
  h = parseInt($('#taskbar > *:eq('+id+')').css('height'),10);
  if (!h)
    h = $('#taskbar > *:eq('+id+')').attr('height');
  $('#taskbar > *:eq('+id+')').css('left', id*40+80);
  $('#taskbar > *:eq('+id+')').animate({top: 38-h}, 400);
} 

function foo() {
}

function resizeWindow(selector, newwidth, newheight) {
  selector.css('height', newheight);
  selector.css('width', newwidth);
  selector.find('.container').css('height', newheight-46).css('width', newwidth-50);
  selector.find('.shadow-bm').css('width', newwidth-100).css('top', newheight-50);
  //selector.find('.shadow-br').css('width', newwidth);
  selector.find('.shadow-tr').css('left', newwidth-50);
  selector.find('.shadow-bl').css('top', newheight-50);
  selector.find('.shadow-br').css('left', newwidth-50).css('top', newheight-50);
  selector.find('.shadow-tm').css('width', newwidth-100);
  selector.find('.shadow-lm').css('height', newheight-100);
  selector.find('.shadow-rm').css('height', newheight-100);
  selector.find('.shadow-rm').css('left', newwidth-50);
}

function repositionTaskbars() {
  for (a = 0; a < taskbars.length; a++) {
    t = taskbars[a];
    if (!$('#taskbar_apps #task'+t.windowid).size())
      $('#taskbar_apps').append('<div id="task'+t.windowid+'" class="task"><div class="wrap1"><div class="wrap2"><div class="icon"><img src="'+t.icon+'" width="32" height="32" alt="" /></div><div class="caption">'+t.caption+'</div></div></div></div>');
  }
  w = $('#taskbar_apps').width();
  s = $('#taskbar_apps .task').size();
  if (s == 0)
    s = 1;
  appw = Math.floor(w / s);
  if (appw > maxtaskbarwidth)
    appw = maxtaskbarwidth;
  $('#taskbar_apps .task').css('width', appw);
  $('#taskbar_apps .task .caption').css('width', appw-52);
}

// divide desktop to sections 100
var desktopiconsmatrix = Array();
for (a = 0; a < 100; a++) {
  desktopiconsmatrix.push(5);
  
}

function repositionDesktopIcons() {
  iconwidth = 110;
  iconheight = 70;
  padding = 5;
  iconcountprev = 0;
  
  $('#desktopicons').css('width', $('#desktopicons .group').size()*iconwidth);
  $('#desktopicons .group').css('width', iconwidth);
  
  var bordertop = RUZEE.ShadedBorder.create({ corner:3, border:0, borderOpacity: 0.4, edges:"tlr" });
  var borderbottom = RUZEE.ShadedBorder.create({ corner:5, border:0, edges:"blr" });
  
  $('#desktopicons .group').each(function(i){
    iconcount = $(this).find('.icon').size();
    groupheight = (iconcount*iconheight+$(this).find('.grouptitle span').height()+$(this).find('.groupdescr').height())+10;
    $(this).css('height', groupheight);
    
    iconx = 0;
    while (desktopiconsmatrix[iconx] > windowsizey-groupheight)
      iconx++;
      
    $(this).find('.groupbackground').css('width', iconwidth);
    $(this).find('.groupbackground').css('height', groupheight-20);
    $(this).find('.groupbackground').css('top', 20);
    $(this).find('.groupicons').css('top', 20+$(this).find('.groupdescr').height()+8);
    $(this).css('top', desktopiconsmatrix[iconx]);
    $(this).css('left', iconx*(iconwidth+5)+5);
    desktopiconsmatrix[iconx] += groupheight+5;
    iconcountprev += iconcount;  
    
    //bordertop.render($(this).find('.grouptitle div'));
    borderbottom.render($(this).find('.groupbackground'));  
    $(this).css('display', 'block');
  });
  $('#desktopicons .group').hover(function(){
    $(this).animate({opacity:1},{queue:false,duration:300});
  }, function() {
    $(this).animate({opacity:0.4},{queue:false,duration:400});    
  });
}

function addDesktopIconsGroup(title, description) {
}

function addDesktopIcon(groupid, iconpath, icontitle) {
}

function addWindow(icon, caption, options, content) {
  // default values
  width = 600;
  height = 300;
  path = '';
  resizable = true;
  allowfullscreen = true;
  fullscreen = false;
  draggable = true;
  centered = false;
  opacity = 0.7;
  bgcolor = '#f6fcff';
  if (!content)
    content = '';
  
  if (options) {
    options = options.split('&');
    for (a = 0; a < options.length; a++) {
      namevalue = options[a].split('=');
      if (namevalue[0] == 'width')
        width = namevalue[1];
      else if (namevalue[0] == 'height') {
        height = namevalue[1];   
      } else if (namevalue[0] == 'path') {
        path = namevalue[1];
      } else if (namevalue[0] == 'resizable') {
        if (namevalue[1] == 'false')
          resizable = false;
        else
          resizable = true;
      } else if (namevalue[0] == 'fullscreen') {
        if (namevalue[1] == 'false')
          fullscreen = false;
        else
          fullscreen = true;
      } else if (namevalue[0] == 'allowfullscreen') {
        if (namevalue[1] == 'false')
          allowfullscreen = false;
        else
          allowfullscreen = true;
      } else if (namevalue[0] == 'draggable') {
        if (namevalue[1] == 'false')
          draggable = false;
        else
          draggable = true;
      } else if (namevalue[0] == 'centered') {
        if (namevalue[1] == 'false')
          centered = false;
        else
          centered = true;
      } else if (namevalue[0] == 'opacity') {
        opacity = parseFloat(namevalue[1],10);
      } else if (namevalue[0] == 'bgcolor') {
        bgcolor = namevalue[1];
      }
    } 
  }
  
  if (!content && !path)
    content = '&nbsp;';
  
  var a = windows.length+1;
  newid = 'window'+a;
  for (var c = 0; c < $('.window').size(); c++) {
    t = $('.window:eq('+c+') .caption').text();
    if (t == caption) {
      if (lastfocused)
        lastfocused.css('zIndex', 2);
      lastfocused = $('.window:eq('+c+')');
      lastfocused.css('zIndex', '1000');
      lastfocused.css('display', 'block');
      selectTaskbar(lastfocused.attr('id'));
      return;
    }
  }
  $('body').append("<div class='window' id='window"+a+"'><div class='shadows'><div class='shadow-tl'></div><div class='shadow-tr'></div><div class='shadow-bl'></div><div class='shadow-tm'></div><div class='shadow-bm'></div><div class='shadow-lm'></div><div class='shadow-rm'></div><div class='shadow-br'></div></div><div class='container' id='container"+a+"'><div class='caption'>"+caption+"</div><div class='title'><div class='buttons'><span class='minimize'><img src='images/window_minimize.png' width='27' height='19' alt='' /></span><span class='fullscreen'><img src='images/window_fullscreen.png' width='25' height='19' alt='' /></span><span class='close'><img src='images/window_close.png' width='45' height='19' alt='' /></span></div></div><div class='content'>"+content+"</div><div class='resize'></div></div></div>");
  
  windows[a] = Object();
  windows[a].zindex = a;
  windows[a].width = parseInt(width,10)+50+2; 
  windows[a].height = parseInt(height,10);
  windows[a].allowfullscreen = allowfullscreen; 
  windows[a].fullscreen = false; 
  windows[a].resizable = resizable; 
  windows[a].centered = centered;
  $('#window'+a).css('left', windows[a].left);
  $('#window'+a).css('top', windows[a].top);
  $('#window'+a).css('zIndex', 2);
  var border = RUZEE.ShadedBorder.create({ corner:10, border:1 });
  
  var taskbar = new Object();
  taskbar.windowid = a;
  taskbar.caption = caption;
  taskbar.icon = icon;
  taskbar.selected = true;
  windows[a].taskbar = taskbar;
  taskbars.push(taskbar);
  repositionTaskbars();
  
  $('#task'+a).click(function(){
    toggleWindow($(this).attr('id'));
  });
  selectTaskbar('window'+a);
  resizeWindow($('#'+newid), windows[a].width, windows[a].height);
  if (centered)
    windowCentrify('window'+a);
  else {
    windows[a].left = (a%10)*10; 
    windows[a].top = (a%10)*10; 
  }
  
  border.render($('#'+newid+' .container'));  
  $('#window'+a+' .sb-inner').css('opacity', opacity);
  $('#window'+a+' .sb-inner').css('background', bgcolor);
  
  activateButtons(a);
  if (resizable) 
    activateResizing(a);
  if (draggable)
    activateDragging(a);
  if (allowfullscreen)
    activateButtonFullscreen(a);
  
  if (path != '') {
    $('#window'+a).addClass('loading');
    $.get(path, function(data) {
      $(data).find('link').each(function(){
        csspath = $(this).attr('href');
        $("head").append("<link>");
        css = $("head").children(":last");
        css.attr({
          rel:  "stylesheet",
          type: "text/css",
          href: csspath
        });
      });
      $('#window'+a+' .container .content').html(data);
      $('#window'+a).removeClass('loading');
      
    });
    
  }
}

function selectTaskbar(id) {
  deselectTaskbars();
  num = id.substr(6);
  $('#task'+num).addClass('taskactive');
  $('#window'+num).css('zIndex', 1000);
}

function deselectTaskbars() {
  $('.task').removeClass('taskactive');
  $('.window').css('zIndex', 2);
}

function toggleWindow(id) { // task id given
  num = id.substr(4);
  if ($('#task'+num).hasClass('taskactive')) {
    deselectTaskbars();
    $('#task'+num).removeClass('taskactive');
    $('#window'+num).css('display', 'none');
  } else {
    deselectTaskbars();
    $('#task'+num).addClass('taskactive');
    $('#window'+num).css('display', 'block');
    bringWindowToFront('window'+num);
  }
}

function bringWindowToFront(id) {
  if (lastfocused)
    lastfocused.css('zIndex', 2);
  $('#'+id).css('zIndex', 1000);
  lastfocused = $('#'+id);
}

function windowCentrify(id) {
  $('#'+id).css('top', (windowsizey - $('#'+id+' .container').height())/2-42); 
  $('#'+id).css('left', (windowsizex - $('#'+id).width())/2);
  
}

function removeWindow(id) {
  $('body #'+id).remove();
  num = id.substr(6);
  $('body #task'+num).remove();
  for (a = 0; a < taskbars.length; a++) {
    if (windows[num].taskbar == taskbars[a])
      taskbars.splice(a,1);
  }
  delete windows[num].taskbar;  
  delete windows[num];
  repositionTaskbars();
}

function minimize(id) {
  $('body #'+id).css('display', 'none');
  deselectTaskbars();
}

function disableDragging(id) {
  $('#window'+id).find('.title').unbind('dragstart').unbind('drag');
  //$('#window'+id).find('.title').css('cursor', 'pointer');
  //$('#window'+id).find('.title').css('cursor', 'hand');
}

function disableResizing(id) {
  $('#window'+id).find('.resize').unbind('dragstart').unbind('drag');
  $('#window'+id).find('.resize').css('cursor', 'default');
}

function activateDragging(id) {
  $('#window'+id+' .title').css('cursor', 'move');
  $('#window'+id+' .title')
    .bind('dragstart',function( event ){
      return $(event.target).is('.title');
      })
    .bind('drag',function( event ){
      $( this ).parent().parent().css({
        top: event.offsetY-18,
        left: event.offsetX-23
      });
      windows[id].left = event.offsetX-23;
      windows[id].top = event.offsetY-18;
      
  });
}

function activateButtonFullscreen(id) {
  $('#window'+id+' .title').dblclick(function(e){
    $(this).parent().parent().find('.fullscreen').trigger('click');
  });
  
  $('#window'+id+' .fullscreen').click(function(e) {
    if (!windows[id].fullscreen) {
      windows[id].width = $('#window'+id).width();
      windows[id].height = $('#window'+id).height();
      $(this).parent().parent().parent().parent().css('zIndex', 1000);
      $(this).parent().parent().parent().parent().css('left', -24);
      $(this).parent().parent().parent().parent().css('top', -18);
      resizeWindow($(this).parent().parent().parent().parent(), windowsizex+50, windowsizey+6);
      $('#window'+id+' .title').css('cursor', 'move');
      disableDragging(id);
      disableResizing(id);
    } else {
      $('#window'+id+' .title').css('cursor', 'move');
      w = $(this).parent().parent().parent().parent();
      resizeWindow(w, windows[id].width, windows[id].height);
      w.css('left', windows[id].left);
      w.css('top', windows[id].top);
      activateDragging(id);
      if (windows[id].resizable)
        activateResizing(id);
    }
    windows[id].fullscreen = !windows[id].fullscreen;
  });
}

function activateButtons(id) {
  $('#window'+id+' .container').mousedown(function() {
    if (lastfocused != null && lastfocused != $(this).parent()) { 
      lastfocused.css('zIndex', 2);
      lastfocused = $(this).parent();
    }
    if (!lastfocused)
      lastfocused = $(this).parent(); 
    $(this).parent().css('zIndex', 1000); 
    selectTaskbar($(this).parent().attr('id')); 
  });
  $('#window'+id+' .title').mousedown(function() {
    if (lastfocused != null && lastfocused != $(this).parent().parent()) { 
      lastfocused.css('zIndex', 2);
      lastfocused = $(this).parent().parent();
    }
    if (!lastfocused)
      lastfocused = $(this).parent().parent(); 
    selectTaskbar($(this).parent().parent().attr('id')); 
  });
  
  $('#window'+id+' .close').click(function() {
    id = $(this).parent().parent().parent().parent().attr('id');
    removeWindow(id);
  });
  
  $('#window'+id+' .minimize').click(function() {
    id = $(this).parent().parent().parent().parent().attr('id');
    minimize(id);
  });
  
}

function activateResizing(id) {
  $('#window'+id).find('.resize').css('cursor', 'SE-resize');  
  $('#window'+id+' .resize')
    .bind('dragstart',function( event ){
      return $(event.target).is('.resize');
      })
    .bind('drag',function( event ){
      var windowxy = $( this ).parent().parent().position();
      var newwidth = event.offsetX-windowxy.left+36;
      var newheight = event.offsetY-windowxy.top+38;
      if (newwidth < 200)
        newwidth = 200;
      if (newheight < 100)
        newheight = 100;
      windows[id].width = newwidth;
      windows[id].height = newheight;
      resizeWindow($(this).parent().parent(), newwidth, newheight);
      
  }); 
}

/// startup menu

function showMenu(clicked) {
  if (startmenuvisible)
    return false;
  $('#startmenu').queue(function(){
    $(this).css('bottom', -$('#startmenu').height());
    $(this).dequeue();
  });
  if (clicked)
    $('#startmenu').animate({bottom: 41, opacity:1, filter:'opacity(100)'}, {duration:500, queue:false});
  else 
    $('#startmenu').animate({bottom: 41, opacity:1, filter:'opacity(100)'}, 500);
  startmenuvisible = true;
}

function hideMenu() {
  if (!startmenuvisible)
    return false;
  $('#startmenu').animate({bottom: -$('#startmenu').height(), opacity:0, filter:'opacity(0)'}, 300);
  startmenuvisible = false;
}

// misc
var clockTicked = true;
function clockTick() {
  d = new Date();
  h = d.getHours();
  m = d.getMinutes();
  if (m < 10)
    m = '0'+m;
  if (h < 10)
    h = '0'+h;
  if (clockTicked)
    $('#clock').html('<div class="hours">'+h+'</div>'+'<div class="delim">:</div>'+'<div class="minutes">'+m+'</div>');
  else
    $('#clock').html('<div class="hours">'+h+'</div>'+'<div class="delim">&nbsp;</div>'+'<div class="minutes">'+m+'</div>');
  clockTicked = !clockTicked;
  setTimeout('clockTick()', 1000);
}


// initiation

var windowsizex = 0;
var windowsizey = 0;
var windowsizeratio = 0;
var backgroundw = 0;
var backgroundh = 0;
var backgroundratio = 0;
var windows = Array();
var taskbars = Array();
var maxtaskbarwidth = 200;
var lastfocused = null;
var startmenuvisible = true;
var startmenutimeout = null;

jQuery(document).ready(function(){
  for (a = 1; a < $('#taskbar > *').size(); a++) {
    setTimeout('showNextTaskbarIcon("'+a+'")', a*200);
  }
  $('#taskbar_apps').css('marginLeft', (a-1)*40+120);
  
  $(window).resize(function() {
    windowsizex = $('body').width();
    windowsizey = $('body').height();
    windowsizeratio = windowsizex/windowsizey;
    resizeBackground();
    repositionTaskbars();
  });
  windowsizex = $('body').width();
  windowsizey = $('body').height();
  windowsizeratio = windowsizex/windowsizey;
  
  hideMenu();
  $('#startmenu').find('.linkblock').click(function(){
    hideMenu();
  });
  $('.startbutton').click(function() {
    clearTimeout(startmenutimeout);
    startmenutimeout = setTimeout('hideMenu()', 4000);
    showMenu(true);
    return false;
  });
  
  $('#startmenu').hover(function(){
    clearTimeout(startmenutimeout);
  }, function() {
    startmenutimeout = setTimeout('hideMenu()', 2000);
  });
  
  var totalmenus = 0;
  $('#startmenu .linkswrap > *').each(function(){
    if ($(this).hasClass('linkblock'))
      totalmenus += 42;
    else
      totalmenus += 20;
  });
  
  $('#startmenu .submenu').each(function(){
    i = $(this).parent().index();
    h = $(this).parent();
    toppos = 0;
    $('#startmenu .linkswrap > *').each(function(n){
      if (n == i) {
        return false;
      }
      if ($(this).hasClass('linkblock'))
        toppos += 42;
      else
        toppos += 20; 
    });
    maxheight = $(this).find('> *').size()*42;
    
    if (maxheight > totalmenus-toppos)
      $(this).css('top', totalmenus-maxheight-toppos-42);
    else
      $(this).css('top', -43);
    $(this).css('height', maxheight);
     
  }); 
  $('#startmenu .submenu').each(function(i){
    $(this).find('.sublink').each(function(n){
      $(this).css('top', n*42);
    });
  });
  
  repositionDesktopIcons();
  
  clockTick();
});
