//-----------------------------------------------------------------------------
// seekbyregion.m
//
// Example of an Animated Seekbar using Regions
// (Improved, no longer requires HiddenSeek)
//
// written by FrisbeeMonkey
//-----------------------------------------------------------------------------

#include </lib/std.mi>

Function setSeekAnim(int posValue);
Function updateSeek(int x, int y);

Global Layer Seek;
Global Map SeekMap;
Global Timer SeekTimer;
Global Boolean SeekChanging;

System.onScriptLoaded() {
	Group SeekGrp = getScriptGroup();

	Seek = SeekGrp.findObject("Seek");

	SeekTimer = new Timer;
	SeekTimer.setDelay(1000);

	SeekMap = new Map;
	SeekMap.loadMap("shogo.seek.map");

	if (getStatus()==0) {
		setSeekAnim(0);
	} else {
		SeekTimer.start();
		setSeekAnim(255 * System.getPosition() / System.getPlayItemLength());
	}
}

System.onPlay() {
	SeekTimer.start();
}

System.onStop() {
	SeekTimer.stop();
	setSeekAnim(0);
}

SeekTimer.onTimer() {
	setSeekAnim(255 * System.getPosition() / System.getPlayItemLength());
}

setSeekAnim(int Value) {
	Region r = new Region;
	r.loadFromMap(SeekMap, Value, 1);
	Seek.setRegion(r);
	delete r;
}

Seek.onLeftButtonDown(int x, int y) {
	SeekTimer.stop();
	SeekChanging = 1;
	updateSeek(x, y);
}

Seek.onLeftButtonUp(int x, int y) {
	SeekTimer.start();
	if (SeekChanging) {
		SeekChanging = 0;
		updateSeek(x, y);
	}
}

Seek.onLeaveArea() {
	SeekTimer.start();
	if (SeekChanging) SeekChanging = 0;
}

Seek.onMouseMove(int x, int y) {
	if (SeekChanging) {
		updateSeek(x, y);
	}
}

updateSeek(int x, int y) {
	int newValue = SeekMap.getValue(x - Seek.getLeft(), y - Seek.getTop());
	if (System.getPlayItemLength() >= 0) {
		int p = (newValue * 100) / 255;
		int s = (newValue * System.getPlayItemLength()) / 255;
		if (!SeekChanging) {
			System.seekTo(s);
		}
		setSeekAnim(255 * s / System.getPlayItemLength());
	}
}

System.onScriptUnloading() {
	delete SeekTimer;
	delete SeekMap;
}