/**
 * ImagePanel.js
 * extending panel.js
 * @author grantd
 */

/*Extending panel.js------------------*/
axe.ImagePanel = function(inits){
	axe.ImagePanel.superclass.constructor.call(this, inits);
	
	this.DOM = inits.DOM;
	
	this.filename = inits["filename"];
	this.addImage(this.filename, this);
	this.url = this.image.src;
	//this.zoomButton = new axe.panelButton("images/icon_zoom_in.png","zoomIn",this.header.HTML,this.zoomIn,this);
this.zoomButton = new axe.panelButton("images/icon_zoom_in.png","zoomIn",this);
this.header.HTML.insertBefore(this.zoomButton.HTML,this.closeButton.HTML);
YAHOO.util.Event.addListener(this.zoomButton.HTML,"click",this.zoomIn,this);
	//this.zoomOutButton = new axe.panelButton("images/icon_zoom_out.png","zoomOut",this.header.HTML, this.zoomOut, this);
this.zoomOutButton = new axe.panelButton("images/icon_zoom_out.png","zoomOut",this);
this.header.HTML.insertBefore(this.zoomOutButton.HTML,this.closeButton.HTML);
YAHOO.util.Event.addListener(this.zoomOutButton.HTML,"click",this.zoomOut,this);
//	this.boxButton = new axe.panelButton("images/icon_rectangle.png","box",this.header.HTML,this.drawBox,this);
	
	this.boxButton = new axe.panelButton("images/icon_rectangle.png","box",this);
this.header.HTML.insertBefore(this.boxButton.HTML,this.closeButton.HTML);
YAHOO.util.Event.addListener(this.boxButton.HTML,"click",this.drawBox,this);
	
this.polyButton = new axe.panelButton("images/icon_polygon.png","polygon",this);
this.header.HTML.insertBefore(this.polyButton.HTML,this.closeButton.HTML);
YAHOO.util.Event.addListener(this.polyButton.HTML,"click",this.drawPoly,this);


	this.viewButton = new axe.panelButton("./theme/images/icon_xml.png","view",this);
this.header.HTML.insertBefore(this.viewButton.HTML,this.closeButton.HTML);
YAHOO.util.Event.addListener(this.viewButton.HTML,"click",this.showXML,this);

	this.tagArea = new axe.tagArea(this);
	
	
	this.loadXML();
	
	this.sidebar = this.desktop.sideBar;
		
	sideInits = {panel: this, sidebar: this.desktop.sideBar};
	
	this.sidePanel = new axe.ImageSidePanel(sideInits);
	this.desktop.sideBar.addPanel(this.sidePanel);
	
	
	
	this.shapeType = 'off';
	this.getTags();
}
YAHOO.lang.extend(axe.ImagePanel,axe.panel);

axe.ImagePanel.prototype.showDOM=function() {
	//attach id
	this.DOM.documentElement.setAttribute("id", this.id);
	/*
	 * Attributes for graphic: 
	 * height, width, url, scale
	 */
	this.DOM.documentElement.setAttribute("height", trueValue(this.image.HTML.height, this.image.scale));
	this.DOM.documentElement.setAttribute("width", trueValue(this.image.HTML.width, this.image.scale));
	
}

axe.ImagePanel.prototype.showXML=function(e,obj){
	
 	xmlout = window.open('','xmlout',''); 
	htmlVal = obj.constructXML(obj,"HTML");
	teiVal = obj.constructXML(obj,"TEI");
	html = "<HTML><HEAD><SCRIPT LANGUAGE='javascript'>function fillTextArea(val){ta = document.getElementById('ta');if (val=='HTML'){ta.value='"+htmlVal+"';}else{ta.value='"+teiVal+"';}}</SCRIPT></HEAD><BODY><SELECT onchange='fillTextArea(this.value)'><OPTION value='TEI'>TEI</OPTION><OPTION value='HTML'>HTML</OPTION></SELECT><textarea id='ta' rows=500 cols=200>"+teiVal+"</textarea></BODY></HTML>";
	
	xmlout.document.write(html);
	xmlout.document.close();

} 
axe.ImagePanel.prototype.constructXML=function(obj,type){

	//type indicates TEI or HTML
	
	switch (type) {
		case 'TEI':
			tag = "<facsimile>";
			for (i in obj.image.imageRegions) { //output all boxes
				tag += "<graphic mimeType=\"image/jpg\" height=\"" + obj.image.HTML.height + "\" width=\"" + obj.image.HTML.width + "\" url=\"\"/>";
				tag += "<zone ulx=\"" + obj.image.imageRegions[i].HTML.style.left + "\" uly=\"" + obj.image.imageRegions[i].HTML.style.top + "\"" +
				"lrx=\"" +
				obj.image.imageRegions[i].HTML.style.width +
				"\" lry=\"" +
				obj.image.imageRegions[i].HTML.style.height +
				"\">";
				tag += "<desc>" + i + "</desc>";
				
			}
			tag += "</facsimile>";
		
			
			
			
			break;
		case 'HTML':
			tag = "<img usemap=\"#" + obj.image.id + "\"/>";
			coords = "";
			tag += "<map id=\"" + obj.image.id + "\" name=\"" + obj.image.id + "\">";
			for (i in obj.image.imageRegions) { //output all boxes
				temp = obj.image.imageRegions[i];
				tag += "<area shape=\"rect\" coords=\"" + temp.HTML.style.left + "," + temp.HTML.style.top + "," + temp.HTML.style.width + "," + temp.HTML.style.height + "\" href=\"#\" target=\"_blank\" alt=\"" + i + "\" />"
			}
			
		
			for (i in obj.image.areas) { //output all boxes
				temp = obj.image.areas[i];
				for (j in temp.nodes) {
					node = temp.nodes[j];
					coords += trueValue(node.dot.HTML.style.left) + "," + trueValue(node.dot.HTML.style.top)+",";
										
				}
				tag += "<area shape=\"poly\" coords=\"" + coords.substring(0,coords.length-1) + "\" href=\"#\" target=\"_blank\" alt=\"" + i + "\" />"
			}
			tag += "</map>";
		
			break;
			
	}
	return tag;

}
axe.ImagePanel.prototype.drawBox = function(e,args){
	
	if(args.shapeType=="box") { //reclicking the button to turn off tagger
		args.shapeType = "off";
		//desktop.objects[this.previousSibling.id].image.src = "images/icon_rectangle.png";
		desktop.objects[this.id].image.src = "images/icon_rectangle.png";
	} else {
		args.shapeType = "box";
		desktop.objects[this.id].image.src = "images/icon_rectangle_selected.png";
		desktop.objects[this.nextSibling.id].image.src = "images/icon_polygon.png";
	}
}

axe.ImagePanel.prototype.drawPoly = function(e,args){
	
	if (args.shapeType == "poly") { //reclicking the button to turn off tagger
		args.shapeType = "off";
		
		//desktop.objects[this.previousSibling.id].image.src = "images/icon_rectangle.png";
		desktop.objects[this.id].image.src = "images/icon_polygon.png";
	}
	else {
		args.shapeType = "poly";
		desktop.objects[this.previousSibling.id].image.src = "images/icon_rectangle.png";
		desktop.objects[this.id].image.src = "images/icon_polygon_selected.png";
	}
}
axe.ImagePanel.prototype.showPoly = function (e, obj, hide) {
	if(!(hide)) {
		//Show polygons
		for(i in this.image.dotArray) {
			dot = this.image.dotArray[i];
			dot.dot.HTML.style.display = "block";
		}
	} else {
		//hide polygons
	}
}
axe.ImagePanel.prototype.handleTextClick= function(obj){
	this.focus();
	
}
axe.ImagePanel.prototype.handleTextChange=function(obj){
	id = this.parentNode.parentNode.id;
	
	panel = desktop.objects[id];
	panel.image.change(this.value);
}



axe.ImagePanel.prototype.showText = function(e,panel){
	if (panel) {
		if (panel.content.HTML.firstChild.nodeName.toLowerCase() == "img") {
			if (panel.pages[panel.curPage]) {
				pageid = panel.pages[panel.curPage].getAttribute("start");
				pageid = pageid.substring(1);
			}
			
			pageTop = getElementWithAttValue(panel.xml, "pb", "xml:id", pageid);
			
			nextEle = pageTop.nextSibling;
			
			txt = "";
			while (!(nextEle.nodeName == "pb")) {
				if (nextEle.nodeName.toLowerCase() == "#text") {
				
				thistxt = nextEle.nodeValue;
			}
				txt = txt + thistxt;
				if (nextEle.firstChild) {
					nextEle = nextEle.firstChild;
				}
				else if (nextEle.nextSibling) {
						nextEle = nextEle.nextSibling;
					}
					else if(nextEle.parentNode.nextSibling){
						nextEle = nextEle.parentNode.nextSibling;
					}
					else{
						return null;
					}
				
			}
			
			panel.clearContents();
			txtDiv = document.createElement("div");
			txtDiv.className = "txtDiv";
			
			txtDiv.innerHTML = txt;
			panel.content.HTML.appendChild(txtDiv);
		}
		else {
		
			panel.showPage(panel.curPage)
		}
	}
	
}
axe.ImagePanel.prototype.transparency = function(obj){
	
	pan = this.HTML;
	percent = obj/90;
	percent = 1-percent;
	
	
	
	
	
		pan.style.filter = "alpha(opacity="+percent*100+");"
		// + ((o - .1) * 100) + ")";
		pan.style.opacity = percent;
		//parseInt(o) - .1;
	
	
	
}
//-----------Coords----------------------
//retrieve boxes
axe.ImagePanel.prototype.getTags=function() {
	var response = phpCall('./database/retrievecoords.php', '', 'GET');
	if (response != "") {
	
		arr = response.split(';');
		for (x = 0; x < arr.length; x++) {
		
			temp = arr[x].split('-');
			if (temp[0] == 'box') {
				id = temp[0];
				coords = temp[1].split(',');
				
				ulx = coords[0];
				uly = coords[1];
				lrx = coords[2];
				lry = coords[3];
				
				box = new axe.imageRegion(this.image, [ulx, uly, lrx, lry], id);
			} else if(temp[0] == "poly") {
				id = temp[1];
				coords = temp[2].split(',');
				node = new Object();
				for(c=0;c<coords.length;c++) {
					p0 = parseInt(coords[c]) + parseInt(YAHOO.util.Dom.getX(this.image.HTML));
					p1 = parseInt(coords[++c]) + parseInt(YAHOO.util.Dom.getY(this.image.HTML));
					
					//startNode = (this.image.curArea != null) ? false : true;
					if (this.image.curArea) {
						node = new axe.node(this.image, [p0, p1, 10, 10], false);
						node.area = this.image.curArea;
						this.image.curArea.nodes.push(node);
					} else {
						node = new axe.node(this.image, [p0, p1, 10, 10], true);
						node.dot.HTML.className = "firstNode";
						this.image.curArea = new axe.area(this.image, "poly");
						this.image.curArea.nodes.push(node);
						this.image.areas.push(this.image.curArea);
						node.area = this.image.curArea;
					}
					
				}
				this.image.curArea.completeShape(this.image.curArea);
			}
		}
	}
}
//-----------Zoom----------------------
axe.ImagePanel.prototype.zoomIn = function(e, thing){
	obj = thing.content.HTML;
	if (obj.firstChild) {
	
		zObj = obj.firstChild;
		newW = (parseInt(YAHOO.util.Dom.getStyle(zObj, "width")) * 2);
		
		newH = (parseInt(YAHOO.util.Dom.getStyle(zObj, "height")) * 2);
		
		YAHOO.util.Dom.setStyle(zObj, "width", newW + "px");
		YAHOO.util.Dom.setStyle(zObj, "height", newH + "px");
		
	}
	thing.image.scale += 2;
	//resize box elements
	for (b in thing.image.imageRegions) {
		box = thing.image.imageRegions[b];
		bimage = document.getElementById(thing.image.id);
		bimageW = parseInt(YAHOO.util.Dom.getStyle(bimage, "width"));
		bimageWOld = bimageW / 1.5;
		ratio = bimageW / bimageWOld;
		
		
		bW = (parseInt(YAHOO.util.Dom.getStyle(box.HTML, "width")) * 2);
		bH = (parseInt(YAHOO.util.Dom.getStyle(box.HTML, "height")) * 2);
		YAHOO.util.Dom.setStyle(box.HTML, "width", bW + "px");
		YAHOO.util.Dom.setStyle(box.HTML, "height", bH + "px");
		bTop = YAHOO.util.Dom.getStyle(box.HTML, "top");
		bLeft = YAHOO.util.Dom.getStyle(box.HTML, "left");
		bTop = parseInt(bTop) * 2;
		bLeft = parseInt(bLeft) * 2;
		
		
		YAHOO.util.Dom.setStyle(box.HTML, "left", bLeft + "px");
		YAHOO.util.Dom.setStyle(box.HTML, "top", bTop + "px");
		/*
arr = {
			ulx: box.HTML.style.left,
			uly: box.HTML.style.top,
			lrx: box.HTML.style.width,
			lry: box.HTML.style.height,
			isetID: box.isetID
		};
		getCoords(thing.image, "overwrite", "box", arr);
*/
	}
	
	
	node = null;
	line = null;
	//resize nodes
	for (n in thing.image.areas) {
		node = thing.image.areas[n];
		node.clearLines(node);
		/*
		 for(l in node.lines) {
		 
		 lin.remove();
		 }
		 */
		lastDot = null;
		child = null;
		//alert(thing.image.scale + "  " + thing.image.HTML.width + "  " + thing.image.HTML.height);
		for (f in node.nodes) {
			child = node.nodes[f];
			newx = (parseInt(child.dot.HTML.style.left) * thing.image.HTML.width) / ((thing.image.HTML.width) / 2);
			newx = parseInt(newx);
			newy = (parseInt(child.dot.HTML.style.top) * thing.image.HTML.height) / ((thing.image.HTML.height) / 2);
			newy = parseInt(newy);
			//newx = Math.ceil((parseInt(child.dot.HTML.style.left)*2));
			//newy = Math.ceil((parseInt(child.dot.HTML.style.top)*2));
			
			
			
			child.dot.HTML.style.left = newx + "px";
			child.dot.HTML.style.top = newy + "px";
			
			if (thing.image.scale > 6) {
				child.dot.x = Math.abs(YAHOO.util.Dom.getX(child.dot.HTML.id));
				child.dot.y = Math.abs(YAHOO.util.Dom.getX(child.dot.HTML.id));
			} else {
				child.dot.setX(YAHOO.util.Dom.getX(child.dot.HTML.id));
				child.dot.setY(YAHOO.util.Dom.getY(child.dot.HTML.id));
			}
			//child.dot.setX((YAHOO.util.Dom.getX(child.dot.HTML.id) * thing.image.HTML.width) / ((thing.image.HTML.width) / 2));
			//child.dot.setY((YAHOO.util.Dom.getY(child.dot.HTML.id) * thing.image.HTML.height) / ((thing.image.HTML.height) / 2));
			
	
			/*
			 if(lastDot) {
			 line = new axe.line(thing.image, lastDot.dot.x, lastDot.dot.y,
			 child.dot.x, child.dot.y);
			 line.drawLine();
			 node.lines.push(line);
			 }
			 lastDot=child;
			 
			 }
			 line = new axe.line(thing.image, node.nodes[0].dot.x, node.nodes[0].dot.y,
			 child.dot.x, child.dot.y);
			 line.drawLine();
			 node.lines.push(line);
			 
			 getCoords(thing.image, 'overwrite', 'poly', node.nodes);
			 */
		}
		
		node.completeShape(node);
	}
}	
axe.ImagePanel.prototype.zoomOut = function(e, thing){
	obj = thing.content.HTML;
	if (obj.firstChild) {
		zObj = obj.firstChild;
		newW = (parseInt(YAHOO.util.Dom.getStyle(zObj, "width")) / 2);
		
		newH = (parseInt(YAHOO.util.Dom.getStyle(zObj, "height")) / 2);
		
		YAHOO.util.Dom.setStyle(zObj, "width", newW + "px");
		YAHOO.util.Dom.setStyle(zObj, "height", newH + "px");
	}
	thing.image.scale -= 2;
	//resize box elements
	boxes = YAHOO.util.Dom.getElementsByClassName("box", "div");
	
	for (b in thing.image.imageRegions) {
		box = thing.image.imageRegions[b];
		bimage = document.getElementById(thing.image.id);
		bimageW = YAHOO.util.Dom.getStyle(bimage, "width");
		bimageWOld = bimageW / 2;
		
		bW = (parseInt(YAHOO.util.Dom.getStyle(box.HTML, "width")) / 2);
		bH = (parseInt(YAHOO.util.Dom.getStyle(box.HTML, "height")) / 2);
		YAHOO.util.Dom.setStyle(box.HTML, "width", bW + "px");
		YAHOO.util.Dom.setStyle(box.HTML, "height", bH + "px");
		bTop = YAHOO.util.Dom.getStyle(box.HTML, "top");
		bLeft = YAHOO.util.Dom.getStyle(box.HTML, "left");
		bTop = parseInt(bTop) / 2;
		bLeft = parseInt(bLeft) / 2;
		
		YAHOO.util.Dom.setStyle(box.HTML, "left", bLeft + "px");
		YAHOO.util.Dom.setStyle(box.HTML, "top", bTop + "px");
		/*
arr = {
			ulx: box.HTML.style.left,
			uly: box.HTML.style.top,
			lrx: box.HTML.style.width,
			lry: box.HTML.style.height,
			isetID: box.isetID
		};
		getCoords(thing.image, "overwrite", "box", arr);
*/
	}
	
	//resize nodes
	
	node = null;
	for (n in thing.image.areas) {
		node = thing.image.areas[n];
		//node.dot.x = (node.dot.x)/2;
		//node.dot.y = (node.dot.y)/2;
		node.clearLines(node);
		/*
		 for (l in node.lines) {
		 lin = node.lines[l].remove();
		 
		 }
		 */
		lastDot = null;
		child = null;
		
		for (f in node.nodes) {
			child = node.nodes[f];
			
			newx = (parseInt(child.dot.HTML.style.left) * thing.image.HTML.width) / ((thing.image.HTML.width) * 2);
			newx = parseInt(newx);
			newy = (parseInt(child.dot.HTML.style.top) * thing.image.HTML.height) / ((thing.image.HTML.height) * 2);
			newy = parseInt(newy);
			
			child.dot.HTML.style.left = newx + "px";
			child.dot.HTML.style.top = newy + "px";
			
			
			if (thing.image.scale > 6) {
				child.dot.x = Math.abs(YAHOO.util.Dom.getX(child.dot.HTML.id)) + (thing.image.HTML.width * 2);
				child.dot.y = Math.abs(YAHOO.util.Dom.getX(child.dot.HTML.id)) + (thing.image.HTML.height * 2);
			} else {
				child.dot.setX(YAHOO.util.Dom.getX(child.dot.HTML.id));
				child.dot.setY(YAHOO.util.Dom.getY(child.dot.HTML.id));
			}
			
			/*
child.dot.setX(parseInt(YAHOO.util.Dom.getX(child.dot.HTML.id)));
			child.dot.setY(parseInt(YAHOO.util.Dom.getY(child.dot.HTML.id)));
*/
			
			/*
			 if (lastDot) {
			
			 //parseInt(lastDot.dot.x); parseInt(lastDot.dot.y); parseInt(child.dot.x); parseInt(child.dot.y);
			
			 line = new axe.line(thing.image, parseInt(lastDot.dot.x), parseInt(lastDot.dot.y), parseInt(child.dot.x), parseInt(child.dot.y));
			
			 line.drawLine();
			
			 node.lines.push(line);
			
			 }
			
			 lastDot = child;
			
			 }
			
			 //parseInt(node.nodes[0].dot.x); parseInt(node.nodes[0].dot.y); parseInt(child.dot.x); parseInt(child.dot.y);
			
			 line = new axe.line(thing.image, parseInt(node.nodes[0].dot.x), parseInt(node.nodes[0].dot.y), parseInt(child.dot.x), parseInt(child.dot.y));
			
			 line.drawLine();
			
			 node.lines.push(line);
			
			 getCoords(thing.image, 'overwrite', 'poly', node.nodes);
			
			 */
			
		}
		node.completeShape(node);
	}
}
axe.ImagePanel.prototype.addZone=function(area, coords){
	dom = this.DOM;
	zone = dom.createElement("zone");
	zone.setAttribute("xml:id", area.id);
	zone.setAttribute("coords", coords);
	dom.documentElement.appendChild(zone);
	
	return zone;
}

axe.ImagePanel.prototype.clearContents= function(){
	contentDiv = this.content.HTML;
	kids = contentDiv.childNodes;
	if (kids){}
	for (i=0;i<kids.length;i++){
		contentDiv.removeChild(kids[i]);
	}
	
}
axe.ImagePanel.prototype.addImage = function(src, obj){
	
	this.image = new axe.image(src,obj);
	this.setContent(this.image.HTML);
	
}

axe.ImagePanel.prototype.setContent = function(contentObj){
	this.clearContents();
	this.content.HTML.appendChild(contentObj);
   YAHOO.util.Event.onAvailable(contentObj,this.adjustContentSize());
}

axe.ImagePanel.prototype.adjustContentSize = function(){
	contentObj = this.content.HTML.firstChild;
	YAHOO.util.Dom.setStyle(contentObj, "width", YAHOO.util.Dom.getStyle(this.HTML, "width"));
}

axe.ImagePanel.prototype.loadXML = function(){
				
				//retrieve coordinates (if any)
				
				
				
				//Clear Previous Coordinates
				/*if (crds = YAHOO.util.Dom.getElementsByClassName("node", "div")) {
					crds2 = YAHOO.util.Dom.getElementsByClassName("firstNode", "div");
					for (i = 0; i < crds.length; i++) {
					
						crds[i].parentNode.removeChild(crds[i]);
						if (crds2[i]) {
							crds2[i].parentNode.removeChild(crds2[i]);
						}
					}
					
				}*/
				//Load Coordinates
				/*if (phpCall('../db_API/session_handler.php', '?mode=getProject', 'GET') != "empty") {
					var pparams = '?mode=coords&curPage='+this.curPage;
					var coords = phpCall('../db_API/sessionhandler.php', pparams, 'GET');
					var arr = coords.split(';');
					
					for (i = 0; i < arr.length; i++) {
						if (arr[i] != "") {
							coord = arr[i];
							arr2 = coord.split(',');
							points = new Array(arr2[0], arr2[1]);
							node = new axe.node(this.image, points);
							node.dot.HTML.style.left = points[0] + "px";
							node.dot.HTML.style.top = points[1] + "px";
							node.dot.HTML.className = "firstNode";
							node.dot.HTML.style.display = "none";
							
							this.image.dotArray.push(node);
							for (k = 2; k < arr2.length; k++) {
								points = new Array(arr2[k], arr2[++k]);
								node2 = new axe.node(this.image, points);
								
								node2.dot.HTML.style.left = points[0] + "px";
								node2.dot.HTML.style.top = points[1] + "px";
								node2.dot.HTML.style.display = "none";
								node.image.dotArray.push(node2);
								
							}
						}
					}
				}*/
				
				
}

//using panel.js
/*
axe.ImagePanel.prototype.handleOnAvailable = function(panel){
	
draggable = new YAHOO.util.DD(this.id);
	draggable.setHandleElId(this.id+"_handle");

	
	//Yahoo YUI code for making a bounding area
	
	YAHOO.example.DDRegion = function(id, sGroup, config) {
        this.cont = config.cont;
        YAHOO.example.DDRegion.superclass.constructor.apply(this, arguments);
    };

    YAHOO.extend(YAHOO.example.DDRegion, YAHOO.util.DD, {
        cont: null,
        init: function() {
            //Call the parent's init method
            YAHOO.example.DDRegion.superclass.init.apply(this, arguments);
            this.initConstraints();

            YAHOO.util.Event.on(window, 'resize', function() {
                this.initConstraints();
            }, this, true);
        },
        initConstraints: function() {
            //Get the top, right, bottom and left positions
            var region = YAHOO.util.Dom.getRegion(this.cont);

            //Get the element we are working on
            var el = this.getEl();

            //Get the xy position of it
            var xy = YAHOO.util.Dom.getXY(el);

            //Get the width and height
            var width = parseInt(YAHOO.util.Dom.getStyle(el, 'width'), 10);
            var height = parseInt(YAHOO.util.Dom.getStyle(el, 'height'), 10);

            //Set left to x minus left
            var left = xy[0] - region.left;

            //Set right to right minus x minus width
            var right = region.right - xy[0] - width;

            //Set top to y minus top
            var top = xy[1] - region.top;

            //Set bottom to bottom minus y minus height
            var bottom = region.bottom - xy[1] - height;

            //Set the constraints based on the above calculations
            this.setXConstraint(left, right);
            this.setYConstraint(top, bottom);
        }
    });
	
	draggable = new YAHOO.example.DDRegion(this.id, '', {cont: this.loc});
	
// Yahoo code for making a resizable panel

	this.yResize = new YAHOO.util.Resize(this.id, {
                handles: ['br'],
				
                autoRatio: false,
                minWidth: 300,
                minHeight: 100
               
            });

            // Setup resize handler to update the size of the Panel's body element
            // whenever the size of the 'resizablepanel' DIV changes
      this.yResize.on('resize', function(args) {
				
				
                var panelHeight = args.height;
					          		
                var headerHeight = this.firstChild.offsetHeight;	 

				if (this.childNodes[2]){
                var footerHeight = this.childNodes[2].offsetHeight; // Content + Padding + Border
				
				}
				else
				{
					footertHeight=0;
				}
				
				
                var bodyHeight = (panelHeight - headerHeight - footerHeight);
				
              //  var bodyContentHeight = (IE_QUIRKS) ? bodyHeight : bodyHeight - PANEL_BODY_PADDING;
 var bodyContentHeight =  bodyHeight;

                YAHOO.util.Dom.setStyle(this.childNodes[1], 'height', bodyContentHeight + 'px');
		

            }, this, true);

		//this.yPanel.show(); 
		
			 
}
*/

				

axe.ImagePanel.prototype.type = "image";


//------PanelHeader--------------
/*axe.ImagePanelHeader = function(panel){
	this.panel = panel;
	
	this.HTML = document.createElement("div");
	this.HTML.className = "hd";
	this.HTML.id = this.panel.id+"_handle";
	this.panel.HTML.appendChild(this.HTML);
	//YAHOO.util.Event.addListener(this.HTML, "mouseup", showX);
	//  Add panelHeader contents here
}*/
axe.ImageSidePanel = function(inits) {

	axe.ImageSidePanel.superclass.constructor.call(this,inits);
	//this.panel = panel;
	//this.sidebar = sidebar;
	this.tagArray = new Array();
	
	//this.HTML = document.createElement("div");
	
	//display url
	this.HTML.appendChild(document.createTextNode(this.panel.url));
	
	
	
	this.container = document.createElement("div");
	this.container.className = "sideContainer";
	
	this.HTML.appendChild(this.container);	
	
	
	
}
YAHOO.lang.extend(axe.ImageSidePanel,axe.SidePanel);

axe.ImageSidePanel.prototype.refreshView=function(obj){
	this.container.parentNode.removeChild(this.container);
	this.container = document.createElement("div");
	this.container.className = "sideContainer";
	
	this.HTML.appendChild(this.container);
	
	if(!obj.overwrite) {
		
		this.tagArray.push(obj);
	} else {
		//erase previous tag and replace with updated info
		for(i in this.tagArray) {
			this.tagArray[i] = (this.tagArray[i].id == obj.id) ? obj: this.tagArray[i];
		}
	}
	
	for (tag in this.tagArray) {
		
		space = document.createElement("div");
		space.id = this.tagArray[tag].id + "tag";
		
		this.displayContent(this, this.tagArray[tag], space);
		
		//timeTag = document.createElement("div");
		//timeTag.appendChild(document.createTextNode(this.tagArray[tag].getAttribute("xml:id") + " : " + time));
		
		
		/*
YAHOO.util.Event.addListener(space.id,"click",function(e,obj){
				
				linkObj = {obj: obj}
				axe.tagClicked.fire(linkObj);
				
			}, obj.area.xml);
*/
		
		this.container.appendChild(space);
		
		
	}
	
}

axe.ImageSidePanel.prototype.displayContent=function(image, obj, loc) {
	var main = document.createElement("div");
	main.id = YAHOO.util.Dom.generateId(main, "imageItem");
	var tag = "<ul>";
	var type = obj["type"];
	
	for(i in obj) {
		tag += (obj[i] != true) ? "<li><span class=\"sidePanelAttribute\">"+i+": </span>"+obj[i]+"</li>" : "";
	}
	tag += "</ul>";
	main.innerHTML = tag;
	loc.appendChild(main);
	
	if (!obj.saved) {
		link = new axe.link({
			loc: main,
			obj: obj,
			panel: image.panel,
			sidepanel: image.panel.sidePanel,
			sidePanelObject: main,
			type: type
		});
	}
	YAHOO.util.Event.addListener(main, "mouseover", this.highlight, obj);
	YAHOO.util.Event.addListener(main, "mouseout", this.unhighlight, obj);
	
	YAHOO.util.Event.addListener(main, "click", this.handleClick, {
		obj: obj,
		desktop: image.panel.desktop,
		panel: image.panel,
		main: main,
		sidepanel: this,
		type: type
	});
}
axe.ImageSidePanel.prototype.highlight=function(e, obj) {
	if (obj["type"] == "box") {
		fobject = document.getElementById(obj["id"]);
		//fobject.style.background = "#00FF00";
		fobject.style.background = "#bfe5ff";
		//make transparent color background in all browsers
		fobject.style.opacity = "0.6";
		fobject.style.mozOpacity = "0.6";
		fobject.style.filter = "alpha(opacity=60)";
		fobject.style.khtmlOpacity = "0.6";
	} else {
		area = obj["area"];
		for(x in area.nodes) {
			fobject = area.nodes[x].dot.HTML;
			fobject.className = "dotHighlight";
		}
	}
}
axe.ImageSidePanel.prototype.unhighlight=function(e, obj) {
	if (obj["type"] == "box") {
		fobject = document.getElementById(obj["id"]);
		fobject.style.background = "transparent";
	} else {
		area = obj["area"];
		for (x in area.nodes) {
			fobject = area.nodes[x].dot.HTML;
			fobject.className = (x == 0) ? "firstNode" : "node";
		}
	}
}
axe.ImageSidePanel.prototype.saveItem=function(args) {
	obj = args["obj"];
	type = args["type"];
	
	
	//update database
	if (type == "box") {
		var coords = "" + trueValue(obj["ulx"], this.panel.image.scale) + "," +
		trueValue(obj["uly"], this.panel.image.scale) +
		"," +
		trueValue(obj["lrx"], this.panel.image.scale) +
		"," +
		trueValue(obj["lry"], this.panel.image.scale);
		var height = trueValue(this.panel.image.HTML.height, this.panel.image.scale);
		var width = trueValue(this.panel.image.HTML.width, this.panel.image.scale);
		var temp = new Object();
		for (i in this.panel.image.imageRegions) {
			if (this.panel.image.imageRegions[i].id == obj.id) {
				temp = this.panel.image.imageRegions[i];
			}
		}
		
		//generate a random number between 1 and 1000
		temp.dbID = (!temp.dbID) ? Math.floor(Math.random() * 1000 + 1) : temp.dbID;
		params = '?coords='+coords+'&id='+temp.dbID+'&width='
				+width+'&height='+height+'&type=box';
		response = phpCall('./database/coords.php', params, 'GET');
		
	} else if(type == "poly") {
		var coords = "";
			for (i in obj.area.nodes) {
				node = obj.area.nodes[i];
				coords += trueValue(node.dot.HTML.style.left, image.scale) + "," + trueValue(node.dot.HTML.style.top, image.scale) + "-";
				
			}
			//generate a random number between 1 and 1000
			//dbID = Math.floor(Math.random() * 1000 + 1);
			coords += coords.substring(0, coords.length-1);
			
			var width = trueValue(image.HTML.width, image.scale);
			var height = trueValue(image.HTML.height, image.scale);
			
			//generate a random number between 1 and 1000
			dbID = (!obj.id) ? Math.floor(Math.random() * 1000 + 1) : obj.id;
			params = '?coords='+coords+'&id='+dbID+'&width='
				+width+'&height='+height+'&type=box';
			response = phpCall('./database/coords.php', params, 'GET');
	
			
	}
			obj.saved = true;
			obj.XML = this.panel.DOM.createElement("facsimile");
			obj.XML.setAttribute("xml:id",obj.id);
			axe.tagCreated.fire({obj: obj.XML});
			
	
}
axe.ImageSidePanel.prototype.removeItem=function(args) {
	obj = args["obj"];
	main = args["main"];
	type = args["type"];
	//remove the element from the tagArray
	for(i in this.tagArray) {
		if(this.tagArray[i].id == obj.id) {
			this.tagArray.splice(i, 1);
		}
	}
	
	if (type == "box") {
		//remove from panel
		for (i in this.panel.image.imageRegions) {
			if (this.panel.image.imageRegions[i].id == obj.id) {
				if (this.panel.image.imageRegions[i].dbID) { //in database
					params = '?id=' + this.panel.image.imageRegions[i].dbID;
					response = phpCall('./database/deletecoord.php', params, 'GET');
				}
				this.panel.image.imageRegions.splice(i, 1);
			}
		}
	} else if(type == "poly") {
		
		for(x in this.panel.image.areas) {
			area = this.panel.image.areas[x];
			
			if(obj.id == area.dbID) {
				curr = this.panel.image.curArea;
				area.clearLines(area);
				for(c in area.nodes) {
					node = area.nodes[c];
					
					node.dot.HTML.parentNode.removeChild(node.dot.HTML);
				}
				
				if (curr != obj.id) {
					
					this.panel.image.curArea = curr;
				}
				this.panel.image.areas.splice(x, 1);
				area = null;
				
			}
			
		}
	}
	main.parentNode.removeChild(main);
	
}
axe.ImageSidePanel.prototype.handleClick=function(e, args) {
	//display menu for linking together tags
	obj = args["obj"];
	desktop = args["desktop"];
	panel=args["panel"];
	main = args["main"];
	sidepanel = args["sidepanel"];
	type = args["type"];
	
	/*
if (obj.link == null) {
		fobject = document.getElementById(obj.id + "tag");
		
		obj.link = new axe.link({
			loc: fobject,
			obj: obj,
			panel: panel,
			sidepanel: sidepanel,
			sidePanelObject: main,
			type: type
		});
		
	}
*/

	if (obj.saved){
	
		axe.tagClicked.fire({obj: obj.XML});
		
	}
	

	//axe.sidePanelClick.fire({obj: obj, desktop: desktop, link: this.link});
}