var CropperEngine = new function() {
    var imgRoot = "http://www.fotoplex.ru/jimages"
    var mainpic = null

    this.textName = "text";

    var self = this

    var crop={
    	nc1:{'w':8,'h':8},
    	nc2:{'w':8,'h':8},
    	active:false,
    	draged:null,
    	na:null,
    	ncell:[3,6,9,12,1,2,4,8]
    }
    var grid={
    	active:false,
    	obj:null,
        btn:null
    }

    //Object.prototype.between=function(vmin,vmax){try{return (this<vmin)?vmin:(this>vmax)?vmax:this}catch(e){return this}}

    function between(x, vmin, vmax) {try{return (x<vmin)?vmin:(x>vmax)?vmax:x}catch(e){return x}}

    function getNa(){
    	var o=mainpic
    	crop.na={'l':o.offsetLeft-8,'t':o.offsetTop-8,'w':o.offsetWidth+16,'h':o.offsetHeight+16}
    	while(o=o.offsetParent){
    		crop.na.l+=o.offsetLeft
    		crop.na.t+=o.offsetTop
    	}
    }

    function reposition(){
    	getNa()
    	for(var i=0;i<crop.ncell.length;i++){
    		document.getElementById('t'+crop.ncell[i]).pos(crop.ncell[i])
    	}
    	grid.obj.pos()
    }

    this.turnGrid = function(){
        if(!grid.active && !crop.active) {
        	crop.active=!crop.active
        	reposition()
        }
    	grid.active=!grid.active
    	grid.obj.pos()
    }

    this.turnCrop = function(){
        if(grid.active && crop.active) {
        	grid.active=!grid.active
        	grid.obj.pos()
        }
    	crop.active=!crop.active
    	reposition()
    }
    /*
    this.waitObj(id,evFunc){
    	var obj=document.getElementById(id)
    	if(obj)window[evFunc]()
    	else setTimeout("waitObj('"+id+"','"+evFunc+"')",100)	
    }
    */

    this.init = function(picId){
    	mainpic=document.getElementById(picId)
    	var mmove = function(e){
    		if(crop.draged!=null){
    			var e=e||event
    			var x=(e.x||e.clientX)+document.body.scrollLeft
    			var y=(e.y||e.clientY)+document.body.scrollTop
    			var side=crop.draged.side

    			//if(side&1) crop.nc1.h=(y-crop.na.t).between(8,crop.na.h-crop.nc2.h-8)
    			//if(side&4) crop.nc2.h=(crop.na.t+crop.na.h-y).between(8,crop.na.h-crop.nc1.h-8)
    			//if(side&2) crop.nc1.w=(x-crop.na.l).between(8,crop.na.w-crop.nc2.w-8)
    			//if(side&8) crop.nc2.w=(crop.na.l+crop.na.w-x).between(8,crop.na.w-crop.nc1.w-8)

    			if(side&1) crop.nc1.h=between(y-crop.na.t, 8, crop.na.h-crop.nc2.h-8)
    			if(side&4) crop.nc2.h=between(crop.na.t+crop.na.h-y, 8,crop.na.h-crop.nc1.h-8)
    			if(side&2) crop.nc1.w=between(x-crop.na.l, 8,crop.na.w-crop.nc2.w-8)
    			if(side&8) crop.nc2.w=between(crop.na.l+crop.na.w-x, 8,crop.na.w-crop.nc1.w-8)
    			reposition()
                if(e.preventDefault) e.preventDefault()
                e.cancelBubble = true
    		}
            return false
    	}
        // document.body.onmousemove = mmove
    	// window.onresize=function(){reposition()}
    	// ! document.body.onmousedown=document.body.ondragstart=function(){return false}
    	// document.body.onmouseup=function(){crop.draged=null}
    	//document.body.ondragend=document.body.onmouseup
    	// document.body.ondrag=document.body.onmousemove	

        addHandler(window, "resize", reposition)
        addHandler(document.body, "mouseup", function(){crop.draged=null})
        addHandler(document.body, "dragend", function(){crop.draged=null})
        addHandler(document.body, "drag", mmove)
        addHandler(document.body, "mousemove", mmove)

        addHandler(document.body, "mousedown", function(e) {
                if(!crop.draged) return
    			var e=e||event
                if(e.preventDefault) e.preventDefault()
                e.cancelBubble = true
                return false
            })
        addHandler(document.body, "dragstart", function(e) {
                if(!crop.draged) return
    			var e=e||event
                if(e.preventDefault) e.preventDefault()
                e.cancelBubble = true
                return false
            })
    	prepareGrid()
    	prepareCrop()
    }


    this.setCrop = function(left, top, right, bottom)
    {
        if(!crop.active) self.turnCrop();
        if(!window.resizeRatio) window.resizeRatio = 1;

    	crop.nc1.w = Math.round(left/window.resizeRatio)+8;
    	crop.nc1.h = Math.round(top/window.resizeRatio)+8;
    	crop.nc2.w =  Math.round(right/window.resizeRatio)+8;
    	crop.nc2.h = Math.round(bottom/window.resizeRatio)+8;
    	window.scrollTo(0,0);
        reposition()
    }


    function prepareGrid(){
    	grid.obj=document.createElement('table')
    	grid.obj.display=grid.active?'':'none'
    	grid.obj.cellSpacing=grid.obj.cellPadding=0
    	grid.obj.style.position='absolute'
    	grid.obj.style.border='solid 1px red'
    	for(var i=0;i<3;i++){
    		grid.obj.insertRow(i)
            var ws = ["38%", "24%", "38%"]
            var hs = ["38%", "24%", "38%"]
            //if(window.navigator.userAgent.toLowerCase().indexOf('opera') != -1) hs = ["36%", "24%", "40%"]
    		for(var j=0;j<3;j++){
    			var c=grid.obj.rows[i].insertCell(j)
                c.valign = "middle";
                c.align  = "center";
    			c.style.fontSize="1px";
    			c.style.border='solid 1px red';
    			c.style.width = ws[j];
    			c.style.height= hs[i];
                c.innerHTML = '&nbsp;' //'<img src="'+imgRoot+'/d.gif" width="1" height="1">'
    		}
    	}
    	grid.obj.pos=function(){
    		this.style.display='none'
    		this.style.display=grid.active?'':'none'
    		this.style.left=crop.na.l+((crop.active)?crop.nc1.w:8)
    		this.style.top=crop.na.t+((crop.active)?crop.nc1.h:8)
    		this.style.width=crop.na.w-((crop.active)?(crop.nc1.w+crop.nc2.w):16)
    		this.style.height=crop.na.h-((crop.active)?(crop.nc1.h+crop.nc2.h):16)
    	}
    	document.body.appendChild(grid.obj)
    }
    function prepareCrop(){ //Создать полупрозрачные слои
    	for(var i=0;i<crop.ncell.length;i++){
    		var dg=crop.ncell[i]
    		var t=document.createElement('table')
    		t.cellSpacing=t.cellPadding=0
    		t.id='t'+dg
    		t.className='cropperMatt '+t.id
    		t.pos=function(dg){
    			if(crop.active){
    				this.style.display=''
    				this.style.left=(dg&2)?crop.na.l:(dg&8)?crop.na.l+crop.na.w-crop.nc2.w:crop.na.l+crop.nc1.w
    				this.style.top=(dg&1)?crop.na.t:(dg&4)?crop.na.t+crop.na.h-crop.nc2.h:crop.na.t+crop.nc1.h
    				this.style.width=(dg&2)?crop.nc1.w:(dg&8)?crop.nc2.w:crop.na.w-crop.nc1.w-crop.nc2.w
    				this.style.height=(dg&1)?crop.nc1.h:(dg&4)?crop.nc2.h:crop.na.h-crop.nc1.h-crop.nc2.h
    			}else{
    				this.style.display='none'
    			}
    		}
    		var c=t.insertRow(0).insertCell(0)
    		c.style.textAlign=(dg&2)?'right':(dg&8)?'left':'center'
    		c.style.verticalAlign=(dg&1)?'bottom':(dg&4)?'top':'middle'
    		c.appendChild(createMarker(dg))
    		document.body.appendChild(t)
    	}
    	reposition()
    }
    function createMarker(side){
    	var m=document.createElement('img')
    	m.side=side
    	try{m.style.cursor='pointer'}catch(e){m.style.cursor='hand'}
    	//m.onmousedown=function(){crop.draged=this}
        addHandler(m, "mousedown", function(){crop.draged=this }.bind(m))
    	m.height=m.width=8
    	m.src=imgRoot+'/crop.gif'
    	return m
    }
}()


//waitObj('mainpic','init')