function callback(name, data) {
  if (!data) data = "";
  window.location.href = "skp:" + name + "@" + data;
}

function init() {
  var w = $( "#main-collapsible" ).width();
  var h = $( "#main-collapsible" ).height();
  var data = "["+w+","+h+"]";
  callback("init", data);
}

function adjust_size() {
  var w = $( "#main-collapsible" ).width();
  var h = $( "#main-collapsible" ).height();
  var data = "["+w+","+h+"]";
  callback("adjust_size", data);
}

$(document).ready( function() {

  var md = false;
  var pos = [0,0];
  var dragged = false;

  // Initialize
  window.setTimeout(init, 0);

  // Animate collapsible.
  $( ".ui-collapsible-heading-toggle" ).on("click", function (e) {
    if (dragged) return false;
    var current = $(this).closest(".ui-collapsible");
    if (current.hasClass("ui-collapsible-collapsed")) {
      // Collapse all others and then expand this one.
      //$(".ui-collapsible").not(".ui-collapsible-collapsed").find(".ui-collapsible-heading-toggle").click();
      $(".ui-collapsible-content", current).slideDown(400);
    } else {
      $(".ui-collapsible-content", current).slideUp(400);
    }
  });

  $( "#main-collapsible" ).click();

  // Adjust size
  jQuery.resize.delay = 30;
  $( "#main-collapsible" ).resize( function() {
    adjust_size();
  });

  // Process checkbox and radio input triggers.
  $( "input[type=checkbox], input[type=radio]" ).change( function() {
    callback("input_changed", "[:"+this.id+","+this.checked+"]");
  });

  // Process button clicks.
  $( "a[data-role=button], div[data-role=button]" ).click( function() {
    callback("button_clicked", this.id);
  });

  $( window ).focus(function() {
    callback("window_focus");
  });

  $( window ).blur(function() {
    callback("window_blur");
  });

  $( document ).mouseenter(function() {
    callback("window_mouse_enter");
  });

  $( document ).mouseleave(function() {
    callback("window_mouse_leave");
  });

  setInterval( function(){
    callback("timer");
  }, 10);

  // Detect Drag
  $( "#main-header" ).mousedown(function(e) {
    md = true;
    var x = e.clientX;
    var y = e.clientY;
    pos = [x,y];
    callback("drag_start", null);
    dragged = false;
    return false;
  });
  $( document ).mousemove(function(e) {
    if (!md) return;
    var x = e.clientX;
    var y = e.clientY;
    var dx = x-pos[0];
    var dy = y-pos[1];
    if ((dx == 0) && (dy == 0)) return;
    dragged = true;
    callback("drag", "["+dx+","+dy+"]");
	return false;
  });
  $( document ).mouseup(function(e) {
    if (md) {
      md = false;
      callback("drag_end", null);
	  return false;
    }
  });
});
