function explode( delimiter, string, limit ) {
    var emptyArray = { 0: '' };
    if ( arguments.length < 2
        || typeof arguments[0] == 'undefined'
        || typeof arguments[1] == 'undefined' )
    {
        return null;
    } 
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
	
        return partA;
    }
}

function ge()
{
  var ea;
  for( var i = 0; i < arguments.length; i++ ) {
    var e = arguments[i];
    if( typeof e == 'string' )
      e = document.getElementById(e);
    if( arguments.length == 1 )
      return e;
    if( !ea )
      ea = new Array();
    ea[ea.length] = e;
  }
  return ea;
}

function show()
{

  for( var i = 0; i < arguments.length; i++ ) {
    var element = ge(arguments[i]);
    if (element && element.style) element.style.display = 'block';
  }
}

function hideTags()
{
  for( var i = 0; i < arguments.length; i++ ) {
    var element = ge(arguments[i]);
    if (element && element.style) element.style.display = 'none';
  }
}

function shown(el) {

    el = ge(el);
    return (el.style.display != 'none');
}

function cancelHit()
{   
	tagFrameFinish();
    resetSelector();
	if (textFileType == 'album') {
		ge('img_src').style.cursor = 'default';
	} else {
		ge('myphoto').style.cursor = 'default';
	}
	taginst = ge('tagging_instructions');
	taginst.style.display = 'none';
	return false;
} 

function nameChange(event)
{ 

  activePersonName = "";
  activePersonID = -2;
}

function commonKeydown(e) {

    if (!e) {
        e = window.event;
    }
    var key = e.keyCode;
    if (ge('isFocused').value == 0) {
     if (e.ctrlKey) {
             if (key == 37) {
                 var p = document.getElementById('prevp');
                 if (p) {
                     location.href = p.href;
                 }
             } else if (key == 39) {
                 var n = document.getElementById('nextp');
                 if (n) {
                     location.href = n.href;
                 }
             }
     }
    }

}

// Get Absolute X Position of HTML Element
function findX(obj)
{
		
  var curleft = 0;
  if (obj.offsetParent) {
    while (obj.offsetParent) {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;
  return curleft;
}

// Get Absolute Y Position of HTML Element
function findY(obj)
{
  var curtop = 0;
  if(obj.offsetParent) {
    while (obj.offsetParent) {
      curtop += obj.offsetTop
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}

function mousePosX(e)
{
  var posx = 0;
  if (!e) var e = window.event;
  if (e.pageX)
    posx = e.pageX;
  else if (e.clientX && document.body.scrollLeft)
    posx = e.clientX + document.body.scrollLeft;
  else if (e.clientX && document.documentElement.scrollLeft)
    posx = e.clientX + document.documentElement.scrollLeft;
  else if (e.clientX)
    posx = e.clientX;
  return posx;
}

function mousePosY(e)
{
  var posy = 0;
  if (!e) var e = window.event;
  if (e.pageY)
    posy = e.pageY;
  else if (e.clientY && document.body.scrollTop)
    posy = e.clientY + document.body.scrollTop;
  else if (e.clientY && document.documentElement.scrollTop)
    posy = e.clientY + document.documentElement.scrollTop;
  else if (e.clientY)
    posy = e.clientY;
  return posy;
}


var ajaxml = false;
var tagging = false;
var tagging_initialized = false;
var frameWidth = 166;
var frameHeight = 166;
var activePersonID = -2;
var activePersonName ='';
var activeImageMouseX;
var activeImageMouseY;
var pid = 0;
var id = 0;
var idname = "";
var user = 0;
var oid = 0;
var aid = 0;

var foundCount = 0;
var lastFoundName = '';
var lastFoundID = 0;
var tagtimerID = 0;
var lastAddedTag = -1;

// minimum W and H of the frame when resizing
var frameMinW = 30, frameMinH = 30;
var frameNewW = 100, frameNewH = 100;

// Helpers and the frame itself
var frameElements = ['nw', 'n', 'ne', 'w', 'tagframe2', 'tagframe2inside3', 'spyphoto', 'e', 'sw', 's', 'se'];
// Helpers only
var frameHelpers = ['nw', 'n', 'ne', 'w', 'e', 'sw', 's', 'se'];
var frameHelpersCached = new Array();
// cache tagframe width and height
var tfW = 0, tfH = 0, tfX = 0, tfY = 0;

// helpers elements
var h_nw = null, h_n = null, h_he = null, h_w = null, h_e = null, h_sw = null, h_s = null, h_se = null;
// helpers width and height (they're all judged by one 'nw' helper)
var hW = 0; var hH = 0;

// photo area bounding box - don't use in movement calculations!, see below
var paLeft = 0, paRight = 0, paTop = 0, paBottom = 0, paHeight = 0, paWidth = 0;
// same as above, but modified by some little value (currently 0)
// useful if needed to constraint frame movement inside 'photoframe'
// see usage in tagFrameStart
var paLeftH = 0, paRightH = 0, paTopH = 0, paBottomH = 0;		// same as above but minus handlers

// temporary tagframe w, h, l, t
var tW, tH, tX, tY;
// variables to store offset when dragging
var xOff = 0, yOff = 0;
// various values and elements we need to cache
var spy = null, myphoto = null, tf = null, tfi = null, tfi2 = null, tfi3 = null, photoarea = null; 
// faded picture elements
var fPh = null, fT = null, fL = null, fB = null, fR = null;
var myphotoX = 0, myphotoY = 0;

var tfIsShown = false;
var initialized = false;
var currentTagArea = null;
var current_helper = null;

function initElements()
{

	if (!initialized)
	{
		// cache page elements
		h_nw = ge('nw'); 
		h_nw.updatePos = function(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh) {
			h_nw.style.left = justx;
			h_nw.style.top  = justy;
			
		}
		h_n = ge('n'); 
		h_n.updatePos = function(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh) { 
			h_n.style.left  = plushalfw;
			h_n.style.top   = justy;
		}
		h_ne = ge('ne');
		h_ne.updatePos = function(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh) { 
			h_ne.style.left = pluswholew;
			h_ne.style.top  = justy;
		}
		h_w  = ge('w') ;                
		h_w.updatePos = function(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh) { 
			h_w.style.left  = justx;
			h_w.style.top   = plushalfh;
		}
		h_e  = ge('e') ;
		h_e.updatePos = function(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh) { 
			h_e.style.left  = pluswholew;
			h_e.style.top   = plushalfh;
		}
		h_sw = ge('sw'); 
		h_sw.updatePos = function(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh) { 
			h_sw.style.left = justx;
			h_sw.style.top  = pluswholeh;
		}
		h_s = ge('s'); 
		h_s.updatePos = function(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh) { 
			h_s.style.left  = plushalfw;
			h_s.style.top   = pluswholeh;
		}
		h_se = ge('se');
		h_se.updatePos = function(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh) { 
			h_se.style.left = pluswholew;
			h_se.style.top  = pluswholeh;
		}
		frameHelpersCached = [h_nw, h_n, h_ne, h_w, h_e, h_sw, h_s, h_se];
		if (textFileType == 'album' ) {
		
			myphoto = ge('img_src');
		} else {
			myphoto = ge('myphoto');
		}
		spy = ge('spyphoto');
		photoarea = ge('photoarea');
		
		tf = ge('tagframe2');
		tfi3 = ge('tagframe2inside3');
		hW = 10; hH = 10;

		for (var coord in tag_coords)
		{
			var x1 = tag_coords[coord][0] * myphoto.width / 100;
			var y1 = tag_coords[coord][1] * myphoto.height / 100;
			var x2 = tag_coords[coord][2] * myphoto.width / 100;
			var y2 = tag_coords[coord][3] * myphoto.height / 100;

			if (!x2)
			{
				x1 -= 83;
				x2 = x1 + 166;
			}

			if (!y2)
			{
				y1 -= 83;
				y2 = y1 + 166;
			}
	
			with(Math)
			{
				tag_coords[coord][0] = round(x1);
				tag_coords[coord][1] = round(y1);
				tag_coords[coord][2] = round(x2);
				tag_coords[coord][3] = round(y2);
			}
		}
	}

		photoarea.style.width = myphoto.width + 0 +"px";
		photoarea.style.height = myphoto.height + 0 +"px";
	
	

	fPh = ge('fadedphoto');

	myphotoX = findX(myphoto);
	myphotoY = findY(myphoto);

	// You can change values with 'H' suffix to apply contraints on frame movement
	paLeft = findX(photoarea) + 1; 			paLeftH = paLeft;
	paTop = findY(photoarea); 			paTopH = paTop;
	paWidth = photoarea.clientWidth;
	paHeight = photoarea.clientHeight;
	paRight = paLeft + paWidth; 	paRightH = paRight;
	paBottom = paTop + paHeight; 	paBottomH = paBottom;

	fPh.style.left = "0px";
	fPh.style.top = "0px";
	fPh.style.width = photoarea.style.width;
	fPh.style.height = photoarea.style.height;

	initialized = true;
}

function showBoxAt( x1, y1, x2, y2, norecount)
{

	if (tfIsShown)
		return;
		initElements();

	if (norecount == null || !norecount)
	{
		
		tfX = x1 * myphoto.width / 100;
		tfY = y1 * myphoto.height / 100;
	

		if (!x2)
		{
			tfW = 166;
			tfX -= 83;
		}
		else	
			tfW = x2 * myphoto.width / 100.0 - x1 * myphoto.width / 100.0;
			
		if (!y2)
		{
			tfH = 166;
			tfY -= 83;
		}
		else	
			tfH = y2 * myphoto.height / 100.0 - y1 * myphoto.height / 100.0;
	}
	else
	{ 
		tfX = x1;
		tfY = y1;
		tfW = x2 - x1;
		tfH = y2 - y1;
	}

	updateFramePos(Math.round(tfX), Math.round(tfY));
	updateFrameSize(Math.round(tfW), Math.round(tfH));
	updateFaded();

	var tagname = ge('tagname');

	for ( c in tag_coords ) {
		if (tag_coords[c][0]==tfX && tag_coords[c][1]==tfY && tagname ){
		if (norecount == 1) {
			if (tagname.innerHTML == tag_coords[c][5]) {
				tagname.innerHTML = tag_coords[c][5];
				tagname.style.left = tag_coords[c][0] + "px";
				tagname.style.top = tag_coords[c][3] + "px";
				tagname.style.width = tag_coords[c][2] - tag_coords[c][0] + "px";
			}
		} else {
			tagname.innerHTML = tag_coords[c][5];
			tagname.style.left = tag_coords[c][0] + "px";
			tagname.style.top = tag_coords[c][3] + "px";
			tagname.style.width = tag_coords[c][2] - tag_coords[c][0] + "px";
		}
		
			}
	}
	
	show('tagname');
	show('tagframe2');
	show('tagframe2inside3');
	if (norecount == null || !norecount) {
		show('fadedphoto');
	}
	
}

function hideBoxTags()
{
	if (tfIsShown) {
		return;
	}


	hideTags('tagframe2');
	hideTags('tagframe2inside3');
	tagname = ge('tagname');
	showAll = ge('showAll');
	hideTags('tagname');
	showAll.innerHTML = '<span id="tagname" style="display:block"></span>';

	hideTags('fadedphoto');
	hideTags('nw'); hideTags('n'); hideTags('ne');
	hideTags('w'); hideTags('e');
	hideTags('sw'); hideTags('s'); hideTags('se');
}

var selectorHtml ='';
var tagname ='';
function submitTag() {
	
	hideTags("selector_progressbar");
	show("selector_buttons");

	percentX_topleft = tfX / myphoto.width * 100;
	percentY_topleft = tfY / myphoto.height * 100;
	percentX_bottomright = (tfX + tfW) / myphoto.width * 100;
	percentY_bottomright = (tfY + tfH) / myphoto.height * 100;
	frameNewW = tfW;
	frameNewH = tfH;
	
	lastAddedTag = tag_coords.length - 1;
	if (textFileType == 'album')
	{
		var textUname = textUname;
	} else {
		var textUname = '';
	}
	params = 'id=' + pid
				+ '&oid=' + oid
				+ '&name=' + encodeURI(activePersonName)
				+ '&owner=' + owner 
				+ '&user=' + user_id 
				+ '&add=1'
				+ '&x=' + percentX_topleft
				+ '&y=' + percentY_topleft
				+ '&x2=' + percentX_bottomright
				+ '&y2=' + percentY_bottomright
				+ '&uname=' + textUname;
			

	hideTags("selector_buttons"); 

	if(params){
		if (textFileType == 'album') {
			var url = "http://www."+path_domain+"/ajax.albums.php?"+params;
		} else {
			var url = "http://www."+path_domain+"/ajax.show.php?"+params;
		}
		if (!ajaxml) {
		  if (window.XMLHttpRequest) {
		   ajaxml = new XMLHttpRequest();
		  } else if (window.ActiveXObject) {
		   ajaxml = new ActiveXObject('Microsoft.XMLHTTP');
		  }
		 } if (ajaxml) {
				  ajaxml.open('GET', url, true);
					ajaxml.onreadystatechange = function() {
						if (ajaxml.readyState == 4 && ajaxml.status == 200) {
							var content = ajaxml.responseText;
			
							if (content != 'NOT OK' && content != 'TAGGED'  && content != 'WRONG USER' ){
				
								var getTags = new Array();
								var arrTagsOnPicture = new Array();
								var tags_in_line = document.getElementById("phototags");
								var tags_on_photos = document.getElementById("show_tags");
								getTags     = explode('___', content,4);
								victim_id   = getTags[0];
								victim_name = getTags[1];
								tag_coords = deleteArrayElement(tag_coords, victim_id);
								tag_coords.push(new Array(tfX, tfY, tfX + tfW, tfY + tfH, 0, victim_name, victim_id));
								var newTag = ge(tagname);

								showBoxAt(percentX_topleft, percentY_topleft, percentX_bottomright, percentY_bottomright);
							

								tagname = ge('tagname');
								var selectorOverlay = ge('selectorOverlay');
								var selector = ge('selector');
								var intNewTag = tag_coords.length-1;
								tagname = ge('tagname');
								tagname.innerHTML = tag_coords[intNewTag][5];
								tagname.style.left = tag_coords[intNewTag][0] + "px";
								tagname.style.top = tag_coords[intNewTag][3] + "px";
								tagname.style.width = tag_coords[intNewTag][2] - tag_coords[intNewTag][0] + "px";
								tagname.style.display = 'none';
							
								selector.onmouseover = function(){
									showConfirmTag();
								}

								showFlag = 0;
								selectorHtml = selector.innerHTML;
								selector.innerHTML = '<div id=\'selectorOverlay\' style=\'display: none\' ><\/div>'+
									'<table  id="confirmOK" cellpadding=\'5\' cellspacing=\'0\'  width=\'100%\' class=\'table-brd-pink\' border=\'0\' onMouseMove=\'showConfirmTag();\' >'+
										'<tr>'+
											'<td colspan=\'2\' class="txt11 pb5"><div id=\'nameLabel\' ><div id=\'nameInner\' class=\'clrWhite txt14 bgPinkLight\'><b>'+putUsername+'</b><\/div><\/div><\/td>'+
									'<\/tr>'+
									'<tr>'+
											'<td colspan=\'2\' class="txt11 pb5"><div id=\'nameLabel\' class=\'tagperson\'>'+textExplain+' '+victim_name+'<\/td>'+
									'<\/tr>'+
										'<tr>'+
											'<td colspan=\'2\' class=\'txt11 pb5\'>'+
												'<input class="addTagBtn" type=\'button\'; onClick= "replaceSelector(selectorHtml);hideBoxTags();cancelHit()" value=\'OK\'></td>'+
										'<\/tr>'+
									'<\/table>'+
								'<\/div>';
								
								// showFlag = 0; showBoxOnMove();
								tags_in_line.innerHTML = getTags[2];
								taginst = ge('tagging_instructions');
								taginst.style.display = 'none';

							} else if (content == 'TAGGED') {
								alert(textErrorTagged);
							} 
							else if (content == 'WRONG USER') {
								alert(textErrorWrongUser);
							} else {
							alert(textError);
							
						}
					}
			}
		};ajaxml.send(null);
	}
 }

function showConfirmTag()
{
showFlag = 0;
var intNewTag = tag_coords.length-1;
tagname = ge('tagname');
tagname.innerHTML = tag_coords[intNewTag][5];
tagname.style.left = tag_coords[intNewTag][0] + "px";
tagname.style.top = tag_coords[intNewTag][3] + "px";
tagname.style.width = tag_coords[intNewTag][2] - tag_coords[intNewTag][0] + "px";
tagname.style.display = 'block';

show('tagname');
}

function replaceSelector(content)
{
	
var selector = ge('selector');
selector.style.display = 'none';
selector.innerHTML = content;
//selector.onmouseover = null;
}
function removeFromList(removeName, removeID, list) {
  return list;
}

function show_tagging_ui(photo_id, owner_id, owner_name, user_id) {
	


	pid = photo_id;
	id = owner_id;
	user = user_id;
	idname = owner_name;
	owner = owner_id;

	tagging = true;
	if (!tagging_initialized) {
		tagging_initialized = true;
	}
	ge('name').value='';
	if (textFileType == 'album') {
		ge('img_src').style.cursor = 'crosshair'; 
	//	arrows = ge('arrows_onload');
	//	arrows.style.display = 'none';
	
	} else {
		ge('myphoto').style.cursor = 'crosshair'; 
	}

	tagFrameStart();
	
}

function focusInstructions() {
	taginst = ge('tagging_instructions');
	taginst.style.display = 'block';
    window.location.hash = 'tagging_instructions';
}

function hide_tagging_ui(href) {
    tagging = false;

    tagFrameFinish();
	if (textFileType == 'album') {
		ge('img_src').style.cursor = '';

	} else {
		ge('myphoto').style.cursor = '';
	}
    hideTags('tagging_instructions_status_message');
    hideTags('tagging_instructions_default_message');
    hideTags('tagging_instructions');
    //hide these, they may be showing
    hideTags('selector');
    hideTags('tagframe');
}


function tagHit() {

	//document.write (activePersonID) 
    if ((activePersonID == -2 || activePersonName == "") && 
            ge('name').value == "") {
	
        return false;
    }
    if (activePersonID == -2) {
        activePersonName = ge('name').value; //text tagging 
            activePersonID = 0; //don't need neg flags here
    }
    lastActivePersonName = activePersonName;
	
	focusInstructions();
	

    submitTag();
	return false;
}

function resetSelector() {
  hideTags('selector'); 
  activePersonID = -2;
  activePersonName = "";
  ge('name').value = "";

	tfIsShown = false;
	hideBoxTags();
}

var allTags = '';
var showAll ='';
var showFlag = 0;

function showBoxOnMove(e)
{

	if (!showFlag) {
		showFlag = 1;
		initElements();

		var showAll = ge('showAll');
		allTags = '';
		var width = 0;

		if ( tag_coords.length > 0){
			for(var c in tag_coords)
			{
				width = tag_coords[c][2] - tag_coords[c][0];
				nickAndLink = tag_coords[c][5];
				showFlag = 1;
				allTags += '<span onmouseover=\'showBoxAt('+tag_coords[c][0]+','+tag_coords[c][1]+','+tag_coords[c][2]+','+tag_coords[c][3]+', 1);\' onmouseout=\'hideFramesOnPhoto();\'    class=\'tagname\' id=\'tagname\' style=\'left: '+tag_coords[c][0]+'px; top: '+tag_coords[c][3]+'px; width: '+width+'px; display: block;\' >'+nickAndLink+'<\/span>';
			}
//\'showBoxAt('+tag_coords[c][0]+','+tag_coords[c][1]+','+tag_coords[c][2]+','+tag_coords[c][3]+', 1);\'
			showAll.innerHTML = allTags;
		}

		if (e)
		{
			return cancelEvent(e);
		}
	}
}


function hideFramesOnPhoto(){
	
	var tagframe2 = ge('tagframe2');
	var tagframe2inside3 = ge('tagframe2inside3');
	
	tagframe2.style.display ='none';
	tagframe2inside3.style.display ='none';
}


function resetTagsOnPicture_()
{
	if (!showFlag) {
		showAll = ge('showAll');
		photoarea = ge('photoarea');
		showAll.innerHTML = '<span id="tagname" style="display:block; width:0px; left:0px; top:0px;" ></span>';
	}
}

function resetTagsOnPicture()
{
	showFlag = 0;
	setTimeout("resetTagsOnPicture_()", 100);
}

function tagFrameStart()
{
	initElements();

	removeEvent(photoarea, "mousemove");
	removeEvent(tfi3, 'mousemove');
	removeEvent(spy, 'mousemove');
	addEventTags(photoarea, 'mousedown', createFrame);
	ge('myphotolink').onclick = "return false;";
	
	for (i = 0; i < frameElements.length; i++)
	{
		addEventTags(ge(frameElements[i]), 'mousedown', frameMouseDown);
		addEventTags(ge(frameElements[i]), 'mouseup', frameMouseUp);
	}
	
	tagging = true;
}
function tagFrameFinish()
{
	mouseUp();
	removeEvent(photoarea, 'mousedown');
	ge('myphotolink').onclick = "";
	//removeEvent(ge('myphoto'), 'mouseup');
	for (i = 0; i < frameElements.length; i++)
	{
		removeEvent(ge(frameElements[i]), 'mousedown');
		removeEvent(ge(frameElements[i]), 'mouseup');
	}
	addEventTags(tfi3, "mousemove", function(e) { return cancelEvent(e); });
	addEventTags(spy, "mousemove", function(e) { return cancelEvent(e); });
	addEventTags(photoarea, "mouseover", showBoxOnMove);//mousemove

	tfIsShown = false;
	tagging = false;
	
	hideBoxTags();
}


function createFrame(e)
{

	x = mousePosX(e);
	y = mousePosY(e);

	for (i = 0; i < frameElements.length; i++)
		show(frameElements[i]);

	show('fadedphoto');
	show('selector');

	updateFrameSize(frameNewW, frameNewH);
	updateFramePos(x - frameNewW / 2 - paLeft, y - frameNewH / 2 - paTop);
	updateSelector();
	updateFaded();
	var justx = tfX + 1 + "px";
	var justy = tfY + 1 + "px";
	var plushalfw  = tfX + (tfW / 2) - (hW / 2) + 1 + "px";
	var pluswholew = tfX + tfW - hW + 1 + "px";
	var plushalfh  = tfY + (tfH / 2) - (hH / 2) + 1 + "px";
	var pluswholeh = tfY + tfH - hH + 1 + "px";
	
	for (i = 0; i < frameHelpersCached.length; i++){
		frameHelpersCached[i].updatePos(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh);
}
	tfIsShown = true;

	return cancelEvent(e);
}

function updateFrameSize(W, H)
{
	if (W >= 0)
	{
		tfW = W;
		tf.style.width = W - 10 + "px";
		tfi3.style.width = W - 12 + "px"; //12
	}

	if (H >= 0)
	{		
		tfH = H;
		tf.style.height = H - 10 + "px";
		tfi3.style.height = H - 12 + "px"; //12
	}
}

function updateFramePos(x, y)
{
	// Apply constraints
	if (x < 0)
		x = 0;
	if (x + tfW + 2> paWidth)
		x = paWidth - tfW - 2;
	if (y < 0)
		y = 0;
	if (y + tfH + 2 > paHeight)
		y = paHeight - tfH - 2;
	
	tfX = x; tfY = y;

	tf.style.left = tfX + "px";
	tf.style.top = tfY + "px";

	var justx = tfX + 1 + "px";
	var justy = tfY + 1 + "px";
	var plushalfw  = tfX + (tfW / 2) - (hW / 2) + 1 + "px";
	var pluswholew = tfX + tfW - hW + 1 + "px";
	var plushalfh  = tfY + (tfH / 2) - (hH / 2) + 1 + "px";
	var pluswholeh = tfY + tfH - hH + 1 + "px";

	if (null != current_helper) {
		current_helper.updatePos(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh);
	} 
}

function updateFaded()
{ 
	if (textFileType == 'album') {
		spy.style.left = -tfX - 7 + "px"; // + 10
		spy.style.top = -tfY - 7 + "px"; // + 0
	} else {
		spy.style.left = -tfX - 7 + "px"; // - 7
		spy.style.top = -tfY - 7 + "px"; // - 7
	}
	
}

function updateSelector()
{

	var sel = ge('selector');
	sel.style.top  = paTop + tfY + "px";
	if (tfX + tfW + 19 + sel.clientWidth < paWidth + 113) {
		sel.style.left = paLeft + tfX + tfW + 19 + "px";
	} else {
		sel.style.left = paLeft + tfX - 19 - sel.clientWidth + "px";
	}
	
}

function frameMouseDown(e)
{

	// Save values at the beginning of resize
	tX = tfX; tY = tfY;
	tW = tfW; tH = tfH;

	target = (e.srcElement) ? e.srcElement : e.target;
	targetid = target.id == '' ? target.parentNode.id : target.id;

	hideTags('selector');
	addEventTags(document.body, 'mouseup', frameMouseUp);
	addEventTags(document.body, 'dragend', frameMouseUp);

	switch(targetid)
	{
		case 'tagframe2':
		case 'tagframe2inside3':
		case 'spyphoto':
			hideHelpers();
			photoarea.style.cursor = 'move';
			xOff = tfX - mousePosX(e);
			yOff = tfY - mousePosY(e);
			assignMove(frameMove);
			
			break;
		case 'nw':
			
			hideHelpers(targetid);
			current_helper = h_nw;
			xOff = tfX + paLeft - mousePosX(e);
			yOff = tfY + paTop - mousePosY(e);
			tf.style.cursor = photoarea.style.cursor = 'nw-resize';
			assignMove(function (e) {
				x = Math.min(tfX + tfW - frameMinW, Math.max(0, mousePosX(e) - paLeft + xOff));
				y = Math.min(tfY + tfH - frameMinH, Math.max(0, mousePosY(e) - paTop + yOff));
				updateFrameSize(tW + tX - x, tH + tY - y);
				updateFramePos(x, y);
				updateFaded();
				return cancelEvent(e);

			} );
			break;
		case 'n':
			hideHelpers(targetid);
			current_helper = h_n;
			yOff = tfY + paTop - mousePosY(e);
			tf.style.cursor = photoarea.style.cursor = 'n-resize';
			assignMove(function (e) {
				y = Math.min(tfY + tfH - frameMinH, Math.max(0, mousePosY(e) - paTop + yOff));
				updateFrameSize(-1, tH + tY - y);
				updateFramePos(tfX, y);
				updateFaded();
				return cancelEvent(e);
			} );
			break;
		case 'ne':
			hideHelpers(targetid);
			current_helper = h_ne;
			xOff = tfX + paLeft + tfW - mousePosX(e);
			yOff = tfY + paTop - mousePosY(e);
			tf.style.cursor = photoarea.style.cursor = 'ne-resize';
			assignMove(function (e) {
				x = Math.min(paWidth - 2, Math.max(tfX + frameMinW, mousePosX(e) - paLeft + xOff));
				y = Math.min(tfY + tfH - frameMinH, Math.max(0, mousePosY(e) - paTop + yOff));
				updateFrameSize(x - tX, tH + (tY) - y);
				updateFramePos(tX, y);
				updateFaded();
				return cancelEvent(e);
			} );
			break;
		case 'w':
			hideHelpers(targetid);
			current_helper = h_w;
			xOff = tfX + paLeft - mousePosX(e);
			tf.style.cursor = photoarea.style.cursor = 'w-resize';
			assignMove(function (e) {
				x = Math.min(tfX + tfW - frameMinW, Math.max(0, mousePosX(e) - paLeft + xOff));
				updateFrameSize(tW + tX - x, -1);
				updateFramePos(x, tfY);
				updateFaded();
				return cancelEvent(e);
			} );
			break;
		case 'e':
			hideHelpers(targetid);
			current_helper = h_e;
			tf.style.cursor = photoarea.style.cursor = 'e-resize';
			xOff = tfX + paLeft + tfW - mousePosX(e);
			assignMove(function (e) {
				x = Math.min(paWidth - 2, Math.max(tfX + frameMinW, mousePosX(e) - paLeft + xOff));
				updateFrameSize(x - tX, -1);
				updateFramePos(tfX, tfY);
				updateFaded();
				return cancelEvent(e);
			} );
			break;
		case 'sw':
			hideHelpers(targetid);
			current_helper = h_sw;
			tf.style.cursor = photoarea.style.cursor = 'sw-resize';
			xOff = tfX + paLeft - mousePosX(e);
			yOff = tfY + paTop + tfH - mousePosY(e);
			assignMove(function (e) {
				x = Math.min(tfX + tfW - frameMinW, Math.max(0, mousePosX(e) - paLeft + xOff));
				y = Math.min(paHeight - 2, Math.max(tfY + frameMinH, mousePosY(e) - paTop + yOff));
				updateFrameSize(tX - x + tW, y - tY);
				updateFramePos(x, tY); 
				updateFaded();
				return cancelEvent(e); 
			} );
			break;
		case 's':
			hideHelpers(targetid);
			current_helper = h_s;
			tf.style.cursor = photoarea.style.cursor = 's-resize';
			yOff = tfY + paTop + tfH - mousePosY(e);
			assignMove(function (e) {
				y = Math.min(paHeight - 2, Math.max(tfY + frameMinH, mousePosY(e) - paTop + yOff));
				updateFrameSize(-1, y - tY);
				updateFramePos(tX, tY);
				updateFaded();
				return cancelEvent(e);
			} );
			break;
		case 'se':
			hideHelpers(targetid);
			current_helper = h_se;
			tf.style.cursor = photoarea.style.cursor = 'se-resize';
			xOff = tfX + paLeft + tfW - mousePosX(e);
			yOff = tfY + paTop + tfH - mousePosY(e);
			assignMove(function (e) {
				x = Math.min(paWidth - 2, Math.max(tfX + frameMinW, mousePosX(e) - paLeft + xOff));
				y = Math.min(paHeight - 2, Math.max(tfY + frameMinH, mousePosY(e) - paTop + yOff));
				updateFrameSize(x - tX, y - tY);
				updateFramePos(tX, tY); 
				updateFaded();
				return cancelEvent(e); 
			} );
			break;
			
		default:
			break;
	}

	return cancelEvent(e);
}

function hideHelpers(keep) {

	for (i = 0; i < frameHelpers.length; i++)
		if (frameHelpers[i] != keep)
			hideTags(frameHelpers[i]);
}

function showHelpers() {

	for (i = 0; i < frameHelpers.length; i++)
		show(frameHelpers[i]);
	current_helper = null;
}

function frameMouseUp(e)
{
	mouseUp();
	return cancelEvent(e);
}

var frameMove = function(e)
{
	x = mousePosX(e);
	y = mousePosY(e);
	updateFramePos(x + xOff, y + yOff);
	updateFaded();

	return cancelEvent(e);
}

function mouseUp()
{
	
	removeEvent(document.body, 'mouseup');
	removeEvent(document.body, 'dragend');
	assignMove('');
	showHelpers();
	var justx = tfX + 1 + "px";
	var justy = tfY + 1 + "px";
	var plushalfw  = tfX + (tfW / 2) - (hW / 2) + 1 + "px";
	var pluswholew = tfX + tfW - hW + 1 + "px";
	var plushalfh  = tfY + (tfH / 2) - (hH / 2) + 1 + "px";
	var pluswholeh = tfY + tfH - hH + 1 + "px";
	for (i = 0; i < frameHelpersCached.length; i++)
		frameHelpersCached[i].updatePos(justx, justy, plushalfw, pluswholew, plushalfh, pluswholeh);
	show('selector');
	updateSelector();
	tf.style.cursor = photoarea.style.cursor = '';
}

function assignMove(func)
{

	if (func != '')
	{
		addEventTags(document.body, 'mousemove', func );
		addEventTags(document.body, 'drag', func );
	}
	else	
	{
		removeEvent(document.body, 'mousemove');
		removeEvent(document.body, 'drag');
	}
}

function addEventTags(obj, event, handler) 
{
//	alert(event);
	var fn = handler;

	if (!obj.attachedEvents)
		obj.attachedEvents = new Array();

	if (obj.attachedEvents[event])
		removeEvent(obj, event);

	obj.attachedEvents[event] = fn;

	if (typeof obj.addEventListener != 'undefined') 
		obj.addEventListener(event, handler, false);
	else if (typeof obj.attachEvent != 'undefined') 
		obj.attachEvent('on' + event, handler);
}

function removeEvent(obj, event)
{

	if (!obj.attachedEvents || !obj.attachedEvents[event])
		return;

	if (typeof obj.removeEventListener != 'undefined') 
		obj.removeEventListener(event, obj.attachedEvents[event], false);
	else if (typeof obj.detachEvent != 'undefined') 
		obj.detachEvent('on' + event, obj.attachedEvents[event]);
}

function cancelEvent(e) 
{

	var e = e ? e : window.event;
	if(e.preventDefault)
		e.preventDefault();
	if(e.stopPropagation)
		e.stopPropagation();
	e.cancelBubble = true;
	e.returnValue = false;
	return false;
}

function deleteArrayElement(arrInput, strDelete)
{
	var arrOutput = new Array();
		if (typeof arrInput == 'object') {
		for (var i in arrInput) {
			var arrNewDetails = explode (',',arrInput[i]);
			if (arrNewDetails[6] != strDelete) {
				arrOutput[i] = arrInput[i];
			}
		}
		return arrOutput;
		} else {
		return arrInput;
		}
}
function del(id, user, picid, vic, owner) {

if(picid && user && id){

	if (textFileType == 'album') {
		var url = "http://www."+path_domain+"/ajax.albums.php?tag=" + id + "&user=" + user + "&picid=" + picid + "&owner=" + owner + "&act=delete_confirm";
	} else {
		var url = "http://www."+path_domain+"/ajax.show.php?tag=" + id + "&user=" + user + "&picid=" + picid + "&owner=" + owner + "&act=delete_confirm";
	}

}
if (confirm(sureDelete)) {

if (!ajaxml) {
  if (window.XMLHttpRequest) {
   ajaxml = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
   ajaxml = new ActiveXObject('Microsoft.XMLHTTP');
  }
 } if (ajaxml) {
		  ajaxml.open('GET', url, true);
			ajaxml.onreadystatechange = function() {
				if (ajaxml.readyState == 4 && ajaxml.status == 200) {
					var content = ajaxml.responseText;

					if (content != 'NOT OK'){
							var getTags = new Array();
							var tags_in_line = document.getElementById("phototags");
							var getTags = explode('___', content, 2);
							tag_coords = deleteArrayElement(tag_coords, vic);
							tags_in_line.innerHTML = getTags[0];
					} else {
						alert(textErrorDelete);
					}
				}
			};ajaxml.send(null);
	}
 }
}

 function approve(id, picid, user) {

	if (confirm(sureApprove)) {
		if(picid && user && id){
			if (textFileType == 'album') {
				var url = "http://www."+path_domain+"/ajax.albums.php?tag=" + id + "&user=" + user + "&picid=" + picid + "&act=approve_confirm";
			} else {
				var url = "http://www."+path_domain+"/ajax.show.php?tag=" + id + "&user=" + user + "&picid=" + picid + "&act=approve_confirm";
			}
	}
	if (!ajaxml) {
	  if (window.XMLHttpRequest) {
	   ajaxml = new XMLHttpRequest();
	  } else if (window.ActiveXObject) {
	   ajaxml = new ActiveXObject('Microsoft.XMLHTTP');
	  }
	 } if (ajaxml) {
			  ajaxml.open('GET', url, true);
				ajaxml.onreadystatechange = function() {
					if (ajaxml.readyState == 4 && ajaxml.status == 200) {
						var content = ajaxml.responseText;
					if (content != 'NOT OK'){
						var getTags = new Array();
						var tags_in_line = document.getElementById("phototags");
						var tags_on_photos = document.getElementById("show_tags");
						getTags = explode('___', content,2);
						tags_in_line.innerHTML = getTags[0];
					} else {
						alert(textError);
						taginst = ge('tagging_instructions');
						taginst.innerHTML = textError;
					}

				}
			};ajaxml.send(null);
		}
	}
}
function DeleteAllTags(picid, user) {

	if(picid && user){

		if (textFileType == 'album') {
			var url = "http://www."+path_domain+"/ajax.albums.php?picid=" + picid + "&user=" + user + "&act=delete_all_confirm";
		} else {
			var url = "http://www."+path_domain+"/ajax.show.php?picid=" + picid + "&user=" + user + "&act=delete_all_confirm";
		}
	}

if (confirm(sureDeleteAll)) {

if (!ajaxml) {
  if (window.XMLHttpRequest) {
   ajaxml = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
   ajaxml = new ActiveXObject('Microsoft.XMLHTTP');
  }
 } if (ajaxml) {
		  ajaxml.open('GET', url, true);
			ajaxml.onreadystatechange = function() {
				if (ajaxml.readyState == 4 && ajaxml.status == 200) {
					var content = ajaxml.responseText;
		
					if (content != 'NOT OK'){
						var getTags = new Array();
						var tags_in_line = document.getElementById("phototags");
						var getTags = explode('___', content, 2);
						
						var moderTags = explode(',', getTags[1]);
						for( var i = 0; i < moderTags.length; i++ ) {
							tag_coords = deleteArrayElement(tag_coords, moderTags[i]);
						}
						tags_in_line.innerHTML = getTags[0];
					} else {
						alert(textErrorDelete);
					}
				}
			};ajaxml.send(null);
	}
 }
}

function print_r( array, return_val ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Michael White (http://getsprink.com)
    // +   improved by: Ben Bryan
    // *     example 1: print_r(1, true);
    // *     returns 1: 1
    
    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        }
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if (obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else if(obj == null || obj == undefined) {
            str = '';
        } else {
            str = obj.toString();
        }
 
        return str;
    };
 
    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) { 
            str += pad_char; 
        };
        return str;
    };
    output = formatArray(array, 0, pad_val, pad_char);
 
    if (return_val !== true) {
        document.write("<pre>" + output + "</pre>");
        return true;
    } else {
        return output;
    }
}
