var MouseX;
var MouseY;

function SetMPos()
{
	MouseX = xMousePos;
	MouseY = yMousePos;
}

function CL(target)
{
	if(Math.abs(MouseX-xMousePos)<5 || Math.abs(MouseY-yMousePos)<5){
		window.location = target;
	}
	else{
	return FALSE;
	}
}

// Set Netscape up to run the "captureMousePosition" function whenever
// the mouse is moved. For Internet Explorer and Netscape 6, you can capture
// the movement a little easier.
if (document.layers) { // Netscape
    document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
    document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
    document.onmousemove = captureMousePosition;
}
// Global variables
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xMousePosMax = 0; // Width of the page
yMousePosMax = 0; // Height of the page

function captureMousePosition(e) {
    if (document.layers) {
        // When the page scrolls in Netscape, the event's mouse position
        // reflects the absolute position on the screen. innerHight/Width
        // is the position from the top/left of the screen that the user is
        // looking at. pageX/YOffset is the amount that the user has
        // scrolled into the page. So the values will be in relation to
        // each other as the total offsets into the page, no matter if
        // the user has scrolled or not.
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    } else if (document.all) {
        // When the page scrolls in IE, the event's mouse position
        // reflects the position from the top/left of the screen the
        // user is looking at. scrollLeft/Top is the amount the user
        // has scrolled into the page. clientWidth/Height is the height/
        // width of the current page the user is looking at. So, to be
        // consistent with Netscape (above), add the scroll offsets to
        // both so we end up with an absolute value on the page, no
        // matter if the user has scrolled or not.
        xMousePos = window.event.x+document.body.scrollLeft;
        yMousePos = window.event.y+document.body.scrollTop;
        xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
        yMousePosMax = document.body.clientHeight+document.body.scrollTop;
    } else if (document.getElementById) {
        // Netscape 6 behaves the same as Netscape 4 in this regard
        xMousePos = e.pageX;
        yMousePos = e.pageY;
        xMousePosMax = window.innerWidth+window.pageXOffset;
        yMousePosMax = window.innerHeight+window.pageYOffset;
    }
}

var spacedrag;
var start_left=0;
var start_top=0;
var page_width=48*12;
var page_height=36*12;
var margin_width=48*12;
var margin_height=36*12;

function getChars(mode) {
  if(spacedrag){spacedrag.destroy(); $('loading').style.display='block';}
  var top=$('beefsquare').style.top.replace('px','')*1;
  if(!top){top=margin_height*-1;}
  top=top+margin_height;
  var left=$('beefsquare').style.left.replace('px','')*1;
  if(!left){left=margin_width*-1;}
  left=left+margin_width;
  top=(parseInt(start_top/12)*12-top*1);
  left=(parseInt(start_left/12)*12-left*1);
  new Ajax.Request('./'+mode+'chars.php?&top='+top+'&left='+left,
    {
      method:'get',
      onSuccess: function(transport){
        var response = transport.responseText || "no response text";
        if(mode=='choose'){
          $('holder').innerHTML=choose_convert(response);
          $('loading').style.display='none';
  			} else{
          $('holder').innerHTML=convert(response);
          HighLighter();
          start_left=left;
          start_top=top;
          var sec_x=(left/page_width)+'';
          var sec_y=(top/page_height)+'';
          $('sec_x').value=roundNumber(sec_x,2);
          $('sec_y').value=roundNumber(sec_y,2);
          spacedrag=new Draggable('beefsquare', { starteffect: false, endeffect:false, onEnd: function() {getChars(mode);}});
          $('loading').style.display='none';
        }        
      },
      onFailure: function(){ alert('Something went wrong...');}
    });
}

function writeMenu(){
  getChars('choose');
  $('infobox').innerHTML='<p>choose your starting character!<br /><a href=\"#\" onClick=\"mainInfo();return false;\">cancel</a></p><p>+you can write text anywhere for free!<br />+you can modify your submitted text for a while, but after a week, anyone can overwrite it with his own(but why would he? there are plenty of space)<br />+if i find some nice artwork, i may set it to protected for a longer time<br />+new texts are coloured white for a whole day<br />+have fun!</p>'; 
}
function buyMenu(){
  setTimeout("$('infobox').innerHTML='<p><a href=\"#\" onClick=\"mainInfo();return false;\">&lt;&lt;back</a></p><p>+for buying characters, write to: <a href=\"mailto:charspace@high-end.hu\">charspace@high-end.hu</a></p><p>Terms: <br />+you can buy any character you want, anywhere you want(of course if its not sold already)<br />+one character costs 5USD, even white spaces<br />+you can buy as many characters as you like, in any shape you want<br />+every character can have a link to a website<br />+paid characters are highlighted with different color<br />+you cannot change the text or link once you have submitted them, but you can ask me to remove them. of course you will not get refund<br />+i keep the right of rejecting the content you submit<br />+your characters stay on their positions for at least a year<br />+the website loads randomly on a sector that has paid characters</p>';",500);   
}

function cC(x,y){
  Effect.Pulsate('infobox', { pulses: 1, duration: 0.2 });
  $('infobox').innerHTML="<table border=\"0\" align=\"right\" id=\"submit_table\"><tr><td>text direction: </td><td><input type=\"radio\" name=\"d\" checked />left-right<input type=\"radio\" name=\"d\" id=\"direction\" />top-down</td></tr><tr><td>text: </td><td><input type=\"text\" name=\"text\" id=\"text\" size=\"38\" maxlength=\"48\" /></td></tr><tr><td colspan=\"2\"><a href=\"#\" onClick=\"mainInfo();return false;\">cancel</a> <a href=\"#\" onClick=\"submitText("+x+","+y+");return false;\">submit&gt;&gt;</a></td></tr></table>";
  $('text').focus();
}
function mainInfo(){
  getChars('get');
  setTimeout("$('infobox').innerHTML='<p><a href=\"#\" onClick=\"writeMenu();return false;\">write text&gt;&gt;</a><br /><a href=\"#\" onClick=\"GoToSector(1985,2);return false;\">about me&gt;&gt;</a></p><p>+move the page with your mouse<br />+choose your own sector<br />+play scrabble, amoeba<br />+create ASCII art<br />+chat with friends<br />+meet new people<br />+leave message to the world<br />+express yourself</p>';",500);
}
//setTimeout("$('infobox').innerHTML='<p><a href=\"#\" onClick=\"writeMenu();return false;\">write text&gt;&gt;</a><br /><a href=\"#\" onClick=\"buyMenu();return false;\">buy text&gt;&gt;</a><br /><a href=\"#\" onClick=\"GoToSector(1985,2);return false;\">about me&gt;&gt;</a></p><p>+move the page with your mouse<br />+choose your own sector<br />+play scrabble, amoeba<br />+create ASCII art<br />+chat with friends<br />+meet new people<br />+leave message to the world<br />+express yourself</p>';",500);

function submitText(x,y){
  var direction='right';
  if ($('direction').checked) {direction='down';}
  var text=encodeURIComponent($('text').value);
  new Ajax.Updater('infobox', './submittext.php?direction='+direction+'&x='+x+'&y='+y+'&text='+text, { method: 'get' });
  setTimeout("getChars('get')",1000);
}

function GoToSector(x,y){
	$('sec_x').value=x;
    $('sec_y').value=y;
	moveToSector();
}

function moveToSector(){
  //Effect.Pulsate('holder', { pulses: 1, duration: 1 }); 
  start_left=($('sec_x').value)*page_width;
  start_top=($('sec_y').value)*page_height;
  setTimeout("$('beefsquare').style.left=margin_width*-1+'px';$('beefsquare').style.top=margin_height*-1+'px';mainInfo()",1000);
  setTimeout("Effect.Appear('beefsquare', { duration: 1.0 });",1500);
}

var arrayChar = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];

function convert(tString) {
	var rex = new RegExp(/<(\d+)>/g);
	var m = tString.match(rex);
	for (i = 0; i < m.length; i++) {
	  strReplacement = "";
	  for (j = 0; j < m[i].substr(1, m[i].length-2); j++) { 
      strReplacement = strReplacement + arrayChar[random(arrayChar)]; 
    }
	  tString = tString.replace(m[i], strReplacement);
  }
	return tString;
}

function choose_convert(tString) {
	var rex = new RegExp(/<[-]?(\d+)[,][-]?(\d+)[,](\d+)>/g);
	var m = tString.match(rex);
	for (i = 0; i < m.length; i++) {
	  var strReplacement = "";
    var data=m[i].substr(1, m[i].length-2);
    var split_data=data.split(",");
	  for (j = 0; j < split_data[2]; j++) { 
      strReplacement = '<a href="#" onClick="cC('+(split_data[0]*1-j*1)+','+split_data[1]+');return false;">'+arrayChar[random(arrayChar)]+'</a>'+strReplacement;
    }
	  tString = tString.replace(m[i], strReplacement);
  }
	return tString;
}

function random(vArray) { return Math.round(Math.floor(Math.random() * vArray.length)); }

//LINK HIGHLIGHTER
var anchors;

function HighLighter() {
  anchors = document.getElementById('beefsquare').getElementsByTagName('a');
  for (i=0; i<anchors.length; i++) {
    anchors[i].onmouseover = function() { HighLightAnchor(this, true); };
    anchors[i].onmouseout = function() { HighLightAnchor(this, false); };
  }
}

function HighLightAnchor(obj, dothat) {
  for (i=0; i<anchors.length; i++) {
    if (anchors[i].href == obj.href) {
	  if (dothat) {anchors[i].className = "highlight";} else {anchors[i].className = "normal";}
	} 
  }
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
