var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	deinit : function (o,msg)
	{
		if (arguments.length==2){
						o.onmousedown	= function () {alert(msg)};
		} else {
						o.onmousedown	= null;
		}
	},

	reinit : function (o)
	{
		o.onmousedown	= Drag.start;
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};

function disableBrushes(msg){
	var br=0
	while (br<brushes.length){
		var brush=document.getElementById(brushes[br]);
		Drag.deinit(brush,msg);
		br++;
	}
}

function enableBrushes(){
	var br=0
	while (br<brushes.length){
		var brush=document.getElementById(brushes[br]);
		Drag.init(brush);
		brush.onDragStart = startDrag;
		brush.onDragEnd = endDrag;
		brush.onDrag = processDrag;

		br++;
	}
}

function setZoom(){
			var msg='Please wait a sec... We are initializing the engine.';
	disableBrushes(msg);

		document.getElementById("mwait").style.display="";

		allowColoring=false;

	if (!oImg){
				return false;
	}

	if (oImg.src=='') {
		if (!_mgp_handleonload) {
			//if handling onload it is possible to pass blank image
			alert('I found your coloring image, but src on that image is not provided?\nPlease check coloring image and make sure src tag is properly set.');
		}
		return false;
	}

	var ext=oImg.src.substring(oImg.src.length-3);
	if (ext!="gif" && ext!="png" && ext!="jpg") {
		alert('Currently I can only support GIF, PNG and JPG images.\nPlease make sure your image with " id=\'coloring\' has one of those extensions.');
		return false;
	}

		
		oImg.style.display='none';

	ki=0;
	while (ki<drawing.childNodes.length){
		drawing.removeChild(drawing.childNodes[ki]);
	}

	mono.src="http://www.magiccoloringpages.com/im-provider.php?img=" + oImg.src + "&grey=1&size=" + _mgp_zoom;
	colorImage.src="http://www.magiccoloringpages.com/im-provider.php?img=" + oImg.src + "&size=" + _mgp_zoom;

	if (document.getElementById(currentBrushId))
	{
		//return previous brush
		document.getElementById(currentBrushId).style.top=0;
		document.getElementById(currentBrushId).style.left=0;
	}
}

function findPosX(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;
}

function findPosY(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 uNotify(e){
	if (!e) var e = window.event;
	
	if (e.target) targ = e.target; 
	else if (e.srcElement) targ = e.srcElement;

	if (targ.id=="printBtn") {
		return true;
	}

	var dragId=0;
	if (Drag.obj) dragId=Drag.obj.id;
	
	if (dragId!=targ.id && allowColoring && !_mgp_skip_messages){
		alert('Select the Magic Brush and drag it over the picture to start coloring');
	}
}

function isdefined(object, variable)
{
	return (typeof(eval(object)[variable]) != "undefined");
}

	function onMainResize(){
				document.getElementById("mwait").style.display="none";

		mono.width>350? canvas.style.width=mono.width + "px": canvas.style.width="350px";		
		canvas.style.height=mono.height+250;

		//center the image
		s = new String(canvas.style.width);
		s=s.replace("px","");
		mono.style.left=(s-mono.width)/2 + "px";
		drawing.style.left=(s-mono.width)/2 + "px";

		if (document.getElementById(currentBrushId)){
			//reset fix coord
			xFix=findPosX(document.getElementById(currentBrushId))-findPosX(mono);
			yFix=findPosY(document.getElementById(currentBrushId))-findPosY(mono);
		}
	}

	function startDrag(){
		var dragId=Drag.obj.id;		

		if (currentBrushId==dragId) return true;

		//return previous brush
		if (document.getElementById(currentBrushId))
		{
			document.getElementById(currentBrushId).style.top=0;
			document.getElementById(currentBrushId).style.left=0;
		}

		//save current brush id
		currentBrushId=dragId;
		currentBrushWidth=document.getElementById(currentBrushId).width;

		//calc relation of brush to the image
		xFix=findPosX(document.getElementById(currentBrushId))-findPosX(mono);
		yFix=findPosY(document.getElementById(currentBrushId))-findPosY(mono);
		iPosX=findPosX(document.getElementById(dragId));
		iPosY=findPosY(document.getElementById(dragId));
	}

	function endDrag(){		
		if (!allowColoring) return false;

		var dragId=Drag.obj.id;


		//if object was not moved - alert
		if ((iPosX==findPosX(document.getElementById(dragId))) && (iPosY==findPosY(document.getElementById(dragId))) && allowColoring)
		{
			alert('Drag me over the image');
		}
	}


	function processDrag(x, y) {
			x+=xFix;
			y+=yFix;

			var img=document.createElement('img');
			img.style.width=mono.width;
			img.style.left=0;
			img.style.top=0;
			img.style.position="absolute";
			img.src = colorImage.src;
			drawing.appendChild(img);

			if (document.all)
			{
				img.style.clip = "rect("          + 
                                 (y) +  " "  + 
								 (x + currentBrushWidth) + " " +
                                 (y + currentBrushWidth) +  " "  + 
                                 x +  ")";

			} else {
				img.style.clip = "rect("          + 
                                 (y) +  " "  + 
                                 (x) +  " "  + 
                                 (y + currentBrushWidth) +  " "  + 
                                 (x + currentBrushWidth) +  ")";
			}
	}

	function setAllowColoring(){
		allowColoring=true;
		enableBrushes();
	}

	function initHTML(){
		var toolHTML;
		toolHTML='<TABLE border="0" cellpadding="0" cellspacing="0" style="z-index: 2; position: relative; border: 1px solid ' + _mgp_bordercolor + ';" width="100%"><TR><TD style="font-size: 11px; font-family: verdana; text-align: center; background-color: ' + _mgp_bgcolor1 + '; color: black; padding: 7px; color: ' + _mgp_fntcolor1 + '"><a name="_topFocus"></a>Drag the Magic Brush over the picture to start coloring</TD></TR><TR><TD style="padding: 5px; font-size: 17px; font-family: arial; text-align: center; background-color: ' + _mgp_bgcolor2 + '; font-weight: bold; color: ' + _mgp_fntcolor2 + ';">Magic Brushes</TD></TR><TR><TD align="center" style="background-color: white; padding: 7px;"><div align="center"><img id="mwait" src="http://www.magiccoloringpages.com/images/animated_hourglass_small.gif" style="display:none;"><img alt="Brush Size: 15" id="brush15" src="http://www.magiccoloringpages.com/images/brush15.gif" style="position:relative; cursor:pointer;">&nbsp;&nbsp;<img alt="Brush Size: 25" id="brush25" src="http://www.magiccoloringpages.com/images/brush25.gif" style=" position:relative; cursor:pointer;">&nbsp;&nbsp;<img alt="Brush Size: 35" id="brush35" src="http://www.magiccoloringpages.com/images/brush35.gif" style=" position:relative; cursor:pointer;">&nbsp;&nbsp;<img alt="Brush Size: 45" id="brush45" src="http://www.magiccoloringpages.com/images/brush45.gif" style=" position:relative; cursor:pointer;">&nbsp;&nbsp;<img alt="Brush Size: 55" id="brush55" src="http://www.magiccoloringpages.com/images/brush55.gif" style=" position:relative; cursor:pointer;"></div></TD></TR><TR><td><table cellpadding="0" cellspacing="0" width="100%"><tr><TD style="padding: 5px; font-size: 14px; font-family: arial; text-align: center; background-color: ' + _mgp_bgcolor2 + '; font-weight: bold; color: ' + _mgp_fntcolor2 + ';">Zoom / Resize Picture</TD><td style="font-size: 14px; font-family: arial; text-align: center; background-color: ' + _mgp_bgcolor2 + '; font-weight: bold; color: ' + _mgp_fntcolor2 + ';"><input id="printBtn" type="button" value="Print Picture" onclick="runPrint();" style="' + _mgp_btncss + '"></td></TR><TR><TD align="center" style="background-color: white;"><a href="#_topFocus" onclick="_mgp_zoom=1;setZoom();" style="padding: 3px; font-size: 13px;">1x</a><a href="#_topFocus" onclick="_mgp_zoom=1.5;setZoom();" style="padding: 3px; font-size: 13px;">1&#189;x</a><a href="#_topFocus" onclick="_mgp_zoom=2; setZoom();" style="padding: 3px; font-size: 13px;">2x</a><a href="#_topFocus" onclick="_mgp_zoom=2.5;setZoom();" style="padding: 3px;font-size: 13px;">2&#189;x</a><a href="#_topFocus" onclick="_mgp_zoom=3; setZoom();" style="padding: 3px;font-size: 13px;">3x</a><a href="#_topFocus" onclick="_mgp_zoom=3.5; setZoom();" style="padding: 3px;font-size: 13px;">3&#189;x</a><a href="#_topFocus" onclick="_mgp_zoom=4; setZoom();" style="padding: 3px;font-size: 13px;">4x</a></TD><td style="font-size: 13px; background-color: white;">&nbsp;</td></TR></table></td></tr><TR><TD style="font-size: 9px; font-family: verdana; text-align: right; color: black; padding: 3px; margin: 0px; height: 30px; vertical-align: bottom;">Powered by <a style="text-decoration: none;" href="http://www.magiccoloringpages.com/">Magic Coloring Pages</a></TD></TR><TR></TABLE>';

		var canvasHTML;
		canvasHTML='<DIV id="canvas" style="z-index: 5; position: relative; top:0; left: 0;">';
		canvasHTML+=toolHTML;
		canvasHTML+='<div style="position: absolute; left:0; top:220; z-index: 1;" id="drawing"></div>';
		canvasHTML+='<img id="mono" src="" style="z-index: 0; position: absolute; left:0; top:220;" onload="onMainResize();">';
		//canvasHTML+='<iframe style="position: absolute; left:500; top:0; z-index: 0;" id="ndisplay" name="ndisplay" border="1" frameborder="1" width="100" height="700" src="" border="0"></iframe>';
		canvasHTML+='</DIV>';
	
		document.write(canvasHTML);
	}

	function runPrint(){
		var printWindow=window.open("http://www.magiccoloringpages.com/print-picture.php?mono=" + escape(mono.src) + "&a=" + window.location,"_printWindow","width=" + (mono.width+100) + ",height=" + (mono.height + 100));	
	}

	if (!isdefined(window, "_mgp_bgcolor1")) _mgp_bgcolor1="#eeeeee";
	if (!isdefined(window, "_mgp_bgcolor2")) _mgp_bgcolor2="#dddddd";
	if (!isdefined(window, "_mgp_fntcolor1")) _mgp_fntcolor1="#000000";
	if (!isdefined(window, "_mgp_fntcolor2")) _mgp_fntcolor2="#880000";
	if (!isdefined(window, "_mgp_bordercolor")) _mgp_bordercolor="#880000";
	if (!isdefined(window, "_mgp_zoom")) _mgp_zoom=1;
	if (!isdefined(window, "_mgp_handleonload")) _mgp_handleonload=false;
	if (!isdefined(window, "_mgp_btncss")) _mgp_btncss="";
	if (!isdefined(window, "_mgp_skip_messages")) _mgp_skip_messages=false;
	

	document.onmousedown=uNotify;

	initHTML();

	//original image
	var oImg=document.getElementById("coloring");

	if (!oImg){
			alert("Now I will try to find the largest image on the page and use it for coloring.\n\nIf you would like to specify the image, simply add \" id='coloring' \" to the image HTML tag and refresh the page to start coloring. Your image HTML tag should look this way\n<img src='http://www.yourdomain.com/image.jpg' id='coloring'> .");

		var dLocation=new String(document.location);
		var maxSize=0;
		if (document.images){
						for (var iCount=0;iCount<document.images.length;iCount++){
				if (document.images[iCount].width*document.images[iCount].height>maxSize) maxSize=document.images[iCount].width*document.images[iCount].height;
			}
				
						for (var iCount=0;iCount<document.images.length;iCount++){
				if (document.images[iCount].width*document.images[iCount].height==maxSize){
					oImg=document.images[iCount];
				}
			}
		}
	}

	if (!oImg){
		alert("You have to specify the image you would like to use for the coloring page.\n\nSimply add \" id='coloring' \" to the image HTML tag and refresh the page to start coloring. Your image HTML tag should look this way\n<img src='http://www.yourdomain.com/image.jpg' id='coloring'> .");
	} else {		
		if (_mgp_handleonload) oImg.onload=setZoom;
	}

	
	var mono = document.getElementById("mono");	
	var drawing = document.getElementById("drawing");
	var canvas = document.getElementById("canvas");

	//new color image cache
	var colorImage=document.createElement('img');
	colorImage.onload=setAllowColoring;	

	//init brushes
	var xFix=0;
	var YFix=0;
	var currentBrushId;
	var currentBrushWidth=0;
	var allowColoring=false;

	var brushes=new Array("brush15","brush25","brush35","brush45","brush55");
	
	//default zoom
	setZoom();		