// generated on Sun Oct  4 10:36:19 2009
window.onerror=function(message,url,line){prompt("A Javascript error occurred!\n "+message+"\n at line "+line, url);return false;};var PXN8=PXN8 || {};PXN8.server=document.location.protocol+"/"+"/"+document.location.host;PXN8.root="/pixenate/";PXN8.basename="pxn8.pl";PXN8.replaceOnSave=true;PXN8.aspectRatio={width:0 , height:0};PXN8.position={x: "-", y: "-"};PXN8.style={};PXN8.style.notSelected={opacity: 0.33,color: "black"};PXN8.style.resizeHandles ={color: "white",size: 6,smallsize: 4,oldsize: -1};PXN8.ON_IMAGE_LOAD="ON_IMAGE_LOAD";PXN8.ON_IMAGE_CHANGE="ON_IMAGE_CHANGE";PXN8.BEFORE_IMAGE_CHANGE="BEFORE_IMAGE_CHANGE";PXN8.ON_ZOOM_CHANGE="ON_ZOOM_CHANGE";PXN8.ON_SELECTION_CHANGE="ON_SELECTION_CHANGE";PXN8.ON_SELECTION_COMPLETE="ON_SELECTION_COMPLETE";PXN8.ON_IMAGE_ERROR="ON_IMAGE_ERROR";PXN8.listener={listenersByType:{}};PXN8.listener.listenersByType[PXN8.ON_ZOOM_CHANGE]=[];PXN8.listener.listenersByType[PXN8.ON_SELECTION_CHANGE]=[];PXN8.listener.listenersByType[PXN8.ON_IMAGE_CHANGE]=[];PXN8.listener.listenersByType[PXN8.ON_IMAGE_ERROR]=[];PXN8.listener.add=function (eventType,callback){var self=PXN8.listener;var callbacks=self.listenersByType[eventType];var found=false;if (!callbacks){callbacks=[];self.listenersByType[eventType]=callbacks;}for (var i=0;i < callbacks.length; i++){if (callbacks[i]==callback){found=true;break;}}if (!found){callbacks.push (callback);}return callback;};PXN8.listener.remove=function (eventType, callback){var self=PXN8.listener;var callbacks=self.listenersByType[eventType];if (!callbacks) return;for (var i=0;i < callbacks.length; i++){if (callbacks[i]==callback){callbacks.splice(i,1);i--;}}};PXN8.listener.onceOnly=function (eventType,callback){var self=PXN8.listener;callback.onceOnly=true;return self.add(eventType, callback);};PXN8.opNumber=0;PXN8.maxOpNumber=0;PXN8.response={status: "",image: "",errorCode: 0,errorMessage: ""};PXN8.updating=false;PXN8.resizelimit={width: 1600,height: 1200};PXN8.imagesBySrc={};PXN8.sx=0;PXN8.sy=0;PXN8.ex=0;PXN8.ey=0;PXN8.initialize=function( param ){PXN8.ready=false;var _=PXN8.dom;var image_src;var paramType=typeof param;if (paramType=='string'){image_src=param;}else{image_src=param.url;}PXN8.priv.createSelectionRect();var canvas=PXN8.initializeCanvas();var imgContainer=_.id("pxn8_image_container");if (!imgContainer){imgContainer=_.ac(canvas,_.ce("div",{id: "pxn8_image_container"}));if (document.all){imgContainer.style.backgroundColor="black";}}if(navigator.userAgent.indexOf("Opera")!=-1){PXN8.style.notSelected.color="transparent";}try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}var rects=["pxn8_top_rect","pxn8_bottom_rect","pxn8_left_rect","pxn8_right_rect","pxn8_topleft_rect","pxn8_topright_rect","pxn8_bottomleft_rect","pxn8_bottomright_rect"];for (var i=0;i < rects.length; i++){var rect=_.id(rects[i]);if (!rect){rect=_.ac(canvas,_.ce("div",{id: rects[i]}));}rect.style.fontSize="0px";if (!rect.style.backgroundColor){rect.style.backgroundColor=PXN8.style.notSelected.color;}rect.style.position="absolute";if (!rect.style.opacity){_.opacity(rect,PXN8.style.notSelected.opacity);}rect.style.top="0px";rect.style.left="0px";rect.style.width="0px";rect.style.height="0px";rect.style.display="none";rect.style.zIndex=1;var antshz="url("+PXN8.server+PXN8.root+"/images/ants_hr.gif)";var antsvt="url("+PXN8.server+PXN8.root+"/images/ants_vt.gif)";if (rects[i]=="pxn8_top_rect"){rect.style.backgroundImage=antshz;rect.style.backgroundPosition="bottom left";rect.style.backgroundRepeat="repeat-x";}if (rects[i]=="pxn8_bottom_rect"){rect.style.backgroundImage=antshz;rect.style.backgroundPosition="top left";rect.style.backgroundRepeat="repeat-x";}if (rects[i]=="pxn8_left_rect"){rect.style.backgroundImage=antsvt;rect.style.backgroundPosition="top right";rect.style.backgroundRepeat="repeat-y";}if (rects[i]=="pxn8_right_rect"){rect.style.backgroundImage=antsvt;rect.style.backgroundPosition="top left";rect.style.backgroundRepeat="repeat-y";}}PXN8.image.location=image_src;PXN8.opNumber=0;PXN8.maxOpNumber=0;PXN8.history=new Array();PXN8.offsets=[1];var fetchOp={operation: "fetch",url: PXN8.image.location};fetchOp.pxn8root=PXN8.root;if (paramType=='object'){for (var i in param){fetchOp[i]=param[i];}}PXN8.history.push(fetchOp);if (PXN8.replaceOnSave){fetchOp.random=PXN8.randomHex();}var gotAbsoluteImageSrc=false;var getAbsoluteImageSrc=function(){if (gotAbsoluteImageSrc){getAbsoluteImageSrc=function(){};return;}gotAbsoluteImageSrc=true;var fetchOp=PXN8.getOperation(0);var theImage=document.getElementById("pxn8_image");fetchOp.url=theImage.src;PXN8.ready=true;};var pxn8image=_.id("pxn8_image");var onImageLoad=function(){var _=PXN8.dom;var pxn8image=_.id("pxn8_image");PXN8.image.width=pxn8image.width;PXN8.image.height=pxn8image.height;PXN8.priv.addImageToHistory(pxn8image.src);PXN8.show.size();getAbsoluteImageSrc();};if (!pxn8image){var innerHTML='<img id="pxn8_image" border="0" src="'+PXN8.image.location+'"/>';try {imgContainer.innerHTML=innerHTML;}catch (e){alert("An error occurred while adding the <img> tag to the page.\n"+"This is most likely because the pxn8_canvas DIV has been added to an incorrect element (<table> or <p>).\n"+"The error message reported was: "+e.message);PXN8.dom.ac(imgContainer,PXN8.dom.ce("img",{id: "pxn8_image", src: PXN8.image.location}));}pxn8image=_.id("pxn8_image");}else
{var imgContainer=_.cl("pxn8_image_container");var innerHTML='<img id="pxn8_image" border="0" src="'+PXN8.image.location+'"/>';try {imgContainer.innerHTML=innerHTML;}catch(e){alert("An error occurred while adding the <img> tag to the page.\n"+"This is most likely because the pxn8_canvas DIV has been added to an incorrect element (<table> or <p>).\n"+"The error message reported was: "+e.message);PXN8.dom.ac(imgContainer,PXN8.dom.ce("img",{id: "pxn8_image", src: PXN8.image.location}));}pxn8image=_.id("pxn8_image");}pxn8image.onload=onImageLoad;PXN8.event.removeListener(pxn8image,"load",PXN8.imageLoadNotifier);PXN8.event.addListener(pxn8image,"load",PXN8.imageLoadNotifier);};PXN8.select=function (startX, startY, width, height){var self=PXN8;if (typeof startX=="object"){var sel=startX;startY=sel.top;width=sel.width;height=sel.height;startX=sel.left;}self.sx=startX;self.sy=startY;self.ex=self.sx+width;self.ey=self.sy+height;if (PXN8.select.constrainToImageBounds==true){if (self.sx < 0) self.sx=0;if (self.sy < 0) self.sy=0;if (self.ex > PXN8.image.width){self.ex=PXN8.image.width;self.sx=self.ex-width;}if (self.ey > PXN8.image.height){self.ey=PXN8.image.height;self.sy=self.ey-height;}}self.position.x=startX;self.position.y=startY;var selection=self.getSelection();self.listener.notify(PXN8.ON_SELECTION_CHANGE,selection);};PXN8.select.constrainToImageBounds=true;PXN8.select.disabler=function(eventType,selection){if (selection.width > 0 || selection.height > 0){PXN8.unselect();return;}};PXN8.select.enable=function(enabled,unselect){var canvas=document.getElementById("pxn8_canvas");if (enabled){PXN8.listener.remove(PXN8.ON_SELECTION_CHANGE,PXN8.select.disabler);}else{if (unselect){PXN8.unselect();}PXN8.listener.add(PXN8.ON_SELECTION_CHANGE,PXN8.select.disabler);}};PXN8.select.defaultListener=function(eventType,selection){var _=PXN8.dom;var self=PXN8;var theImg=_.id("pxn8_image");var selectRect=_.id("pxn8_select_rect");var leftRect=_.id("pxn8_left_rect");var rightRect=_.id("pxn8_right_rect");var topRect=_.id("pxn8_top_rect");var bottomRect=_.id("pxn8_bottom_rect");var topleftRect=_.id("pxn8_topleft_rect");var toprightRect=_.id("pxn8_topright_rect");var bottomleftRect=_.id("pxn8_bottomleft_rect");var bottomrightRect=_.id("pxn8_bottomright_rect");PXN8.show.position();PXN8.show.selection();if ((eventType==PXN8.ON_SELECTION_CHANGE && selection==null) ||
eventType==PXN8.ON_ZOOM_CHANGE){selection=self.getSelection();}if (selection.width <=0 && selection.height <= 0 ){selectRect.style.display="none";leftRect.style.display="none";rightRect.style.display="none";topRect.style.display="none";bottomRect.style.display="none";topleftRect.style.display="none";toprightRect.style.display="none";bottomleftRect.style.display="none";bottomrightRect.style.display="none";return;}var zoom=PXN8.zoom.value();var sel={};for (var i in selection){if (typeof selection[i] != "function"){sel[i]=Math.floor(selection[i]*zoom);}}var bh=theImg.height-(sel.top+sel.height);if (bh < 0){bh=0;}bh=bh+"px";var bt=sel.top+sel.height+"px";var th=sel.top+"px";var ll="0px";var lw=sel.left+"px";var rw=(theImg.width-(sel.left+sel.width));if (rw < 0){rw=0;}rw=rw+"px";var rl=sel.left+sel.width+"px";topleftRect.style.display="block";topleftRect.style.top="0px";topleftRect.style.left=ll;topleftRect.style.width=lw;topleftRect.style.height=th;leftRect.style.display="block";leftRect.style.top=sel.top+"px";leftRect.style.left=ll;leftRect.style.width=lw;leftRect.style.height=sel.height+"px";bottomleftRect.style.display="block";bottomleftRect.style.top=bt;bottomleftRect.style.left=ll;bottomleftRect.style.width=lw;bottomleftRect.style.height=bh;topRect.style.display="block";topRect.style.top="0px";topRect.style.left=sel.left+"px";topRect.style.width=sel.width+"px";topRect.style.height=th;selectRect.style.top=sel.top+"px";selectRect.style.left=sel.left+"px";selectRect.style.width=sel.width+"px";selectRect.style.height=sel.height+"px";selectRect.style.display="block";selectRect.style.zIndex=100;bottomRect.style.display="block";bottomRect.style.top=bt;bottomRect.style.left=sel.left+"px";bottomRect.style.width=sel.width+"px";bottomRect.style.height=bh;toprightRect.style.display="block";toprightRect.style.top="0px";toprightRect.style.left=rl;toprightRect.style.width=rw;toprightRect.style.height=th;rightRect.style.display="block";rightRect.style.top=sel.top+"px";rightRect.style.left=rl;rightRect.style.width=rw;rightRect.style.height=sel.height+"px";bottomrightRect.style.display="block";bottomrightRect.style.top=bt;bottomrightRect.style.left=rl;bottomrightRect.style.width=rw;bottomrightRect.style.height=bh;};PXN8.listener.add(PXN8.ON_SELECTION_CHANGE,PXN8.select.defaultListener);PXN8.listener.add(PXN8.ON_ZOOM_CHANGE,PXN8.select.defaultListener);PXN8.getSelection=function(){var rect={};var self=PXN8;rect.width=self.ex>self.sx?self.ex-self.sx:self.sx-self.ex;rect.height=self.ey>self.sy?self.ey-self.sy:self.sy-self.ey;rect.left=self.ex>self.sx?self.sx:self.ex;rect.top=self.ey>self.sy?self.sy:self.ey;return rect;};PXN8.selectByRatio=function(ratio,override){var _=PXN8.dom;var self=PXN8;if (typeof ratio != "string"){alert("Ratio must be expressed as a string e.g. '4x6'");return;}if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.selectByRatio(ratio,override);});return;}var ih=PXN8.image.height;var iw=PXN8.image.width;var sepIndex=ratio.indexOf("x");if (sepIndex != -1){var rw=parseFloat(ratio.substring(0,sepIndex));var rh=parseFloat(ratio.substring(sepIndex+1));if (override){PXN8.aspectRatio.width=rw;PXN8.aspectRatio.height=rh;}else{if (iw > ih){if (rw > rh){PXN8.aspectRatio.width=rw;PXN8.aspectRatio.height=rh;}else{PXN8.aspectRatio.width=rh;PXN8.aspectRatio.height=rw;}}else{if (rw > rh){PXN8.aspectRatio.width=rh;PXN8.aspectRatio.height=rw;}else{PXN8.aspectRatio.width=rw;PXN8.aspectRatio.height=rh;}}}rw=PXN8.aspectRatio.width;rh=PXN8.aspectRatio.height;}else{PXN8.aspectRatio.width=0;PXN8.aspectRatio.height=0;PXN8.resize.enable(["n","s","e","w"],true);return;}PXN8.resize.enable(["n","s","e","w"],false);var left=0;var top=0;var width=0;var height=0;var fitWidth=function(){width=iw;height=Math.round(width / rw*rh);top=Math.round( (ih /2 )-(height / 2));};var fitHeight=function(){height=ih;width=Math.round(height / rh*rw);left=Math.round((iw / 2)-(width /2));};if (iw > ih){if ((iw / ih) > (rw / rh)){fitHeight();}else{fitWidth();}}else{if ((ih / iw) > (rh / rw)){fitWidth();}else{fitHeight();}}self.select(left,top,width,height);};PXN8.rotateSelection=function(){if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.rotateSelection();});return;}var sel=PXN8.getSelection();var imgSize=PXN8.getImageSize();var cx=sel.left+(sel.width / 2);var cy=sel.top+(sel.height / 2);if (sel.width > imgSize.height){sel.height=sel.height*(imgSize.height / sel.width);sel.width=imgSize.height;}if (sel.height > imgSize.width){sel.width=sel.width*(imgSize.width / sel.height);sel.height=imgSize.width;}PXN8.select (cx-sel.height/2, cy-sel.width /2, sel.height, sel.width);var temp=PXN8.aspectRatio.width;PXN8.aspectRatio.width=PXN8.aspectRatio.height;PXN8.aspectRatio.height=temp;PXN8.snapToAspectRatio();};PXN8.selectAll=function(){if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.selectAll();});return;}PXN8.select( 0, 0, PXN8.image.width, PXN8.image.height);};PXN8.unselect=function (){PXN8.select( 0, 0, 0,0);};PXN8.getUncompressedImage=function(){if (PXN8.responses[PXN8.opNumber]){return PXN8.responses[PXN8.opNumber].uncompressed;} else {return false;}};PXN8.listener.notify=function(eventType,source){var self=PXN8.listener;var listeners=self.listenersByType[eventType];if (listeners){for (var i=0; i < listeners.length; i++){var listener=listeners[i];if (listener != null){listener(eventType,source);if (listener.onceOnly){PXN8.listener.remove(eventType,listener);i--;}}}}};PXN8.imageLoadHousekeeping=function(eventType,theImage){var _=PXN8.dom;theImage=_.id("pxn8_buffered_image");if (theImage==null){theImage=_.id("pxn8_image");}if (PXN8.log){PXN8.log.trace("image "+theImage.src+" has loaded");}PXN8.image.width=theImage.width;PXN8.image.height=theImage.height;var iw=PXN8.image.width;var ih=PXN8.image.height;var zoomFactor=PXN8.zoom.value();theImage.width=iw*zoomFactor;theImage.height=ih*zoomFactor;_.ac(_.cl("pxn8_image_container"),theImage);theImage.id="pxn8_image";PXN8.show.size();PXN8.priv.addImageToHistory(theImage.src);var selection=PXN8.getSelection();if (selection.width > iw ||
selection.left > iw ||
selection.height > ih ||
selection.top > ih){PXN8.unselect();}else{var moved=false;if (selection.left+selection.width > iw){selection.left=iw-selection.width;moved=true;}if (selection.top+selection.height > ih){selection.top=ih-selection.height;moved=true;}if (moved){PXN8.select(selection);}}PXN8.listener.notify(PXN8.ON_SELECTION_CHANGE,selection);PXN8.imagesBySrc[theImage.src]=true;PXN8.listener.notify(PXN8.ON_IMAGE_CHANGE);var timer=_.id("pxn8_timer");if (timer){timer.style.display="none";}return theImage;};PXN8.listener.add(PXN8.ON_IMAGE_LOAD,PXN8.imageLoadHousekeeping);if (typeof log4javascript != "undefined"){PXN8.log=log4javascript.getDefaultLogger();}else{PXN8.log=false;}PXN8.getOperation=function(i){if (i > PXN8.opNumber){return null;}return PXN8.history[i];};PXN8.getUserOperation=function(index){var self=PXN8;var result=null;var lastIndex=0;for (var i=0;i < index; i++){lastIndex += self.offsets[i];}return self.history[lastIndex];};PXN8.getScript=function(){var self=PXN8;var result=new Array();var lastIndex=0;for (var i=0;i <= self.opNumber; i++){lastIndex += self.offsets[i];}for (var i=0;i < lastIndex; i++){var original=self.history[i];var duplicate={};for (var j in original){duplicate[j]=original[j];}result.push(duplicate);}return result;};PXN8.isUpdating=function(){return PXN8.updating;};PXN8.curry=function(func,object){return function(){return func(object);};};PXN8.prepareForSubmit=function(msg){var _=PXN8.dom;if (!msg){msg=PXN8.strings["UPDATING"];}var timer=_.id("pxn8_timer");if (!timer){timer=_.ce("div",{id: "pxn8_timer"});_.ac(timer,_.tx(msg));var canvas=_.id("pxn8_canvas");_.ac(canvas,timer);}if (timer){_.ac(_.cl(timer),_.tx(msg));timer.style.display='block';var theImage=_.id("pxn8_image");var imagePos=_.ep(theImage);timer.style.width=Math.max(200,theImage.width)+"px";}PXN8.updating=true;};PXN8.scrolledPoint=function (x,y){var result={"x":x,"y":y};var canvas=document.getElementById("pxn8_canvas");if (canvas.parentNode.id=="pxn8_scroller"){var scroller=document.getElementById("pxn8_scroller");result.x += scroller.scrollLeft;result.y += scroller.scrollTop;}return result;};PXN8.getWindowScrollPoint=function(){var scrOfX=0, scrOfY=0;if( typeof( window.pageYOffset )=='number' ) {scrOfY=window.pageYOffset;scrOfX=window.pageXOffset;} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {scrOfY=document.body.scrollTop;scrOfX=document.body.scrollLeft;} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {scrOfY=document.documentElement.scrollTop;scrOfX=document.documentElement.scrollLeft;}return {"x": scrOfX, "y": scrOfY };};PXN8.createPin=function (pinId,imgSrc){var pinElement=document.createElement("img");pinElement.id=pinId;pinElement.className="pin";pinElement.src=imgSrc;pinElement.style.position="absolute";return pinElement;};PXN8.mousePointToElementPoint=function(mx,my){var _=PXN8.dom;var result={};var canvas=_.id("pxn8_canvas");var imageBounds=_.eb(canvas);var scrolledPoint=PXN8.scrolledPoint(mx,my);var zoom=PXN8.zoom.value();result.x=Math.round((scrolledPoint.x-imageBounds.x)/zoom);result.y=Math.round((scrolledPoint.y-imageBounds.y)/zoom);if (canvas.style.borderWidth){var borderWidth=parseInt(canvas.style.borderWidth);result.x -= borderWidth;result.y -= borderWidth;if (result.x < 0){result.x=0;}if (result.y < 0){result.y=0;}}return result;};PXN8.getImageSize=function(){var imgElement=document.getElementById("pxn8_image");var zoomValue=PXN8.zoom.value();var realWidth=imgElement.width / zoomValue;var realHeight=imgElement.height / zoomValue;return {width: realWidth, height: realHeight};};PXN8.objectToString=function(obj){var s="";var propToString=function(prop){return "\""+prop+"\":";};var operationAlwaysFirst=function(a,b){if (a=="operation"){ return -1;}if (b=="operation"){ return 1;}return a > b ? 1:b > a ? -1: 0;};var types={array:{s:"[",e:"]",indexer: function(o){ var result=new Array(); for (var i =0;i < o.length;i++){result.push(i);}return result;},pusher: function(array,o,i){array.push(o);}},object: {s:"{",e:"}",indexer: function(o){ var result=new Array(); for (var i in o){ if (typeof o[i] != "function"){ result.push(i);}}return result.sort(operationAlwaysFirst);},pusher: function(array,o,i){array.push(propToString(i)+o);}}};var type="object";if (PXN8.isArray(obj)){type="array";}s=types[type].s;var props=new Array();var pusher=types[type].pusher;var indexes=types[type].indexer(obj);for (var j=0;j < indexes.length; j++){var i=indexes[j];if (typeof obj[i]=="function"){continue;}if (typeof obj[i]=="string"){pusher(props,"\""+obj[i]+"\"",i);}else if (typeof obj[i]=="object"){pusher(props, PXN8.objectToString(obj[i]),i);}else if (typeof obj[i]=="boolean"){pusher(props, "\""+obj[i]+"\"",i);}else{pusher(props, obj[i],i);}}for (var i=0;i < props.length; i++){s=s+props[i];if (i < props.length-1){s += ",";}}s += types[type].e;return s;};PXN8.isArray=function(o){return (o && typeof o=='object') && o.constructor==Array;};PXN8.randomHex=function(){return (Math.round(Math.random()*65535)).toString(16)};PXN8.getImageBuffer=function(){var _=PXN8.dom;var buffer=_.id("pxn8_buffer");if (!buffer){buffer=_.ce("div",{id: "pxn8_buffer"});_.ac(document.body,buffer);buffer.style.width="1px";buffer.style.height="1px";buffer.style.overflow="hidden";}return buffer;};PXN8.replaceImage=function(imageurl){var _=PXN8.dom;var buffer=PXN8.getImageBuffer();_.cl(buffer);var theImage=_.ce("img",{id: "pxn8_buffered_image"});_.ac(buffer,theImage);var timer=_.id("pxn8_timer");if (timer){timer.style.display="block";_.ac(_.cl(timer),_.tx("Loading photo. Please wait..."));}var notified=false;var closure={onload: function(){if (!notified){PXN8.imageLoadNotifier();notified=true;}}};PXN8.event.addListener(theImage,"load",closure.onload);theImage.onload=closure.onload;theImage.src=imageurl;PXN8.show.size();};PXN8.imageUpdateDone=function (jsonResponse){var errorMsg=null;var _=PXN8.dom;var status=null;if (PXN8.log){PXN8.log.trace("PXN8.imageUpdateDone("+jsonResponse+")"); }var targetDiv=_.id("pxn8_image_container");PXN8.response=jsonResponse;if (jsonResponse && jsonResponse.status=="OK"){PXN8.responses[PXN8.opNumber]=jsonResponse;if (document.all){}var newImageSrc=PXN8.server+PXN8.root+"/"+jsonResponse.image;PXN8.replaceImage(newImageSrc);}else{status=PXN8.response;if (PXN8.response && typeof PXN8.response=="object"){status=PXN8.response.status;errorMsg="An error occurred while updating the image.\n"+"status: "+status+"\n"+"errorMessage: "+PXN8.response.errorMessage;if (PXN8.log){ PXN8.log.error(errorMsg); }alert(errorMsg);}else{errorMsg="An error occurred while updating the image.\nstatus:"+status ;if (PXN8.log){ PXN8.log.error(errorMsg); }alert(errorMsg);}PXN8.listener.notify(PXN8.ON_IMAGE_ERROR);PXN8.updating=false;PXN8.opNumber--;var timer=_.id("pxn8_timer");if (timer){timer.style.display="none";}}var theImage=_.id("pxn8_image");theImage.onerror=function(){alert(PXN8.strings.IMAGE_ON_ERROR1+theImage.src+PXN8.strings.IMAGE_ON_ERROR2);PXN8.listener.notify(PXN8.ON_IMAGE_ERROR);};};PXN8.show={};PXN8.show.selection=function(){var _=PXN8.dom;var selectionField=_.id("pxn8_selection_size");if (selectionField){var text="N/A";if (PXN8.ex-PXN8.sx > 0){text=(PXN8.ex-PXN8.sx)+","+(PXN8.ey-PXN8.sy);}_.ac(_.cl(selectionField),_.tx(text));}};PXN8.show.position=function(){var _=PXN8.dom;var posInfo=_.id("pxn8_mouse_pos");if (posInfo){var text=PXN8.position.x+","+PXN8.position.y;_.ac(_.cl(posInfo),_.tx(text));}};PXN8.show.zoom=function(t,v){var _=PXN8.dom;var zoomInfo=_.id("pxn8_zoom");if (zoomInfo){var text=Math.round((PXN8.zoom.value()*100))+"%";_.ac(_.cl(zoomInfo),_.tx(text));}};PXN8.show.size=function (){var _=PXN8.dom;var sizeInfo=_.id("pxn8_image_size");if (sizeInfo){var text=PXN8.image.width+"x"+PXN8.image.height;_.ac(_.cl(sizeInfo),_.tx(text));}};PXN8.show.alert=function (message,duration){var _=PXN8.dom;duration=duration || 1000;var warning=_.id("pxn8_warning");if (!warning){warning=_.ce("div",{id: "pxn8_warning",className: "warning"});_.ac(_.id("pxn8_canvas"),warning);}else{warning.style.display="block";}_.ac(_.cl(warning),_.tx(message));_.opacity(warning,90);warning.style.width=(PXN8.image.width>200?PXN8.image.width:200)+"px";setTimeout("PXN8.fade.init();PXN8.fade.fadeout('pxn8_warning',false);",duration);};PXN8.fade={values: [0.99,0.85, 0.70, 0.55, 0.40, 0.25, 0.10, 0],times: [75, 75, 75, 75, 75, 75, 75, 75],i: 0,stopfadeout: false};PXN8.fade.init=function(){ var self=PXN8.fade; self.i =0; self.stopfadeout=false;};PXN8.fade.cancel=function(){ var self=PXN8.fade; self.stopfadeout=true; };PXN8.fade.fadeout=function(eltid,destroyOnFade){var _=PXN8.dom;var self=PXN8.fade;if (self.stopfadeout){return;}_.opacity(eltid,self.values[self.i]);if (self.i < self.values.length -1 ){self.i++;setTimeout("PXN8.fade.fadeout('"+eltid+"',"+destroyOnFade+");",self.times[self.i]);}else{if (destroyOnFade){var node=_.id(eltid);if (!node){return;}else{var parent=node.parentNode;parent.removeChild(node);}}else{_.id(eltid).style.display="none";}}};PXN8.fade.fadein=function(eltid){var _=PXN8.dom;var self=PXN8.fade;try{if (self.i >= self.values.length){self.i=self.values.length-1;}_.opacity(eltid,self.values[self.i]);if (self.i > 0){self.i--;setTimeout("PXN8.fade.fadein('"+eltid+"');",self.times[self.i]);}}catch(e){alert(e.message);}};PXN8.offsets=[];PXN8.addOperations=function(operations){var self=PXN8;var cachedImage=self.getUncompressedImage();self.opNumber++;self.offsets[self.opNumber]=operations.length;var lastIndex=0;for (var i=0;i < self.opNumber; i++){lastIndex += self.offsets[i];}for (var i=0;i < operations.length; i++){self.history[lastIndex+i]=operations[i];}self.maxOpNumber=self.opNumber;var script=PXN8.getScript();self.prepareForSubmit();self.ajax.submitScript(script,self.imageUpdateDone);};PXN8.snapToAspectRatio=function(){var sel=PXN8.getSelection();if (PXN8.aspectRatio.width != 0){if (PXN8.aspectRatio.width > PXN8.aspectRatio.height){sel.height=Math.round((sel.width / PXN8.aspectRatio.width )*PXN8.aspectRatio.height);}else{sel.width=Math.round((sel.height / PXN8.aspectRatio.height)*PXN8.aspectRatio.width);}PXN8.select(sel);}};PXN8.zoom={};PXN8.zoom.values=[0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 2, 3, 4 ];PXN8.zoom.index=3;PXN8.zoom.zoomedBy=PXN8.zoom.values[PXN8.zoom.index];PXN8.zoom.value=function(){return PXN8.zoom.zoomedBy;};PXN8.zoom.canZoomIn=function(){var self=PXN8.zoom;return self.zoomedBy < self.values[self.values.length-1];};PXN8.zoom.canZoomOut=function(){var self=PXN8.zoom;return self.zoomedBy > self.values[0];};PXN8.zoom.zoomByIndex=function(index){return PXN8.zoom.setIndex(index);};PXN8.zoom.shrinkToWidth=function(width){if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.zoom.shrinkToWidth(width);});return;}var imgSize=PXN8.getImageSize();if (imgSize.width > width){PXN8.zoom.toWidth(width);}};PXN8.zoom.expandToWidth=function(width){if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.zoom.expandToWidth(width);});return;}var imgSize=PXN8.getImageSize();if (imgSize.width < width){PXN8.zoom.toWidth(width);}};PXN8.zoom.expandToHeight=function(height){if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.zoom.expandToHeight(height);});return;}var imgSize=PXN8.getImageSize();if (imgSize.height < height){PXN8.zoom.toHeight(height);}};PXN8.zoom.toWidth=function(width){if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.zoom.toWidth(width);});return;}var imgSize=PXN8.getImageSize();PXN8.zoom.setValue(width / imgSize.width);};PXN8.zoom.toHeight=function(height){if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.zoom.toHeight(height);});return;}var imgSize=PXN8.getImageSize();PXN8.zoom.setValue(height / imgSize.height);};PXN8.zoom.setIndex=function(i){var self=PXN8.zoom;self.index=i;return self.setValue(self.values[i]);};PXN8.zoom.setValue=function(magnification){if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.zoom.setValue(magnification);});return;}var self=PXN8.zoom;self.zoomedBy=magnification;var theImg=document.getElementById("pxn8_image");theImg.width=PXN8.image.width*magnification;theImg.height=PXN8.image.height*magnification;PXN8.listener.notify(PXN8.ON_ZOOM_CHANGE,magnification);return magnification;};PXN8.zoom.zoomIn=function(){var self=PXN8.zoom;if (self.canZoomIn()){for (var i=0; i < self.values.length;i++){if (self.values[i] > self.zoomedBy){self.setIndex(i);break;}}}else{PXN8.show.alert(PXN8.strings.NO_MORE_ZOOMIN,500);}return false;};PXN8.zoom.zoomOut=function(){var self=PXN8.zoom;if (self.canZoomOut()){for (var i=self.values.length-1; i >= 0; i--){if (self.values[i] < self.zoomedBy){self.setIndex(i);break;}}}else{PXN8.show.alert(PXN8.strings.NO_MORE_ZOOMOUT,500);}return false;};PXN8.zoom.toSize=function(width, height){if (!PXN8.ready){PXN8.listener.onceOnly(PXN8.ON_IMAGE_LOAD,function(){PXN8.zoom.toSize(width,height);});return;}var hr=width / PXN8.image.width ;var vr=height / PXN8.image.height ;PXN8.zoom.setValue(Math.min(vr,hr));return false;};PXN8.zoom.zoomByValue=function(magnification){PXN8.zoom.setValue(magnification);};PXN8.browser={};PXN8.browser.isIE6=function(){return window.navigator.userAgent.indexOf("MSIE 6") > -1;};PXN8.history=[];PXN8.responses=[];PXN8.images=[];PXN8.ready=false;PXN8.image={width: 0,height: 0,location: ""};PXN8.priv={};PXN8.priv.addImageToHistory=function(imageLocation){var item={"location": imageLocation,"width": PXN8.image.width,"height": PXN8.image.height};PXN8.images[PXN8.opNumber]=item;PXN8.updating=false;};PXN8.priv.createSelectionRect=function(){var _=PXN8.dom;var selectRect=_.id("pxn8_select_rect");if (!selectRect){var canvas=_.id("pxn8_canvas");selectRect=_.ac(canvas, _.ce("div", {id: "pxn8_select_rect"}));selectRect.style.backgroundColor="white";_.opacity(selectRect,0);selectRect.style.cursor="move";selectRect.style.borderWidth="1px";selectRect.style.borderColor="red";selectRect.style.borderStyle="dotted";selectRect.style.position="absolute";selectRect.style.zIndex=1;selectRect.style.fontSize="0px";selectRect.style.display="block";selectRect.style.width="0px";selectRect.style.height="0px";}selectRect.onmousedown=function(event){if (!event) event=window.event;PXN8.drag.begin(selectRect,event,PXN8.drag.moveSelectionBoxHandler,PXN8.drag.upSelectionBoxHandler);};return selectRect;};PXN8.when=function (condition, callback, interval){if (!condition()){setTimeout(function(){PXN8.when(condition,callback,interval);},interval);}else{callback();}};PXN8.whenReady=function(callback){var condition=function(){return PXN8.ready;};PXN8.when(condition,callback,50);};PXN8.imageLoadNotifier=function(){PXN8.when(
function(){ return PXN8.ready; },function(){ PXN8.listener.notify(PXN8.ON_IMAGE_LOAD); },50
);};PXN8.onCanvasMouseDown=function(event){if (!event) event=window.event;PXN8.drag.begin(document.getElementById("pxn8_canvas"),event,PXN8.drag.moveCanvasHandler,PXN8.drag.upCanvasHandler);};PXN8.initializeCanvas=function(){var _=PXN8.dom;var canvas=_.id("pxn8_canvas");canvas.onmousemove=function (event){if (!event) event=window.event;var cursorPos=_.cursorPos(event);var imagePoint=PXN8.mousePointToElementPoint(cursorPos.x, cursorPos.y);PXN8.position.x=imagePoint.x;PXN8.position.y=imagePoint.y;PXN8.show.position();return true;};canvas.onmouseout=function (event){if (!event) event=window.event;PXN8.position.x="-";PXN8.position.y="-";PXN8.show.position();};canvas.onmousedown=PXN8.onCanvasMouseDown;canvas.ondrag=function(){return false;};var computedCanvasStyle=_.computedStyle("pxn8_canvas");var canvasPosition=null;if (computedCanvasStyle.getPropertyValue){canvasPosition=computedCanvasStyle.getPropertyValue("position");}else{if (!computedCanvasStyle.position){canvasPosition="static";}else{canvasPosition=computedCanvasStyle.position;}}if (!canvasPosition || canvasPosition=="static"){canvas.style.position="relative";canvas.style.top="0px";canvas.style.left="0px";}var floatProperty="cssFloat";if (document.all){floatProperty="styleFloat";}var floatValue=computedCanvasStyle[floatProperty];if (!floatValue || floatValue=="none"){canvas.style[floatProperty]="left";}return canvas;};PXN8.listener.add(PXN8.ON_IMAGE_CHANGE, PXN8.show.zoom);PXN8.listener.add(PXN8.ON_ZOOM_CHANGE, PXN8.show.zoom);var PXN8=PXN8 || {};PXN8.toolbar={};PXN8.toolbar.crop_options=["4x6","5x8"];PXN8.toolbar.draw=function(buttons){var dom=PXN8.dom;if (!buttons){buttons=new Array();for (var i in PXN8.toolbar.buttons){buttons.push(i);}}document.writeln("<table cellspacing='0' cellpadding='0'><tbody><tr id='pxn8_toolbar_table'></tr></tbody></table>");for (var i in PXN8.toolbar.menu){document.writeln("<div id='pxn8_toolbar_"+i+"' class='pxn8_toolbar_dropdown' style='display:none;'></div>");}function moveMenusToBody(){for (var i in PXN8.toolbar.menu){var menuElement=document.getElementById("pxn8_toolbar_"+i);var menuParent=menuElement.parentNode;menuParent.removeChild(menuElement);document.body.appendChild(menuElement);}};PXN8.dom.addLoadEvent(moveMenusToBody);var toolbar=dom.id('pxn8_toolbar_table');for (var h =0; h < buttons.length; h++){var i= buttons[h];var widgetModel=PXN8.toolbar.buttons[i];var cell=dom.ac(toolbar,dom.ce("td"));var widget=dom.ce("a",{className: "pxn8_toolbar_btn",href: "javascript:void(0);",onclick: widgetModel.onclick,title: widgetModel.tooltip,onmousedown: function(){this.className='pxn8_toolbar_btndown';},onmouseup: function(){this.className='pxn8_toolbar_btn';},onmouseout: function(){this.className='pxn8_toolbar_btn';}});var arrowLink=dom.ce("a",{href: "javascript:void(0);",onclick: function(event,element){widgetModel.arrowClicked=widgetModel.arrowClicked==true?false:true;}});dom.ac(cell,widget);var widgetImage=dom.ce("img", {border: 0,alt: widgetModel.tooltip,src: PXN8.server+PXN8.root+widgetModel.image});dom.ac(widget,widgetImage);}dom.ac(dom.ac(dom.ac(toolbar,dom.ce("td")),dom.ce("a",{ href: "http:/"+"/pixenate.com/"})),dom.ce("img",{border: 0,id: "pxn8_poweredby",src: PXN8.server+PXN8.root+"/images/icons/powered_by_pxn8.gif"}));};PXN8.toolbar.hidemenu=function(e){if (!e) var e=window.event;var tg=(window.event) ? e.srcElement:e.target;if (tg.nodeName != 'DIV') return;var reltg=(e.relatedTarget) ? e.relatedTarget:e.toElement;while (reltg != tg && reltg.nodeName != 'BODY'){reltg=reltg.parentNode;}if (reltg==tg) return;tg.style.display="none";};PXN8.toolbar.ontoolclick=function(event, menuDiv, button_offset, menuMap, default_func){var dom=PXN8.dom;if (!event){event=window.event;}var button=(window.event) ? event.srcElement:event.target;menuDiv.onmouseout=function(event){PXN8.toolbar.hidemenu(event);};if (menuDiv.style.display=="block"){menuDiv.style.display="none";return;}var dropdowns=PXN8.dom.clz("pxn8_toolbar_dropdown");for (var i=0; i < dropdowns.length; i++){var dropdown=dropdowns[i];dropdown.style.display="none";}var pos=dom.eb(button);var ox=event.clientX-pos.x ;var oy=event.clientY-pos.y ;if (ox > button_offset){dom.cl(menuDiv);for (var i in menuMap){var callback=function(f){return function(){f();var dropdowns=PXN8.dom.clz("pxn8_toolbar_dropdown");for (var i=0; i < dropdowns.length; i++){var dropdown=dropdowns[i];dropdown.style.display="none";}return false;};};var link=dom.ce("a",{href: "javascript:void(0);",className: "pxn8_toolbar_option",onclick:callback(menuMap[i].onclick),title: menuMap[i].tooltip});if (menuMap[i].image){var linkImage=dom.ce("img", {border: 0, src: PXN8.server+PXN8.root+"/" +menuMap[i].image, alt: menuMap[i].tooltip});dom.ac(link,linkImage);}dom.ac(link,dom.tx(i));dom.ac(menuDiv,link);}menuDiv.style.display="block";menuDiv.style.top=pos.y+pos.height+4+"px";menuDiv.style.left=(pos.x-4)+"px";}else{default_func();}return false;};PXN8.toolbar.menu={crop: {},rotate: {},instantFix: {}};PXN8.toolbar.buttons={};PXN8.toolbar.buttons.zoomin={onclick: function(){PXN8.zoom.zoomIn();return false;},image: "/images/icons/magnifier_zoom_in.gif",tooltip: "Zoom In"};PXN8.toolbar.buttons.zoomout={onclick: function(){PXN8.zoom.zoomOut();return false;},image: "/images/icons/magnifier_zoom_out.gif",tooltip: "Zoom Out"};PXN8.toolbar.buttons.rotate={onclick: function(event){var dropdown=document.getElementById("pxn8_toolbar_rotate");var menuContents={"Clockwise": {onclick: function(){PXN8.tools.rotate({angle: 90});},image: "/images/icons/rotate_clockwise.gif",tooltip: "Rotate the image 90 degrees clockwise"},"Anti-Clockwise": {onclick: function(){PXN8.tools.rotate({angle: 270});},image: "/images/icons/rotate_anticlockwise.gif",tooltip: "Rotate the image 90 degrees anti-clockwise"},"Flip Vertically": {onclick: function(){PXN8.tools.rotate({flipvt: "true"});},image: "/images/icons/shape_flip_vertical.gif",tooltip: "Flip the image on the Vertical axis"},"Flip Horizontally": {onclick: function(){PXN8.tools.rotate({fliphz: "true"});},image: "/images/icons/shape_flip_horizontal.gif",tooltip: "Flip the image on the Horizontal axis"}};PXN8.toolbar.ontoolclick(event,dropdown,40,menuContents,function(){PXN8.tools.rotate({angle:90});});return false;},image: "/images/icons/rotate.gif",tooltip: "Rotate the photo by 90 degrees clockwise"};PXN8.toolbar.buttons.add_text={onclick: function(event){},image: "/images/icons/add_text.gif",tooltip: "Add Text to photo"};PXN8.toolbar.buttons.normalize={onclick: function(){PXN8.tools.normalize();return false;},image: "/images/icons/normalize.gif",tooltip: "Gives better color balance"};PXN8.toolbar.buttons.enhance={onclick: function(event){PXN8.tools.enhance();return false;},image: "/images/icons/enhance.gif",tooltip: "Smooths facial lines"};PXN8.toolbar.buttons.save={onclick: function(event){return PXN8.save.toServer();},image: "/images/icons/save.gif",tooltip: "Save image to server"};PXN8.toolbar.buttons.instantFix={onclick: function(event){var dropdown=document.getElementById("pxn8_toolbar_instantFix");var fixes={"Enhance": {onclick: function(){PXN8.tools.enhance(); },tooltip: "Enhance the photo (smooths facial lines)"},"Normalize": {onclick: function(){PXN8.tools.normalize();},tooltip: "Normalize gives better color balance"}};PXN8.toolbar.ontoolclick(event,dropdown,48,fixes,PXN8.tools.instantFix);return false;},image: "/images/icons/instant_fix.gif",tooltip: "A quick fix solution-gives better color balance and smooths lines"};PXN8.toolbar.buttons.crop={onclick: function(event){var dropdown=document.getElementById("pxn8_toolbar_crop");var callback=function(opt){return function(){PXN8.selectByRatio(opt);};};var menuContents={};for (var i=0;i < PXN8.toolbar.crop_options.length; i++){var option=PXN8.toolbar.crop_options[i];menuContents[option]={onclick: callback(option)};}PXN8.toolbar.ontoolclick(event,dropdown,40,menuContents,function(){var selection=PXN8.getSelection();if (selection.width > 0){PXN8.tools.crop(selection);}else{PXN8.show.alert("Select an area to crop");}});return false;},image: "/images/icons/cut_red.gif",tooltip: "Crop the image"};PXN8.toolbar.buttons.fillflash={onclick: function(){PXN8.tools.fill_flash();return false;},image: "/images/icons/lightning_add.gif",tooltip: "Add Fill-Flash to brighten the image"};PXN8.toolbar.buttons.undo={onclick: function(){PXN8.tools.undo();return false;},image: "/images/icons/undo.gif",tooltip: "Undo the last operation"};PXN8.toolbar.buttons.redo={onclick: function(){PXN8.tools.redo();return false;},image: "/images/icons/redo.gif",tooltip: "Redo the last operation"};PXN8.toolbar.buttons.undoall={onclick: function(){PXN8.tools.undoall();return false;},image: "/images/icons/undo_all.gif",tooltip: "Undo all operations"};PXN8.toolbar.buttons.redoall={onclick: function(){PXN8.tools.redoall();return false;},image: "/images/icons/redo_all.gif",tooltip: "Redo all operations"};PXN8.toolbar.buttons.selectall={onclick: PXN8.selectAll,image: "/images/icons/selectall.gif",tooltip: "Select entire photo"};PXN8.toolbar.buttons.unselect={onclick: PXN8.unselect,image: "/images/icons/unselect.gif",tooltip: "Select entire photo"};var PXN8=PXN8 || {};PXN8.event={};PXN8.event._added=[];PXN8.event.addListener=function(el,eventstr,func){if (typeof el=='string'){ el=PXN8.dom.id(el); }if (el.addEventListener){el.addEventListener(eventstr,func,true);}else if (el.attachEvent){el.attachEvent("on"+eventstr,func);}var record={"element": el, "event": eventstr, "listener": func};PXN8.event._added.push(record);return func;};PXN8.event.removeListener=function(el,eventstr,func){if (typeof el=='string'){ el=PXN8.dom.id(el);}if (func){PXN8.event._removeListener(el,eventstr,func);} else {var original=PXN8.event._added;var removed=false;for (var i =0; i < original.length; i++){var record=original[i];if (record){if (record.eventstr==eventstr && record.element==el){PXN8.event._removeListener(el,eventstr,record.listener);original[i]=null;removed=true;}}}if (!removed){ return ;}var temp=[];for (var i=0;i < original.length;i++){if (original[i] != null){temp.push(original[i]);}}PXN8.event._added=temp;}};PXN8.event._removeListener=function(el,eventstr,func){if (typeof el=='string'){ el=PXN8.dom.id(el); }if (el.removeEventListener){el.removeEventListener(eventstr,func,true);}else if (el.detachEvent){el.detachEvent("on"+eventstr,func);}};PXN8.event.closure=function(object,func){return function(event){event=event || window.event;var source=(window.event) ? event.srcElement:event.target;func(event,object,source,arguments.callee);};};PXN8.event.normalize=function(func){return function(event){event=event || window.event;var source=(window.event) ? event.srcElement:event.target;func(event,source,arguments.callee);};};PXN8.behaviour={bind: function(className,behaviourObject){var elements=PXN8.dom.clz(className);for (var i=0;i < elements.length; i++){for (var j in behaviourObject){PXN8.event.addListener(elements[i],j,behaviourObject[j]);}}}};var PXN8=PXN8 || {};PXN8.drag={dx: 0,dy: 0,beginDragX: 0,beginDragY: 0,osx: 0,osy: 0,ow: 0,oh: 0};PXN8.drag.begin=function (elementToDrag, event, moveHandler, upHandler){var _=PXN8.dom;var elementBounds=_.eb(elementToDrag);var cursorPos=_.cursorPos(event);var scrolledPoint=PXN8.scrolledPoint(cursorPos.x,cursorPos.y);PXN8.drag.beginDragX=scrolledPoint.x;PXN8.drag.beginDragY=scrolledPoint.y;PXN8.drag.dx=scrolledPoint.x-elementBounds.x;PXN8.drag.dy=scrolledPoint.y-elementBounds.y;PXN8.drag.osx=PXN8.sx;PXN8.drag.osy=PXN8.sy;PXN8.drag.ow=PXN8.ex-PXN8.sx;PXN8.drag.oh=PXN8.ey-PXN8.sy;if (document.addEventListener){document.addEventListener("mousemove", moveHandler, true);document.addEventListener("mouseup", upHandler, true);}else if (document.attachEvent){document.attachEvent("onmousemove",moveHandler);document.attachEvent("onmouseup",upHandler);}if (event.stopPropogation) {event.stopPropogation();}else{event.cancelBubble=true; }if (event.preventDefault){event.preventDefault(); }else {event.returnValue=false; }};PXN8.drag.moveCanvasHandler=function (event){var _=PXN8.dom;if (!event) event=window.event;var canvasBounds=_.eb("pxn8_canvas");var theImg=_.id("pxn8_image");var maxX=canvasBounds.x+theImg.width;var maxY=canvasBounds.y+theImg.height;var cursorPos=_.cursorPos(event);var scrolledPoint=PXN8.scrolledPoint(cursorPos.x, cursorPos.y);var x2=scrolledPoint.x>maxX?maxX:scrolledPoint.x;x2=x2 < canvasBounds.x?canvasBounds.x:x2;var y2=scrolledPoint.y>maxY?maxY:scrolledPoint.y;y2=y2 < canvasBounds.y?canvasBounds.y:y2;var numerical=function(a,b){return a-b;};var xVals=[PXN8.drag.beginDragX-canvasBounds.x,x2-canvasBounds.x].sort(numerical);var yVals=[PXN8.drag.beginDragY-canvasBounds.y,y2-canvasBounds.y].sort(numerical);var pixelWidth=xVals[1]-xVals[0];var pixelHeight=yVals[1]-yVals[0];var width=Math.round(pixelWidth / PXN8.zoom.value());var height=Math.round(pixelHeight / PXN8.zoom.value());height=height > PXN8.image.height?PXN8.image.height:height;width=width > PXN8.image.width?PXN8.image.width:width;if (width > PXN8.aspectRatio.width && height > PXN8.aspectRatio.height && PXN8.aspectRatio.width > 0){if (PXN8.aspectRatio.width > PXN8.aspectRatio.height){height=Math.round(width/PXN8.aspectRatio.width *PXN8.aspectRatio.height);}else{width=Math.round(height/PXN8.aspectRatio.height *PXN8.aspectRatio.width);}}PXN8.sx=Math.round(xVals[0]/PXN8.zoom.value());PXN8.ex=PXN8.sx+width;PXN8.sy=Math.round(yVals[0]/PXN8.zoom.value());PXN8.ey=PXN8.sy+height;PXN8.snapToAspectRatio();PXN8.listener.notify(PXN8.ON_SELECTION_CHANGE,PXN8.getSelection());if (event.stopPropogation){event.stopPropogation(); }else {event.cancelBubble=true; }};PXN8.drag.upCanvasHandler=function (event){if (!event) event=window.event ;if (document.removeEventListener){document.removeEventListener("mouseup",PXN8.drag.upCanvasHandler,true);document.removeEventListener("mousemove",PXN8.drag.moveCanvasHandler, true);}else if (document.detachEvent){document.detachEvent("onmouseup",PXN8.drag.upCanvasHandler);document.detachEvent("onmousemove",PXN8.drag.moveCanvasHandler);}if (event.stopPropogation) {event.stopPropogation(); }else {event.cancelBubble=true; }PXN8.listener.notify(PXN8.ON_SELECTION_COMPLETE);};PXN8.drag.moveSelectionBoxHandler=function (event){var _=PXN8.dom;if (!event) event=window.event;var canvasBounds=_.eb("pxn8_canvas");var theImg=_.id("pxn8_image");var mx=canvasBounds.x+theImg.width;var my=canvasBounds.y+theImg.height;var cursorPos=_.cursorPos(event);var scrolledPoint=PXN8.scrolledPoint(cursorPos.x, cursorPos.y);var rx=scrolledPoint.x-PXN8.drag.beginDragX;var ry=scrolledPoint.y-PXN8.drag.beginDragY;var zrx=rx / PXN8.zoom.value();var zry=ry / PXN8.zoom.value();var sx=Math.round(PXN8.drag.osx+zrx);var sy=Math.round(PXN8.drag.osy+zry);if (PXN8.select.constrainToImageBounds==true){sx=Math.max(sx,0);sx=Math.round((sx+PXN8.drag.ow)>PXN8.image.width?(PXN8.image.width-PXN8.drag.ow):sx);sy=Math.max(sy,0);sy=Math.round((sy+PXN8.drag.oh)>PXN8.image.height?(PXN8.image.height-PXN8.drag.oh):sy);}var width=PXN8.drag.ow>0?PXN8.drag.ow:0;var height=PXN8.drag.oh>0?PXN8.drag.oh:0;if (event.stopPropogation) {event.stopPropogation(); }else {event.cancelBubble=true; }PXN8.select(sx,sy,width,height);};PXN8.drag.upSelectionBoxHandler=function (event){if (!event) event=window.event ;if (document.removeEventListener){document.removeEventListener("mouseup",PXN8.drag.upSelectionBoxHandler,true);document.removeEventListener("mousemove",PXN8.drag.moveSelectionBoxHandler, true);}else if (document.detachEvent){document.detachEvent("onmouseup",PXN8.drag.upSelectionBoxHandler);document.detachEvent("onmousemove",PXN8.drag.moveSelectionBoxHandler);}if (event.stopPropogation) {event.stopPropogation(); }else {event.cancelBubble=true; }PXN8.listener.notify(PXN8.ON_SELECTION_COMPLETE);};var PXN8=PXN8 || {};PXN8.resize={dx: 0,dy: 0,start_width: 0,start_height: 0};PXN8.resize.canResizeNorth=function(yOffset){return (PXN8.sy+yOffset < (PXN8.ey-PXN8.style.resizeHandles.size)) && (PXN8.sy+yOffset > 0);};PXN8.resize.canResizeWest=function(xOffset){return (PXN8.sx+xOffset < (PXN8.ex-PXN8.style.resizeHandles.size)) && (PXN8.sx+xOffset > 0);};PXN8.resize.canResizeSouth=function(yOffset){return (PXN8.ey+yOffset > (PXN8.sy+PXN8.style.resizeHandles.size)) && (PXN8.ey+yOffset < PXN8.image.height);};PXN8.resize.canResizeEast=function(xOffset){return (PXN8.ex+xOffset > (PXN8.sx+PXN8.style.resizeHandles.size)) && (PXN8.ex+xOffset < PXN8.image.width);};PXN8.resize.nTest=function(xOffset,yOffset,event){if (PXN8.resize.canResizeNorth(yOffset) ) {PXN8.resize.dy=event.clientY;PXN8.sy=Math.round(PXN8.sy+yOffset);return true;}return false;};PXN8.resize.sTest=function(xOffset,yOffset,event){if (PXN8.resize.canResizeSouth(yOffset)){PXN8.resize.dy=event.clientY;PXN8.ey=Math.round(PXN8.ey+yOffset);return true;}return false;};PXN8.resize.wTest=function(xOffset,yOffset,event){if (PXN8.resize.canResizeWest(xOffset)) {PXN8.resize.dx=event.clientX;PXN8.sx=Math.round(PXN8.sx+xOffset);return true;}return false;};PXN8.resize.eTest=function(xOffset,yOffset,event){if (PXN8.resize.canResizeEast(xOffset)){PXN8.resize.dx=event.clientX;PXN8.ex=Math.round(PXN8.ex+xOffset);return true;}return false;};PXN8.resize.nwTest=function(xOffset,yOffset,event){if (xOffset==0 || yOffset==0){return false;}var hr=PXN8.resize.start_height/PXN8.resize.start_width;var wr=1 / hr;if (wr > hr){xOffset=yOffset*wr;}else if (wr < hr){yOffset=xOffset*hr;}else{yOffset=xOffset;}if (xOffset > 0){yOffset=Math.abs(yOffset);}else{yOffset=0-Math.abs(yOffset);}if (PXN8.resize.canResizeWest(xOffset) && PXN8.resize.canResizeNorth(yOffset)){PXN8.resize.dx=event.clientX;PXN8.resize.dy=event.clientY;PXN8.sx=Math.round(PXN8.sx+xOffset);PXN8.sy=Math.round(PXN8.sy+yOffset);return true;}return false;};PXN8.resize.swTest=function(xOffset,yOffset,event) {if (xOffset==0 || yOffset==0){return false;}var hr=PXN8.resize.start_height/PXN8.resize.start_width;var wr=1 / hr;if (wr > hr){yOffset=xOffset*wr;}else{yOffset=xOffset;}if (xOffset > 0){yOffset=0-Math.abs(yOffset);}else{yOffset=Math.abs(yOffset);}if (PXN8.resize.canResizeWest(xOffset) && PXN8.resize.canResizeSouth(yOffset)){PXN8.resize.dx=event.clientX;PXN8.resize.dy=event.clientY;PXN8.sx=Math.round(PXN8.sx+xOffset);PXN8.ey=Math.round(PXN8.ey+yOffset);return true;}return false;};PXN8.resize.neTest=function(xOffset,yOffset,event) {if (xOffset==0 || yOffset==0){return false;}var hr=PXN8.resize.start_height/PXN8.resize.start_width;var wr=1 / hr;if (wr > hr){xOffset=yOffset*wr;}else{xOffset=yOffset;}if (yOffset > 0){xOffset=0-Math.abs(xOffset);}else{xOffset=Math.abs(xOffset);}if (PXN8.resize.canResizeEast(xOffset) && PXN8.resize.canResizeNorth(yOffset)){PXN8.resize.dx=event.clientX;PXN8.resize.dy=event.clientY;PXN8.ex=Math.round(PXN8.ex+xOffset);PXN8.sy=Math.round(PXN8.sy+yOffset);return true;}return false;};PXN8.resize.seTest=function(xOffset,yOffset,event) {if (xOffset==0 || yOffset==0){return false;}var hr=PXN8.resize.start_height/PXN8.resize.start_width;var wr=1 / hr;if (wr > hr){xOffset=yOffset*wr;}else{yOffset=xOffset;}if (xOffset > 0){yOffset=Math.abs(yOffset);}else{yOffset=0-Math.abs(yOffset);}if (PXN8.resize.canResizeEast(xOffset) && PXN8.resize.canResizeSouth(yOffset)){PXN8.resize.dx=event.clientX;PXN8.resize.dy=event.clientY;PXN8.ex=Math.round(PXN8.ex+xOffset);PXN8.ey=Math.round(PXN8.ey+yOffset);return true;}return false;};PXN8.resize.stopResizing=function(event){if (!event) event=window.event ;if (document.removeEventListener){document.removeEventListener("mouseup",PXN8.resize.stopResizing,true);for (var i in PXN8.resize.handles){if (typeof PXN8.resize.handles[i] != "function"){document.removeEventListener("mousemove",PXN8.resize.handles[i].moveHandler, true);}}}else if (document.detachEvent){document.detachEvent("onmouseup",PXN8.resize.stopResizing);for (var i in PXN8.resize.handles){if (typeof PXN8.resize.handles[i] != "function"){document.detachEvent("onmousemove",PXN8.resize.handles[i].moveHandler);}}}if (event.stopPropogation) event.stopPropogation();else event.cancelBubble=true;PXN8.listener.notify(PXN8.ON_SELECTION_COMPLETE);};PXN8.resize.startResizing=function(hdlr){var result=function(event){if (!event) event=window.event;PXN8.resize.dx=event.clientX;PXN8.resize.dy=event.clientY;var sel=PXN8.getSelection();PXN8.resize.start_height=sel.height;PXN8.resize.start_width=sel.width;if (document.addEventListener){document.addEventListener("mousemove", hdlr, true);document.addEventListener("mouseup", PXN8.resize.stopResizing, true);}else if (document.attachEvent){document.attachEvent("onmousemove",hdlr);document.attachEvent("onmouseup",PXN8.resize.stopResizing);}if (event.stopPropogation){event.stopPropogation();}else {event.cancelBubble=true; }if (event.preventDefault){event.preventDefault(); }else {event.returnValue=false; }};return result;};PXN8.resize.createResizeHandle=function(direction,size,color) {var result=document.createElement("div");result.id=direction+"_handle";result.style.backgroundColor=color;result.style.position="absolute";result.style.width=size+"px";result.style.height=size+"px";result.style.overflow="hidden"; result.style.zIndex=999;result.style.cursor=direction+"-resize";result.onmousedown=PXN8.resize.startResizing(PXN8.resize.handles[direction].moveHandler);result.ondrag=function(){return false;};return result;};PXN8.resize.positionResizeHandles=function() {var dom=PXN8.dom;var sel=PXN8.getSelection();if (sel.width==0){PXN8.resize.hideResizeHandles();return;}var zoom=PXN8.zoom.value();var rhsz=PXN8.style.resizeHandles.size;var rhsm=PXN8.style.resizeHandles.smallsize;var canvas=dom.id("pxn8_canvas");for (var i in PXN8.resize.handles){if (typeof (PXN8.resize.handles[i])=="function"){continue;}var handle=dom.id( i+"_handle");if (!handle){handle=PXN8.resize.createResizeHandle(i, rhsz, PXN8.style.resizeHandles.color);dom.ac(canvas,handle);}if (handle.style.display=="none"){handle.style.display="block";}PXN8.resize.handles[i].position(handle,sel);}};PXN8.resize.hideResizeHandles=function(hdls) {var dom=PXN8.dom;if (hdls){for (var i =0; i < hdls.length;i++){var handle=dom.id( i+"_handle");if (handle){handle.style.display="none";}}}else{for (var i in PXN8.resize.handles){if (typeof (PXN8.resize.handles[i])=="function"){continue;}var handle=dom.id( i+"_handle");if (handle){handle.style.display="none";}}}};PXN8.resize.resizer=function( testFunc ){var result=function(event){if (!event) event=window.event;var rdy=event.clientY-PXN8.resize.dy;var rdx=event.clientX-PXN8.resize.dx;var prdy=Math.round(rdy / PXN8.zoom.value());var prdx=Math.round(rdx / PXN8.zoom.value());if (prdx==0 && prdy==0){}else{if (testFunc(prdx,prdy,event)==true){PXN8.snapToAspectRatio();PXN8.listener.notify(PXN8.ON_SELECTION_CHANGE,PXN8.getSelection());}}if (event.stopPropogation) event.stopPropogation();else event.cancelBubble=true; };return result;};PXN8.resize.handles={"n": { moveHandler: PXN8.resize.resizer(PXN8.resize.nTest),position: function(handle,sel){var sel_rect=PXN8.dom.eb("pxn8_select_rect");handle.style.left=sel_rect.x+Math.ceil(sel_rect.width/2)-(PXN8.style.resizeHandles.size/2)+"px";handle.style.top=sel_rect.y+"px";}},"s": { moveHandler: PXN8.resize.resizer(PXN8.resize.sTest),position: function(handle,sel){var sel_rect=PXN8.dom.eb("pxn8_select_rect");handle.style.left=sel_rect.x+Math.ceil(sel_rect.width/2)-(PXN8.style.resizeHandles.size/2)+"px";handle.style.top=Math.round(((sel.top+sel.height)*PXN8.zoom.value())-PXN8.style.resizeHandles.size)+"px";}},"e": { moveHandler: PXN8.resize.resizer(PXN8.resize.eTest),position: function(handle,sel){var sel_rect=PXN8.dom.eb("pxn8_select_rect");handle.style.left=Math.round(((sel.left+sel.width)*PXN8.zoom.value())-PXN8.style.resizeHandles.size)+"px";handle.style.top=sel_rect.y+Math.ceil(sel_rect.height / 2)-(PXN8.style.resizeHandles.size / 2)+"px";}},"w": { moveHandler: PXN8.resize.resizer(PXN8.resize.wTest),position: function(handle,sel){var sel_rect=PXN8.dom.eb("pxn8_select_rect");handle.style.top=sel_rect.y+Math.ceil(sel_rect.height / 2)-(PXN8.style.resizeHandles.size / 2)+"px";handle.style.left=sel_rect.x+"px";}},"nw": { moveHandler: PXN8.resize.resizer(PXN8.resize.nwTest),position: function(handle,sel){handle.style.left=Math.round(sel.left*PXN8.zoom.value())+"px";handle.style.top=Math.round((sel.top*PXN8.zoom.value()))+"px";}},"sw": { moveHandler: PXN8.resize.resizer(PXN8.resize.swTest),position: function(handle,sel){handle.style.left=Math.round(sel.left*PXN8.zoom.value())+"px";handle.style.top=Math.round(((sel.top+sel.height)*PXN8.zoom.value())-PXN8.style.resizeHandles.size)+"px";}},"ne": { moveHandler: PXN8.resize.resizer(PXN8.resize.neTest),position: function(handle,sel){handle.style.left=Math.round(((sel.left+sel.width)*PXN8.zoom.value())-PXN8.style.resizeHandles.size)+"px";handle.style.top=Math.round((sel.top*PXN8.zoom.value()))+"px";}},"se": { moveHandler: PXN8.resize.resizer(PXN8.resize.seTest),position: function(handle,sel){handle.style.left=Math.round(((sel.left+sel.width)*PXN8.zoom.value())-PXN8.style.resizeHandles.size)+"px";handle.style.top=Math.round(((sel.top+sel.height)*PXN8.zoom.value())-PXN8.style.resizeHandles.size)+"px";}}};PXN8.resize.enable=function(handles, enable){var source=PXN8.resize.handles;var target=PXN8.resize.handle_store;var display="none";var dom=PXN8.dom;if (enable){source=PXN8.resize.handle_store;target=PXN8.resize.handles;dispay="block";}for (var i=0; i < handles.length; i++){var handle=handles[i];var hdl=source[handle];delete source[handle];if (hdl){target[handle]=hdl;var handle_element=dom.id( handle+"_handle");if (handle_element){handle_element.parentNode.removeChild(handle_element);}}}PXN8.resize.positionResizeHandles();};PXN8.resize.handle_store={};PXN8.listener.add(PXN8.ON_SELECTION_CHANGE, PXN8.resize.positionResizeHandles);PXN8.listener.add(PXN8.ON_ZOOM_CHANGE, PXN8.resize.positionResizeHandles);var PXN8=PXN8 || {};PXN8.dom={cachedComputedStyles: {}};PXN8.dom.cl=function(elt){if (typeof elt=='string'){ elt=PXN8.dom.id(elt); }if (!elt) return false;while (elt.firstChild){ elt.removeChild(elt.firstChild);}return elt;};PXN8.dom.tx=function(str){ return document.createTextNode(str);};PXN8.dom.id=function(str){ return document.getElementById(str);};PXN8.dom.ce=function(nodeType,attrs){var el=document.createElement(nodeType);for (var i in attrs){ el[i]=attrs[i];}return el;};PXN8.dom.css=function(elt,attrs){var i;if (typeof elt=='string'){ elt=PXN8.dom.id(elt); }for (i in attrs){elt.style[i]=attrs[i];}return elt;};PXN8.dom.ac=function(parent,child){if (typeof parent=='string'){ parent=PXN8.dom.id(parent); }if (typeof child=='string'){ child=PXN8.dom.id(child); }if (!parent || !child){ return false; }parent.appendChild(child);return child;};PXN8.dom.eb=function(elt){if (typeof elt=='string'){ elt=PXN8.dom.id(elt); }if (!elt){ return false; }var x=null;var y=null;if(elt.style.position=="absolute"){x=parseInt(elt.style.left);y=parseInt(elt.style.top);} else {var pos=this.ep(elt);x=pos.x;y=pos.y;}return {x: x, y: y, width: elt.offsetWidth, height: elt.offsetHeight};};PXN8.dom.ep=function (elt){if (typeof elt=='string'){ elt=PXN8.dom.id(elt); }if (!elt) { return false; }var tmpElt=elt;var posX=parseInt(tmpElt["offsetLeft"]);var posY=parseInt(tmpElt["offsetTop"]);while(tmpElt.tagName.toUpperCase() != "BODY") {tmpElt=tmpElt.offsetParent;if (tmpElt==null){break;}posX += parseInt(tmpElt["offsetLeft"]);posY += parseInt(tmpElt["offsetTop"]);}return {x: posX, y:posY};};PXN8.dom.windowSize=function(){if (document.all){return {width: document.body.clientWidth,height: document.body.clientHeight};}else{return {width: window.outerWidth,height: window.outerHeight};}};PXN8.dom.opacity=function(elt, value){if (typeof elt=='string'){ elt=PXN8.dom.id(elt); }if (!elt){return;}if (document.all){elt.style.filter="alpha(opacity:"+(value*100)+")";}else{elt.style.opacity=value;elt.style._moz_opacity=value;}};PXN8.dom.clz=function(className){var links=document.getElementsByTagName("*");var result=new Array();for (var i=0;i < links.length; i++){if (links[i].className.match(className)){result.push(links[i]);}}return result;};PXN8.dom.removeClass=function(elt,className){if (typeof elt=='string'){ elt=PXN8.dom.id(elt); }var oldClassname=elt.className;var oldClasses=oldClassname.split(/ /);var newClasses=[];for (var i=0;i < oldClasses.length; i++){if (oldClasses[i] != className){newClasses.push(oldClasses[i]);}}var newClassname=newClasses.join(' ');elt.className=newClassname;};PXN8.dom.addClass=function(elt,className){if (typeof elt=='string'){ elt=PXN8.dom.id(elt); }elt.className += ' '+className;};PXN8.dom.isClass=function(elt,className){if (typeof elt=='string'){ elt=PXN8.dom.id(elt); }var clzs=elt.className.split(/ /);for (var i=0; i < clzs.length; i++){if (clzs[i]==className){return true;}}return false;};PXN8.dom.computedStyle=function(elementId){var result=null;if (this.cachedComputedStyles[elementId]){result=this.cachedComputedStyles[elementId];}else{var element=this.id(elementId);if (document.all){result=element.currentStyle;}else{if (window.getComputedStyle){result=window.getComputedStyle(element,null);}else{result=element.style;}}this.cachedComputedStyles[elementId]=result;}return result;};PXN8.dom.cursorPos=function (e){e=e || window.event;var cursor={x:0, y:0};if (e.pageX || e.pageY) {cursor.x=e.pageX;cursor.y=e.pageY;}else {var sl=document.documentElement.scrollLeft || document.body.scrollLeft;var st=document.documentElement.scrollTop || document.body.scrollTop;cursor.x=e.clientX+sl-document.documentElement.clientLeft;cursor.y=e.clientY+st-document.documentElement.clientTop;}return cursor;};PXN8.dom.addLoadEvent=function(func){var oldonload=window.onload;if (typeof window.onload != 'function'){window.onload=func;} else {window.onload=function(){if (oldonload){oldonload();}func();};}};PXN8.dom.addClickEvent=function(elt,func){var oldonclick=elt.onclick;if (typeof oldonclick != 'function'){elt.onclick=func;} else {elt.onclick=function(){if (oldonclick){oldonclick(elt);}func(elt);};}};PXN8.dom.onceOnlyClickEvent=function(elt,func){var oldonclick=elt.onclick;PXN8.dom.addClickEvent(elt,function(){func();elt.onclick=oldonclick;});};PXN8.dom.table=function(rows, attributes){var dom=PXN8.dom;var result=dom.ce("table",attributes);var tbody=dom.ce("tbody");result.appendChild(tbody);var mostCells=0;for (var i=0; i < rows.length; i++){var row=rows[i];if (row.length > mostCells){mostCells=row.length;}}for (var i=0; i < rows.length; i++){var tr=dom.ce("tr");tbody.appendChild(tr);var rowData=rows[i];var cellsInRow=rowData.length;for (var j=0; j < rows[i].length; j++){var cellData=rows[i][j];var td=dom.ce("td");tr.appendChild(td);if (j==rows[i].length -1 && cellsInRow < mostCells){td.colSpan=(mostCells-cellsInRow)+1;}if (typeof cellData=="string"){td.appendChild(dom.tx(cellData));}else if (PXN8.isArray(cellData)){for (var k=0; k < cellData.length; k++){if (typeof cellData[k]=="string"){td.appendChild(dom.tx(cellData[k]));}else{td.appendChild(cellData[k]);}}}else{td.appendChild(cellData);}}}return result;};PXN8.dom.createFlag=function(x,y,id){var flag=PXN8.dom.ce("img",{"src": PXN8.root+"images/icons/flag.gif", "id": id});document.body.appendChild(flag);flag.style.position="absolute";flag.style.top=y-16+"px";flag.style.left=x-11+"px";return flag;};var PXN8=PXN8 || {};PXN8.tools={};PXN8.tools.history=function (offset){if (offset==0){return;}if (PXN8.isUpdating()){alert (PXN8.strings.IMAGE_UPDATING);return;}var theImage=PXN8.dom.id("pxn8_image");if (!theImage){alert("Please wait for the image to load");return;}if (!offset) offset=-1;if (PXN8.opNumber==0 && offset < 0){PXN8.show.alert(PXN8.strings.NO_MORE_UNDO);return;}if (PXN8.opNumber==PXN8.maxOpNumber && offset > 0){PXN8.show.alert(PXN8.strings.NO_MORE_REDO);return;}if (offset < 0){var userOp=PXN8.getUserOperation(PXN8.opNumber);PXN8.show.alert("- "+userOp.operation, 500);}else{var userOp=PXN8.getUserOperation(PXN8.opNumber+1);PXN8.show.alert("+ "+userOp.operation,500);}var index=PXN8.opNumber+offset;var currentImageData=PXN8.images[index];if (!currentImageData){alert("Error! PXN8.images["+index+"] is undefined");return false;}PXN8.opNumber=index;PXN8.image.location=currentImageData.location;PXN8.image.width=currentImageData.width;PXN8.image.height=currentImageData.height;PXN8.listener.notify(PXN8.BEFORE_IMAGE_CHANGE,null);PXN8.unselect();PXN8.replaceImage(PXN8.image.location);return false;};PXN8.tools.undo=function(){PXN8.tools.history(-1);return false;};PXN8.tools.redo=function(){PXN8.tools.history(+1);return false;};PXN8.tools.undoall=function(){PXN8.tools.history(0-PXN8.opNumber);return false;};PXN8.tools.redoall=function(){PXN8.tools.history(PXN8.maxOpNumber-PXN8.opNumber);return false;};PXN8.tools.updateImage=function(ops){var theImage=PXN8.dom.id("pxn8_image");if (!PXN8.ready){alert("Please wait for the image to load");return;}if (PXN8.isUpdating()){alert (PXN8.strings.IMAGE_UPDATING);return;}PXN8.listener.notify(PXN8.BEFORE_IMAGE_CHANGE,ops);PXN8.addOperations(ops);};PXN8.tools.startTransaction=function(){PXN8.tools.transactionCache=new Array();PXN8.tools.commit=PXN8.tools.updateImage;PXN8.tools.updateImage=PXN8.tools.cacheUpdates;};PXN8.tools.cacheUpdates=function(ops){for (var i =0; i < ops.length; i++){PXN8.tools.transactionCache.push(ops[i]);}};PXN8.tools.endTransaction=function(){PXN8.tools.updateImage=PXN8.tools.commit;PXN8.tools.updateImage(PXN8.tools.transactionCache);};PXN8.tools.enhance=function(){PXN8.tools.updateImage([{operation: "enhance"}]);};PXN8.tools.normalize=function(){PXN8.tools.updateImage([{operation: "normalize"}]);};PXN8.tools.instantFix=function(){PXN8.tools.updateImage([ {operation: "normalize"},{operation: "enhance"}]);};PXN8.tools.spiritlevel=function(x1,y1,x2,y2){var opposite=y1 > y2 ? y1-y2:y2-y1;var adjacent=x1 > x2 ? x1-x2:x2-x1;var hypotenuse=Math.sqrt((opposite*opposite)+(adjacent*adjacent));var sineratio=opposite / hypotenuse;var RAD2DEG=57.2957795;var rads=Math.atan2(sineratio,Math.sqrt(1-(sineratio*sineratio)));var degrees=rads*RAD2DEG;if (y1 < y2){degrees=360-degrees;}PXN8.tools.rotate ({angle: degrees});return degrees;};PXN8.tools.spiritlevel_mode={};PXN8.tools.spiritlevel_mode.clicks=[];PXN8.tools.spiritlevel_mode.callback=null;PXN8.tools.spiritlevel_mode.start=function(callback){var _=PXN8.dom;var img=_.id("pxn8_image");var iw=img.width / PXN8.zoom.value();var ih=img.height / PXN8.zoom.value();var sel=_.id("pxn8_select_rect");sel.style.cursor="pointer";PXN8.crosshairs.setEnabled(false);PXN8.resize.enable(["n","s","e","w","ne","se","nw","sw"],false);PXN8.select({top:0,left:0,width: iw/2,height: ih});PXN8.event.addListener(sel,"click",this.onclick);this.callback=callback;};PXN8.tools.spiritlevel_mode.end=function(){var _=PXN8.dom;var pin1=_.id('pxn8_flag_0');if (pin1){document.body.removeChild(pin1);}var pin2=_.id('pxn8_flag_1');if (pin2){document.body.removeChild(pin2);}PXN8.unselect();var sel=_.id("pxn8_select_rect");sel.style.cursor="move";PXN8.crosshairs.setEnabled(true);PXN8.resize.enable(["n","s","e","w","ne","se","nw","sw"],true);PXN8.event.removeListener(sel,"click",this.onclick);this.clicks=[];};PXN8.tools.spiritlevel_mode.onclick=function(event){var _=PXN8.dom;var self=PXN8.tools.spiritlevel_mode;var img=_.id("pxn8_image");var iw=img.width / PXN8.zoom.value();var ih=img.height / PXN8.zoom.value();var sel=_.id("pxn8_select_rect");var pos=_.cursorPos(event);var flag=PXN8.dom.createFlag(pos.x,pos.y,"pxn8_flag_"+self.clicks.length);self.clicks.push(pos);PXN8.select({top:0,left:iw/2,width: iw/2,height: ih});if (self.clicks.length==2){PXN8.event.removeListener(sel,"click",self.onclick);PXN8.tools.spiritlevel(self.clicks[0].x,self.clicks[0].y,self.clicks[1].x,self.clicks[1].y);var oldSize=PXN8.dom.eb("pxn8_image");PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){self.end();var newSize=PXN8.dom.id("pxn8_image");var hdiff=newSize.height-oldSize.height;var wdiff=newSize.width-oldSize.width;PXN8.select(wdiff,hdiff,oldSize.width-wdiff,oldSize.height-hdiff);self.callback();});}};PXN8.tools.rotate=function(params){var operation={"operation":"rotate", angle: 0, "fliphz": false, "flipvt": false };if (params){for (var i in params){operation[i]=params[i];}}if (!params){operation.angle=90;}if (operation.angle > 0 || operation.flipvt || operation.fliphz){PXN8.tools.updateImage([operation]);}};PXN8.tools.blur=function (params){params.operation="blur";PXN8.tools.updateImage([params]);};PXN8.tools.colors=function(param){if (!param.saturation) param.saturation=100;if (!param.brightness) param.brightness=100;if (!param.hue) param.hue=100;if (!param.contrast) param.contrast=0;param.operation="colors";PXN8.tools.updateImage([param]);};PXN8.tools.crop=function (params){if (!params){params=PXN8.getSelection();}var operation={operation: "crop"};for (var i in params){operation[i]=params[i];}if (operation.width <= 0 || operation.height <= 0){PXN8.show.alert(PXN8.strings.CROP_SELECT_AREA);return;}PXN8.tools.updateImage([operation]);};PXN8.tools.previewCrop=function (timeout){timeout=timeout || 3500;var preview=function(borderColor,borderOpacity,handleOpacity){var _=PXN8.dom;var rects=["left","right","top","bottom","topleft","topright","bottomleft","bottomright"];for (var i=0;i < rects.length; i++){var rect=_.id("pxn8_"+rects[i]+"_rect");rect.style.backgroundColor=borderColor;_.opacity(rect,borderOpacity);}for (var i in PXN8.resize.handles){if (typeof PXN8.resize.handles[i] != "function"){var handle=_.id( i+"_handle");_.opacity(handle,handleOpacity);}}};preview("white",1.00,0);setTimeout(function(){var _=PXN8.style.notSelected;preview(_.color,_.opacity,1.00);},timeout);};PXN8.tools.preview_crop=PXN8.tools.previewCrop;PXN8.tools.filter=function (params){params.color=params.color;params.operation="filter";PXN8.tools.updateImage([params]);};PXN8.tools.interlace=function(params){params.color=params.color;params.operation="interlace";PXN8.tools.updateImage([params]);};PXN8.tools.lomo=function(params){params.operation="lomo";PXN8.tools.updateImage([params]);};PXN8.tools.fillFlash=function(opacity){var operation={operation: "fill_flash"};if (opacity){operation.opacity=Math.max(0,Math.min(100,opacity));}else{operation.opacity=50;}PXN8.tools.updateImage([operation]);};PXN8.tools.fill_flash=PXN8.tools.fillFlash;PXN8.tools.snow=function (){PXN8.tools.overlay({filepath: "images/overlays/snowflakes.png", tile: "true"});};PXN8.tools.overlay=function(params){params.operation="overlay";PXN8.tools.updateImage([params]);};PXN8.tools.addText=function(params){params.operation="add_text";params.fill=params.fill;params.text=params.text.replace(/\"/g,"\\\"");PXN8.tools.updateImage([params]);};PXN8.tools.add_text=PXN8.tools.addText;PXN8.tools.whiten=function (params){if (!params){params=PXN8.getSelection();}if (params.width==0 || params.height==0){return;}params.operation="whiten";PXN8.tools.updateImage([params]);};PXN8.tools.fixredeye=function(params){if (!params){params=PXN8.getSelection();}if (PXN8.isArray(params)){for (var i=0;i < params.length; i++){params[i].operation="fixredeye";}PXN8.tools.updateImage(params);}else{params.operation="fixredeye";PXN8.tools.updateImage([params]);}};PXN8.tools.resize=function(width, height){PXN8.tools.updateImage([{"operation": "resize", "width": width, "height": height}]);};PXN8.tools.roundedCorners=function(color, radius){PXN8.tools.updateImage([{"operation":"roundcorners","color": color,"radius":radius}]);};PXN8.tools.roundedcorners=PXN8.tools.roundedCorners;PXN8.tools.sepia=function(color){PXN8.tools.updateImage([{"operation":"sepia","color": color}]);};PXN8.tools.grayscale=function(){PXN8.tools.updateImage([{"operation":"grayscale"}]);};PXN8.tools.charcoal=function(radius){PXN8.tools.updateImage([{"operation":"charcoal", "radius":radius}]);};PXN8.tools.oilpaint=function(radius){PXN8.tools.updateImage([{"operation":"oilpaint", "radius":radius}]);};PXN8.tools.unsharpmask=function(params){var operation={"operation": "unsharpmask"};if (params){for (var i in params){operation[i]=params[i];}}PXN8.tools.updateImage([operation]);};PXN8.tools.fetch=function(params){var operation={"operation":"fetch"};if (params){for (var i in params){operation[i]=params[i];}}PXN8.tools.updateImage([operation]);};PXN8.tools.hi_res=function(hires_params,callback){var script=PXN8.getScript();var fetchOp=script[0];var hires_script=[fetchOp];var proxyOp={operation: "proxy"};for (var i in fetchOp){if (i != "operation"){proxyOp[i]=fetchOp[i];}}proxyOp.timestamp=new Date().getTime();hires_script.push(proxyOp);for (var i in hires_params){fetchOp[i]=hires_params[i];}for (var i=1; i < script.length; i++){hires_script.push(script[i]);}PXN8.prepareForSubmit(PXN8.strings.SAVING_HI_RES);PXN8.ajax.submitScript(hires_script,function(jsonResponse){var timer=document.getElementById("pxn8_timer");if (timer){timer.style.display="none";}PXN8.updating=false;callback(jsonResponse);});};PXN8.tools.mask=function(params){var operation={"operation":"mask"};if (params){for (var i in params){operation[i]=params[i];}}PXN8.tools.updateImage([operation]);};PXN8.tools.rearrange=function(params){var operation={"operation":"rearrange"};if (!params){alert(PXN8.strings.INVALID_PARAMETER+" (null) ");return;}operation.pieces=params;PXN8.tools.updateImage([operation]);};PXN8.tools.transparent=function (params){params.__extension=".png";params.operation="transparent";PXN8.tools.updateImage([params]);};var PXN8=PXN8 || {};PXN8.ON_HIRES_COMPLETE="ON_HIRES_COMPLETE";PXN8.ON_HIRES_BEGIN="ON_HIRES_BEGIN";PXN8.hires={originalURL: "",responses:[],jsonCallback:function(jsonResponse){PXN8.listener.notify(PXN8.ON_HIRES_COMPLETE,jsonResponse);}};PXN8.hires.scaleScript=function(script,ratio){var paramsToScale=["left","width","top","height","radius"];for (var i=0;i < script.length; i++){var op=script[i];for (var j=0; j < paramsToScale.length; j++){var attr=paramsToScale[j];if (op[attr]){op[attr]=op[attr]*ratio;}}}};PXN8.hires.doImageChange=function(eventType){var loRes=PXN8.images[0];var ratio=PXN8.hires.responses[0].height / loRes.height;var script=PXN8.getScript();PXN8.hires.interpolate(script,PXN8.hires.originalURL,ratio);};PXN8.hires.interpolate=function(originalScript,hiresImageURL,ratio){originalScript[0].image=hiresImageURL;PXN8.hires.scaleScript(originalScript,ratio);PXN8.listener.notify(PXN8.ON_HIRES_BEGIN);var opNumberWas=PXN8.opNumber;PXN8.ajax.submitScript(originalScript,function(jsonResponse){jsonResponse.initOpNumber=opNumberWas;PXN8.hires.jsonCallback(jsonResponse);});};PXN8.hires.init=function(imageUrl){PXN8.listener.add(PXN8.ON_HIRES_COMPLETE,function(eventType,jsonResponse){PXN8.hires.responses[jsonResponse.initOpNumber]=jsonResponse;});PXN8.hires.originalURL=imageUrl;var fetch={operation: "fetch",image: imageUrl,pxn8root: PXN8.root,random: Math.random()};PXN8.listener.notify(PXN8.ON_HIRES_BEGIN);var opNumberWas=PXN8.opNumber;PXN8.ajax.submitScript([fetch],function(jsonResponse){jsonResponse.initOpNumber=opNumberWas;PXN8.hires.jsonCallback(jsonResponse);});PXN8.listener.add(PXN8.ON_IMAGE_CHANGE,PXN8.hires.doImageChange);PXN8.getUncompressedImage=PXN8.hires.getUncompressedImage;};PXN8.hires.getUncompressedImage=function(){var result=false;if (PXN8.hires.responses[PXN8.opNumber]){result=PXN8.hires.responses[PXN8.opNumber].uncompressed;}return result;};var PXN8=PXN8 || {};PXN8.strings={};PXN8.strings.NO_MORE_REDO="No more operations left to redo!";PXN8.strings.NO_MORE_UNDO="No operations left to undo!";PXN8.strings.NO_MORE_ZOOMIN="Cannot zoom-in any further!";PXN8.strings.NO_MORE_ZOOMOUT="Cannot zoom-out any further!";PXN8.strings.MUST_UPGRADE_IE="You must upgrade to Internet Explorer 6.0 to use PXN8";PXN8.strings.WEB_SERVER_ERROR="Web server error:";PXN8.strings.IMAGE_ON_ERROR1="An error occured while attempting to load ";PXN8.strings.IMAGE_ON_ERROR2="\nPlease check the URL is correct and try again";PXN8.strings.NO_CONFIG_CONTENT="ERROR: no config_content element is defined in your html template";PXN8.strings.CONFIG_BLUR_TOOL="Configure Blur tool";PXN8.strings.BLUR_PROMPT="Enter a value in the range 1 to 8 for blur radius. A larger radius results in a more blurred image.";PXN8.strings.BLUR_RANGE="Blur radius must be in the range 1-8";PXN8.strings.RADIUS_LABEL="Radius:";PXN8.strings.BRIGHTNESS_RANGE="Enter a percentage value for brightness";PXN8.strings.HUE_RANGE="Hue must be in the range 0-200";PXN8.strings.SATURATION_RANGE="Enter a percentage value for saturation";PXN8.strings.CONFIG_CROP_TOOL="Configure Crop Tool";PXN8.strings.CONFIG_COLOR_TOOL="Change colors ";PXN8.strings.CONFIG_FILTER_TOOL="Configure Lens Filter";PXN8.strings.FILTER_PROMPT="Click on the image and a graduated filter of the selected color (and opacity) will be overlayed on top of the image";PXN8.strings.CONFIG_INTERLACE_TOOL= "Configure Interlace Effect";PXN8.strings.INTERLACE_PROMPT="Creates an interlaced overlay above the image making it appear like a grab from a TV screen.";PXN8.strings.INVALID_HEX_VALUE="You must enter a hexadecimal color value or choose one from the color palette";PXN8.strings.CONFIG_LOMO_TOOL="Configure Lomo Effect";PXN8.strings.OPACITY_PROMPT="Low opacity means darker corners. High opacity means lighter corners.";PXN8.strings.OPACITY_RANGE="Opacity must be in the range 0-100";PXN8.strings.WHITEN_SELECT_AREA="You must first select the area of the image you wish to whiten";PXN8.strings.CONFIG_WHITEN_TOOL="Configure Teeth Whitening";PXN8.strings.CROP_SELECT_AREA="You must first select the area of the image you wish to crop";PXN8.strings.RESIZE_SELECT_AREA="You must first select an area to resize to.";PXN8.strings.RESIZE_SELECT_LABEL="Resize to selected area.";PXN8.strings.SELECT_SMALLER_AREA="Please select a smaller area";PXN8.strings.REDEYE_SELECT_AREA="You must first select the area you wish to fix";PXN8.strings.REDEYE_SMALLER_AREA="Please select a smaller area to fix (less than 100x100)";PXN8.strings.CONFIG_REDEYE_TOOL="Fix Red Eye";PXN8.strings.REDEYE_PROMPT="To fix red-eye, select the affected area (begining at the top left corner and centering the cross-hairs on the iris) and click the 'Apply' button or press 'Enter'.";PXN8.strings.NUMERIC_WIDTH_HEIGHT="You must specify a numeric value for new width and height";PXN8.strings.LIMIT_SIZE="You can't resize larger than ";PXN8.strings.ASPECT_LABEL="Preserve aspect ratio: ";PXN8.strings.ASPECT_CROP_LABEL="Aspect ratio: ";PXN8.strings.CROP_FREE="free select";PXN8.strings.CROP_SQUARE="(square)";PXN8.strings.WIDTH_LABEL="Width: ";PXN8.strings.HEIGHT_LABEL="Height: ";PXN8.strings.FLIPVT_LABEL="Flip vertically: ";PXN8.strings.FLIPHZ_LABEL="Flip horizontally: ";PXN8.strings.ANGLE_LABEL="Angle: ";PXN8.strings.OPACITY_LABEL="Opacity: ";PXN8.strings.CONTRAST_NORMAL="Normal ";PXN8.strings.COLOR_LABEL="Color: ";PXN8.strings.SEPIA_LABEL="Sepia";PXN8.strings.SATURATE_LABEL="Saturate :";PXN8.strings.GRAYSCALE_LABEL="Grayscale";PXN8.strings.ORIENTATION_LABEL="Orientation: ";PXN8.strings.CONFIG_RESIZE_TOOL="Resize Image";PXN8.strings.CONFIG_ROTATE_TOOL="Rotate or Flip Image";PXN8.strings.SPIRIT_LEVEL_PROMPT1="Please click on the left half of the crooked horizon.";PXN8.strings.SPIRIT_LEVEL_PROMPT2="OK. Now click on the right half of the crooked horizon.";PXN8.strings.CONFIG_SPIRITLVL_TOOL="Spirit-level Mode";PXN8.strings.CONFIG_ROUNDED_TOOL="Configure Rounded Corners";PXN8.strings.CONFIG_BW_TOOL="Configure Sepia or Black & White";PXN8.strings.ORIENTATION_PORTRAIT="Portrait";PXN8.strings.ORIENTATION_LANDSCAPE="Landscape";PXN8.strings.PROMPT_ROTATE_CHOICE="Please specify an angle of rotation or flip orientation";PXN8.strings.BW_PROMPT="Turn your photograph into black & white or add a sepia tone.";PXN8.strings.IMAGE_UPDATING="The image is currently updating.\nPlease wait for the current operation to complete.";PXN8.strings.BRIGHTNESS_LABEL="brightness";PXN8.strings.SATURATION_LABEL="saturation";PXN8.strings.CONTRAST_LABEL="contrast";PXN8.strings.HUE_LABEL="hue";PXN8.strings.UPDATING="Updating image. Please wait...";PXN8.strings.CONFIG_OILPAINT_TOOL="Apply Oil-Painting Filter";PXN8.strings.CONFIG_CHARCOAL_TOOL="Apply Charcoal Filter";PXN8.strings.SAVING_HI_RES="Saving High-Resolution image. Please wait a moment...";PXN8.strings.INVALID_PARAMETER="Invalid parameter passed to function.";PXN8.strings.RESET="Reset";var PXN8=PXN8 || {};PXN8.crosshairs={};PXN8.crosshairs.enabled=true;PXN8.crosshairs.image=null;PXN8.crosshairs.setEnabled=function(enabled){PXN8.crosshairs.enabled=enabled;PXN8.crosshairs.refresh();};PXN8.crosshairs.isEnabled=function(){return PXN8.crosshairs.enabled;};PXN8.crosshairs.getImage=function(){if (PXN8.crosshairs.image==null){PXN8.crosshairs.image=PXN8.server+PXN8.root+"/images/pxn8_xhairs_white.gif";}return PXN8.crosshairs.image;};PXN8.crosshairs.setImage=function(imageURL){PXN8.crosshairs.image=imageURL;PXN8.crosshairs.refresh();};PXN8.crosshairs.refresh=function(){var _=PXN8.dom;var xhairs=_.id("pxn8_crosshairs");if (!PXN8.crosshairs.isEnabled()){if (xhairs){xhairs.style.display="none";}return;}var sel=PXN8.getSelection();var _=PXN8.dom;var selBounds=_.eb("pxn8_select_rect");var canvas=_.id("pxn8_canvas");if (!xhairs){xhairs=_.ac(canvas,_.ce("img",{id: "pxn8_crosshairs", src: PXN8.crosshairs.getImage()}));}if (selBounds.width <= 0){xhairs.style.display="none";return;}var xhcx=xhairs.width/2;var xhcy=xhairs.height/2;xhairs.style.display="inline";xhairs.style.position="absolute";xhairs.style.left=Math.floor((selBounds.x+(selBounds.width / 2))-xhcx)+"px";xhairs.style.top=Math.floor((selBounds.y+(selBounds.height / 2))-xhcy)+"px";};PXN8.listener.add(PXN8.ON_SELECTION_CHANGE,PXN8.crosshairs.refresh);PXN8.listener.add(PXN8.ON_ZOOM_CHANGE,PXN8.crosshairs.refresh);PXN8=PXN8 || {};PXN8.preview={};PXN8.preview._div_to_intervalid={};PXN8.preview.initialize=function(elementId,preview_method){if (!preview_method){preview_method="crop";}if (preview_method=="crop" || preview_method=="resize"){}else{alert("Invalid preview method provided-use either 'crop' or 'resize'");return;}try {document.execCommand('BackgroundImageCache', false, true);} catch(e) {}PXN8.event.removeListener(elementId,"mousedown");PXN8.event.removeListener(elementId,"mouseup");PXN8.event.removeListener(elementId,"mousemove");var oldIntervalId=PXN8.preview._div_to_intervalid[elementId];if (oldIntervalId){clearInterval(oldIntervalId);}var result={};var element=PXN8.dom.id(elementId);if (!element){return false;}result._preview_method=preview_method;result._element=element;result._sizeX=parseInt(element.style.width);result._sizeY=parseInt(element.style.height);result._offset={x: 0, y: 0};result._op=false;result._opQueue=[];result._intervalId=0;result._beginDrag={x: 0, y: 0};result._endDrag={x: 0, y: 0};result._mouseDownCoords={};result._mouseUpCoords={};result._mouseDown=PXN8.event.closure(result,PXN8.preview._innerMouseDown);result._mouseUp=PXN8.event.closure(result,PXN8.preview._innerMouseUp);result._mouseMove=PXN8.event.closure(result,PXN8.preview._innerMouseMove);var img=PXN8.dom.id("pxn8_image");if (img){var real_image_width=img.width / PXN8.zoom.value();var real_image_height=img.height / PXN8.zoom.value();result._fullsize_ratio=Math.ceil(Math.max(real_image_height/result._sizeY, real_image_width/result._sizeX));PXN8.preview.centerOffset(result);}else{result._fullsize_ratio=-1;}result._intervalId=setInterval(function(){PXN8.preview._manageQueue(result);},750);PXN8.preview._div_to_intervalid[elementId]=result._intervalId;PXN8.event.addListener(elementId,"mousedown",result._mouseDown);return result;};PXN8.preview.setOffset=function(object,x,y){var img=PXN8.dom.id("pxn8_image");var iw=img.width / PXN8.zoom.value();var ih=img.height / PXN8.zoom.value();var maxY=ih-object._sizeY;var maxX=iw-object._sizeX;if (x < 0){ x=0; }if (y < 0){ y=0; }if (y > maxY) { y=maxY;}if (x > maxX) { x=maxX;}object._offset.x=x;object._offset.y=y;PXN8.preview._refresh(object);};PXN8.preview.centerOffset=function(object){var _=PXN8.dom;var image=_.id("pxn8_image");var iw=image.width / PXN8.zoom.value();var ih=image.height / PXN8.zoom.value();var halfW=object._sizeX / 2;var halfH=object._sizeY / 2;PXN8.preview.setOffset(object,Math.round((iw/2)-halfW), Math.round((ih/2)-halfH));};PXN8.preview.show=function(object,op){var _=PXN8.dom;if (!object._element){return;}if (object._element.style.display=="none"){object._element.style.display="block";}if (op){ object._op=op; }if (op){PXN8.preview._enqueue(object);}};PXN8.preview.hide=function(object){if (object._element){object._element.innerHTML="";object._element.style.display="none";}object._op=false;clearInterval(object._intervalId);PXN8.event.removeListener(object._element,"mousedown",object._mouseDown);PXN8.event.removeListener(object._element,"mousemove",object._mouseMove);PXN8.event.removeListener(object._element,"mouseup",object._mouseUp);};PXN8.preview._enqueue=function(object){object._opQueue.push(object._op);};PXN8.preview._complete=true;PXN8.preview._getOffset=function(object){return {x: object._offset.x, y: object._offset.y};};PXN8.preview._manageQueue=function(object){var lastIndex=object._opQueue.length -1;if (lastIndex < 0){return;}if (!PXN8.preview._complete){return;}var _=PXN8.dom;var script=PXN8.getScript();var image=_.id("pxn8_image");if (!image){return;}PXN8.preview._complete=false;var op=object._opQueue[lastIndex];object._opQueue.length=0;var width=image.width / PXN8.zoom.value();var height=image.height / PXN8.zoom.value();var top=object._offset.y;var left=object._offset.x;var gridSize=100;var offsetTop=top % gridSize;var offsetLeft=left % gridSize;top=top-offsetTop;left=left-offsetLeft;var right=Math.min(width,left+(object._sizeX+gridSize));var bottom=Math.min(height, top+(object._sizeY+gridSize));var addedOps=[];var prepareOp=null;if (object._preview_method=="crop"){prepareOp={"operation":"crop", "top":top, "left":left, "width":right-left, "height":bottom-top, "__quality":100, "__uncompressed":0};}else{prepareOp={"operation":"resize", "width":right-left, "height":bottom-top};}if (width > object._sizeX && height > object._sizeY){addedOps.push(prepareOp);}var opsFromQueue=[];if (PXN8.isArray(op)){opsFromQueue=op;}else{opsFromQueue.push(op);}for (var i=0;i < opsFromQueue.length; i++){var opFromQueue=opsFromQueue[i];if (opFromQueue["__quality"]==null){opFromQueue.__quality=65;}opFromQueue.__uncompressed=0;addedOps.push(opFromQueue);}object._element.innerHTML='<span class="pxn8_preview_update">Please wait...</span>';var cachedImage=PXN8.getUncompressedImage();if (cachedImage){script=[{"operation": "cache", "image":cachedImage}];}for (var i=0;i < addedOps.length; i++){script.push(addedOps[i]);}PXN8.ajax.submitScript(script, function(jsonResponse){PXN8.preview._complete=true;_.cl(object._element);if (jsonResponse.status=="ERROR"){alert(jsonResponse.errorMessage);return;}if (!jsonResponse){return;}var prevImgURL=PXN8.server+PXN8.root+"/"+jsonResponse.image;object._element.style.backgroundImage="url("+prevImgURL+")";var position=(offsetLeft*-1)+"px "+(offsetTop*-1)+"px";object._element.style.backgroundPosition=position;});};PXN8.preview._refresh=function(object){var _=PXN8.dom;if (!object._element){return;}var position=(object._offset.x*-1)+"px "+(object._offset.y*-1)+"px";var image=_.id("pxn8_image");object._element.style.backgroundPosition=position;object._element.style.backgroundImage="url("+image.src+")";object._element.style.cursor="move";object._element.style.backgroundRepeat="no-repeat";};PXN8.preview._innerMouseMove=function(event,object,source){var _=PXN8.dom;object._endDrag=_.cursorPos(event);var offset=PXN8.preview._getOffset(object);var xdiff=object._beginDrag.x-object._endDrag.x;var ydiff=object._beginDrag.y-object._endDrag.y;if (object._fullsize_ratio==-1){var img=PXN8.dom.id("pxn8_image");if (img){var real_image_width=img.width / PXN8.zoom.value();var real_image_height=img.height / PXN8.zoom.value();object._fullsize_ratio=Math.ceil(Math.max(real_image_height/object._sizeY, real_image_width/object._sizeX));}}offset.x += xdiff*object._fullsize_ratio;offset.y += ydiff*object._fullsize_ratio;PXN8.preview.setOffset(object,offset.x,offset.y);object._beginDrag=object._endDrag;};PXN8.preview._innerMouseUp=function(event,object,source){PXN8.event.removeListener(object._element,"mouseup",object._mouseUp);PXN8.event.removeListener(object._element,"mouseout",object._mouseUp);PXN8.event.removeListener(object._element,"mousemove",object._mouseMove);PXN8.preview.show(object,object._op);};PXN8.preview._innerMouseDown=function(event,object,source){var _=PXN8.dom;var img=_.id("pxn8_image");object._element.style.backgroundImage="url("+img.src+")";PXN8.preview._refresh(object);object._beginDrag=_.cursorPos(event);object._mouseDownCoords=_.cursorPos(event);PXN8.event.addListener(object._element,"mouseup",object._mouseUp);PXN8.event.addListener(object._element,"mouseout",object._mouseUp);PXN8.event.addListener(object._element,"mousemove",object._mouseMove);};var PXN8=PXN8 || {};PXN8.overlay={};PXN8.overlay.start=function(overlayURL,dimensions){PXN8.overlay.stop();if (dimensions==undefined){dimensions=PXN8.getSelection();}var rects=["top","bottom","left","right","topright","topleft","bottomleft","bottomright"];for (var i=0;i < rects.length; i++){PXN8.dom.opacity("pxn8_"+rects[i]+"_rect",0);}var img=document.getElementById("pxn8_image");var iw=img.width / PXN8.zoom.value();var ih=img.height / PXN8.zoom.value();if (dimensions.top==undefined && dimensions.left==undefined){dimensions.top=(ih/2)-(dimensions.height / 2);dimensions.left=(iw/2)-(dimensions.width / 2);}PXN8.select(dimensions);var canvas=PXN8.dom.id("pxn8_canvas");var overlayEl=PXN8.dom.id("pxn8_overlay");if (overlayURL.indexOf(".png") > -1 && PXN8.browser.isIE6()){canvas.removeChild(overlayEl);overlayEl=null;}if (overlayEl==null){overlayEl=PXN8.dom.ce("img", {id: "pxn8_overlay"});overlayEl.style.position="absolute";canvas.appendChild(overlayEl);}if (overlayURL.indexOf(".png") > -1 && PXN8.browser.isIE6()){overlayEl.onload=function(){PXN8.overlay.fixPNG(overlayEl);};}overlayEl.src=overlayURL;PXN8.overlay.show();PXN8.listener.add(PXN8.ON_SELECTION_CHANGE,PXN8.overlay.show);PXN8.listener.add(PXN8.ON_ZOOM_CHANGE, PXN8.overlay.show);PXN8.crosshairs.setEnabled(false);};PXN8.overlay.stop=function(){var rects=["top","bottom","left","right","topright","topleft","bottomleft","bottomright"];for (var i=0;i < rects.length; i++){PXN8.dom.opacity("pxn8_"+rects[i]+ "_rect",PXN8.style.notSelected.opacity);}PXN8.listener.remove(PXN8.ON_SELECTION_CHANGE,PXN8.overlay.show);PXN8.listener.remove(PXN8.ON_ZOOM_CHANGE, PXN8.overlay.show);var overlay=document.getElementById("pxn8_overlay");if (overlay){overlay.style.display="none";}PXN8.selectByRatio("free");PXN8.crosshairs.setEnabled(true);};PXN8.overlay.show=function (){var overlay=document.getElementById("pxn8_overlay");var sel=PXN8.getSelection();var zoom=PXN8.zoom.value();overlay.style.display="block";overlay.style.top=(sel.top*zoom)+"px";overlay.style.left=(sel.left*zoom)+"px";overlay.width=sel.width*zoom;overlay.height=sel.height*zoom;overlay.style.width=sel.width*zoom+"px";overlay.style.height=sel.height*zoom+"px";};PXN8.overlay.fixPNG=function(img){if (!PXN8.browser.isIE6()){return;}if (img.src.indexOf(".png")==-1){return;}var imgID=(img.id) ? "id='"+img.id+"' ":"";var imgClass=(img.className) ? "class='"+img.className+"' ":"";var imgTitle=(img.title) ? "title='"+img.title+"' ":"title='"+img.alt+"' ";var imgStyle="display:inline-block;"+img.style.cssText ;if (img.align=="left") imgStyle="float:left;"+imgStyle;if (img.align=="right") imgStyle="float:right;"+imgStyle;if (img.parentElement.href) imgStyle="cursor:hand;"+imgStyle;var strNewHTML="<span "+imgID+imgClass+imgTitle+" style=\""+"width:"+img.width+"px; height:"+img.height+"px;"+imgStyle+";";strNewHTML=strNewHTML+"filter:progid:DXImageTransform.Microsoft.AlphaImageLoader";strNewHTML=strNewHTML+"(src=\'"+img.src+"\', sizingMethod='scale');\"></span>" ;img.outerHTML=strNewHTML;};var PXN8=PXN8 || {};PXN8.slide={};PXN8.slide.bind=function(slideElement,inputElementId,startRange,rangeSize,initValue,increment,optionalCallback){if (!increment){increment=1;}if (typeof slideElement=='string'){slideElement=PXN8.dom.id(slideElement);}slideElement.className="pxn8_slide";slideElement.onmousedown=function(event){if (!event) event=window.event;PXN8.slide.onmousedown(slideElement,event,inputElementId,startRange,rangeSize,increment);};var slider=document.createElement("span");slider.className="pxn8_slider";slideElement.appendChild(slider);PXN8.slide.refresh_slider(slider,initValue,startRange,rangeSize);var inputElement=PXN8.dom.id(inputElementId);if (!inputElement){alert("ERROR: NO <input/> element was found with id=\""+inputElementId+"\"");return false;}inputElement.value=initValue;inputElement.onblur=function(){if (isNaN(this.value)){this.value=startRange;}if (this.value > startRange+rangeSize){this.value=startRange+rangeSize;}if (this.value < startRange){this.value=startRange;}PXN8.slide.refresh_slider(slider,this.value,startRange,rangeSize);};if (typeof optionalCallback=='function'){PXN8.event.addListener(slideElement,"mouseup",optionalCallback);PXN8.event.addListener(inputElement,"change",optionalCallback);}};PXN8.slide.refresh_slider=function(slider,value,startRange,rangeSize){slider.style.left=(3+(((value-startRange) / rangeSize)*117))+"px";};PXN8.slide.onmousedown=function(slide,event,inputId,start,size,increment){var kids=slide.getElementsByTagName("*");var slider=undefined;for (var i=0; i < kids.length; i++){if (kids[i].className=="pxn8_slider"){slider=kids[i];break;}}slider.onmousemove=null;var inputElement=document.getElementById(inputId);slide.onmousemove=function(evt){return PXN8.slide.update(slider,inputElement,slide,evt,start,size,increment);};slide.onmouseup=function(){slide.onmousemove=null;};PXN8.slide.update(slider,inputElement,slide,event,start,size,increment);};PXN8.slide.update=function(slider,inputElement,slide, evt,start,size,increment){evt=(evt)?evt:window.event;var px=PXN8.slide.position(slide);var nx=evt.clientX-px;if (nx <= 120 && nx >= 3){var iv=start+(((nx-3) / 117 )*size);iv=iv-(iv % increment);PXN8.slide.refresh_slider(slider,iv,start,size);inputElement.value=Math.round(iv,2);}};PXN8.slide.position=function (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;};var PXN8=PXN8 || {};PXN8.colors={};PXN8.colors.values=[
"#000000","#000033","#000066","#000099","#0000CC","#0000FF","#330000","#330033","#330066","#330099","#3300CC","#3300FF","#660000","#660033","#660066","#660099","#6600CC","#6600FF","#990000","#990033","#990066","#990099","#9900CC","#9900FF","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#003300","#003333","#003366","#003399","#0033CC","#0033FF","#333300","#333333","#333366","#333399","#3333CC","#3333FF","#663300","#663333","#663366","#663399","#6633CC","#6633FF","#993300","#993333","#993366","#993399","#9933CC","#9933FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#006600","#006633","#006666","#006699","#0066CC","#0066FF","#336600","#336633","#336666","#336699","#3366CC","#3366FF","#666600","#666633","#666666","#666699","#6666CC","#6666FF","#996600","#996633","#996666","#996699","#9966CC","#9966FF","#CC6600","#CC6633","#CC6666","#CC6699","#CC66CC","#CC66FF","#FF6600","#FF6633","#FF6666","#FF6699","#FF66CC","#FF66FF","#009900","#009933","#009966","#009999","#0099CC","#0099FF","#339900","#339933","#339966","#339999","#3399CC","#3399FF","#669900","#669933","#669966","#669999","#6699CC","#6699FF","#999900","#999933","#999966","#999999","#9999CC","#9999FF","#CC9900","#CC9933","#CC9966","#CC9999","#CC99CC","#CC99FF","#FF9900","#FF9933","#FF9966","#FF9999","#FF99CC","#FF99FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#66CC00","#66CC33","#66CC66","#66CC99","#66CCCC","#66CCFF","#99CC00","#99CC33","#99CC66","#99CC99","#99CCCC","#99CCFF","#CCCC00","#CCCC33","#CCCC66","#CCCC99","#CCCCCC","#CCCCFF","#FFCC00","#FFCC33","#FFCC66","#FFCC99","#FFCCCC","#FFCCFF","#00FF00","#00FF33","#00FF66","#00FF99","#00FFCC","#00FFFF","#33FF00","#33FF33","#33FF66","#33FF99","#33FFCC","#33FFFF","#66FF00","#66FF33","#66FF66","#66FF99","#66FFCC","#66FFFF","#99FF00","#99FF33","#99FF66","#99FF99","#99FFCC","#99FFFF","#CCFF00","#CCFF33","#CCFF66","#CCFF99","#CCFFCC","#CCFFFF","#FFFF00","#FFFF33","#FFFF66","#FFFF99","#FFFFCC","#FFFFFF"
];PXN8.colors.picker=function(initColor,callback){var _=PXN8.dom;var cols=18;var rows=Math.ceil(PXN8.colors.values.length/cols);var well=_.ce("div", {className:"pxn8_color_well"});well.style.backgroundColor=initColor;var input=_.ce("input",{className:"pxn8_color_value",type: "text",value: initColor});input.onchange=function(){var v=input.value;if (v.match(/#[0-9A-Fa-f]{6}/)){well.style.backgroundColor=v;callback(v);}else
{alert(PXN8.strings.INVALID_HEX_VALUE);}};var reset=_.ce("button",{ className:"pxn8_color_reset" });_.ac(reset,_.tx(PXN8.strings.RESET));reset.onclick=function(){well.style.backgroundColor=initColor;input.value=initColor;callback(initColor);};var closure=function(color,func){return function(){well.style.backgroundColor=color;input.value=color;func(color);};};var table=_.ce("table", {className: "pxn8_color_table"});table.setAttribute("cellpadding","0");table.setAttribute("cellspacing","0");table.cellPadding=0;table.cellSpacing=0; var row;var tbody=_.ac(table,_.ce("tbody"));for (var i=0;i < rows;i++){row=_.ac(tbody,_.ce("tr"));for (var j=0; j < cols; j++){var cell=_.ac(row,_.ce("td"));var index=(i*cols)+j;if (index < PXN8.colors.values.length){var color=PXN8.colors.values[index];var link=_.ce("a",{href: "#",title: color,onclick: closure(color,callback)});_.ac(link,_.tx(" "));link.style.backgroundColor=color;_.ac(cell,link);}}}var container=_.ce("div",{className: "pxn8_color_container"});var picker=_.ce("div",{className: "pxn8_color_picker"});_.ac(picker, well);_.ac(picker, input);_.ac(picker, reset);_.ac(container,table);_.ac(container,picker);return container;};var PXN8=PXN8 || {};PXN8.ImageMagick=function(){var id=PXN8.ImageMagick.objectCount++;if (id==0){this.handle="_";}else{this.handle="im"+id;}return this;};PXN8.ImageMagick.curry=function(methodName){return function(a) {var statement=new Array();statement.push(this.handle);statement.push(methodName);for (var i=0; i < arguments.length;i++){statement.push(arguments[i]);}PXN8.ImageMagick.statements.push(statement);};};PXN8.ImageMagick.prototype.Method=function(){var methodName=arguments[0];if (!PXN8.ImageMagick.prototype[methodName]){PXN8.ImageMagick.prototype[methodName]=PXN8.ImageMagick.curry(methodName);}var statement=new Array();statement.push(this.handle);for (var i=0; i < arguments.length;i++){statement.push(arguments[i]);}PXN8.ImageMagick.statements.push(statement);};PXN8.ImageMagick.prototype.Crop=function(coords){var _coords={x: (coords.left || coords.x),y: (coords.top || coords.y),width: coords.width,height: coords.height};this.Method("Crop",_coords);};PXN8.ImageMagick.prototype._CropToText=function ( textParams){this.Method("_CropToText", textParams) ;};PXN8.ImageMagick.prototype._ScaleTo=function (scaleParams){this.Method("_ScaleTo", scaleParams) ;};PXN8.ImageMagick.prototype.Clone=function(){var clone=new PXN8.ImageMagick();var statement=new Array();statement.push(clone.handle);statement.push("clone_from");statement.push(this.handle);PXN8.ImageMagick.statements.push(statement);return clone;};PXN8.ImageMagick.prototype.Append=function(stack){var appended=new PXN8.ImageMagick();var statement=new Array();statement.push(appended.handle);statement.push("append");statement.push([this.handle,stack]);PXN8.ImageMagick.statements.push(statement);return appended;};PXN8.ImageMagick.prototype.push=function(image){var statement=new Array();statement.push(this.handle);statement.push("push");statement.push(image.handle);PXN8.ImageMagick.statements.push(statement);return this;};PXN8.ImageMagick.start=function(){PXN8.ImageMagick.objectCount=0;var image=new PXN8.ImageMagick();PXN8.ImageMagick.statements=new Array();return image;};PXN8.ImageMagick.end=function(image,callback){var op={operation: "imagemagick"};op.script=PXN8.ImageMagick.statements;op.script.push([image.handle,"return"]);if (typeof callback=="undefined"){PXN8.tools.updateImage([op]);}else if (typeof callback=="boolean"){if (callback==true){PXN8.tools.updateImage([op]);}}else if (typeof callback=="function"){PXN8.ajax.submitScript([op],callback);}return op;};PXN8.ImageMagick.maskFromPaths=function(size, paths){var result=new PXN8.ImageMagick();result.Set({size: size.width+"x"+size.height});result.Read("xc:#000000");for (var i=0; i < paths.length; i++){var path=paths[i];var ps=PXN8.freehand.getPoints(path);result.Draw({stroke: "#ffffff", fill: "#00000000", primitive: "path", points: ps, strokewidth: path.width});}result.Set({matte: false});return result;};PXN8.ImageMagick.methods=["AdaptiveBlur","AdaptivelyResize","AdaptiveSharpen","AdaptiveThreshold","AddNoise","AffineTransform","Annotate","AutoOrient","Blur","Border","BlackThreshold","Charcoal","Colorize","Contrast","Composite","Draw","Edge","Emboss","Enhance","Extent","Flip","Flop","Frame","Gamma","GaussianBlur","Implode","Label","Level","Magnify","Mask","Minify","Modulate","MotionBlur","Negate","Normalize","OilPaint","Opaque","Posterize","Quantize","Raise","ReduceNoise","Resample","Read",,"Rotate","Resize","Roll","Set","SetPixel","Shadow","Sharpen","Shear","Sketch","Solarize","Spread","Stegano","Stereo","Strip","Swirl","Texture","Thumbnail","Threshold","Tint","Transparent","Transpose","Transverse","Trim","UnsharpMask","Vignette","Wave","WhiteThreshold"];for (var i=0; i < PXN8.ImageMagick.methods.length;i++){var method=PXN8.ImageMagick.methods[i];PXN8.ImageMagick.prototype[method]=PXN8.ImageMagick.curry(method);}PXN8=PXN8 || {};PXN8.freehand={};PXN8.freehand.color="#ff0000";PXN8.freehand.opacity=0;PXN8.freehand.width=1;PXN8.freehand.started=false;PXN8.freehand.start=function(){if (PXN8.log){ PXN8.log.trace("PXN8.freehand.start()"); }var _=PXN8.dom;if (!Raphael){alert("Warning: PXN8.freehand requires the Raphael Javascript Library");return;}if (PXN8.freehand.started){alert("Warning: PXN8.freehand has already started");return;}var self=PXN8.freehand;self.started=true;PXN8.unselect();var pos=_.ep("pxn8_canvas");var theImage=_.id("pxn8_image");var glassPane=_.ce("div",{id: "pxn8_freehand_glasspane"});_.css(glassPane,{top:pos.y+"px",left:pos.x+"px",position:"absolute" ,width:theImage.width,height:theImage.height,backgroundColor:"white",opacity:0.01,filter:"alpha(opacity:1)",cursor:"crosshair"});_.ac(document.body,glassPane);var raphaelContainer=_.ce("div",{id: "pxn8_raphael_container"});_.css(raphaelContainer,{position:"absolute",top:pos.y+"px",left:pos.x+"px"});_.ac(document.body, raphaelContainer);self.paper=Raphael("pxn8_raphael_container",theImage.width,theImage.height);self.oldmousemove=document.body.onmousemove;document.body.onmousemove=self.onmousemove;self.oldmousedown=document.body.onmousedown;self.oldmouseup=document.body.onmouseup;document.body.onmousedown=function(event){event=event || window.event;event.cancelBubble=true;self.mousedown=true;_.css("pxn8_raphael_container",{cursor: "crosshair"});};document.body.onmouseup=function(event){event=event || window.event;self.mousedown=false;_.css("pxn8_raphael_container",{cursor: "default"});};PXN8.listener.add(PXN8.ON_ZOOM_CHANGE,self.onZoomChange);};PXN8.freehand.onZoomChange=function(eventType,zoom){var self=PXN8.freehand;var sz=PXN8.getImageSize();PXN8.dom.id("pxn8_raphael_container").innerHTML="";self.paper=Raphael("pxn8_raphael_container",sz.width*zoom,sz.height*zoom);self.refresh();};PXN8.freehand.refresh=function(){var self=PXN8.freehand;var i=0;self.paper.clear();for (i=0;i < self.paths.length; i++){self.paths[i].refresh();}};PXN8.freehand.end=function(){if (PXN8.log){ PXN8.log.trace("PXN8.freehand.end()"); }var self=PXN8.freehand;if (!self.started){return;}self.started=false;self.activePath=null;self.paths=[];document.body.removeChild(document.getElementById("pxn8_freehand_glasspane"));document.body.removeChild(document.getElementById("pxn8_raphael_container"));document.body.onmousemove=self.oldmousemove;document.body.onmousedown=self.oldmousedown;document.body.onmouseup=self.oldmouseup;PXN8.listener.remove(PXN8.ON_ZOOM_CHANGE,self.onZoomChange);};PXN8.freehand.undo=function(){var self=PXN8.freehand;var lastPath=self.paths.pop();if (!lastPath){return;}lastPath.view.remove();};PXN8.freehand.count=0;PXN8.freehand.mousedown=false;PXN8.freehand.isDrawing=function(event){return PXN8.freehand.mousedown || event.button;};PXN8.freehand.onmousemove=function(event){event=event || window.event;var self=PXN8.freehand;if (!self.isDrawing(event)){self.count=0;return;}var canvasPos=PXN8.dom.ep("pxn8_canvas");var windowOffset=PXN8.getWindowScrollPoint();var cx=Math.floor(event.clientX-canvasPos.x+windowOffset.x);var cy=Math.floor(event.clientY-canvasPos.y+windowOffset.y);var theImage=document.getElementById("pxn8_image");if (cx < 0 || cx > theImage.width
|| cy < 0 || cy > theImage.height){self.count=0;return;}if (self.count != 0){PXN8.freehand.activePath.lineTo(cx,cy);}else
{self.count=2;PXN8.freehand.activePath=new PXN8.freehand.Path(
PXN8.freehand.width,PXN8.freehand.color,cx, cy, []);}};PXN8.freehand.activePath=null;PXN8.freehand.paths=[];PXN8.freehand.getPaths=function(){var result=[];var i=0;var path=null;for (i=0;i < PXN8.freehand.paths.length; i++){path=PXN8.freehand.paths[i];if (path.d.length > 2){result.push(path);}}return result;};PXN8.freehand.getPoints=function(path){var result=null;if (path.d.length > 2){result="M "+path.d[0]+" "+path.d[1]+" L";for (j=2; j < path.d.length; j=j+2){result += " "+path.d[j]+" "+path.d[j+1];}}return result;};PXN8.freehand.Path=function(width, color, x, y){var zoom=PXN8.zoom.value();this.d=[x / zoom, y / zoom];this.color=color;this.width=width;this.opacity=PXN8.freehand.opacity;this.view=PXN8.freehand.paper.path(
{stroke: color,"fill-opacity": this.opacity,"stroke-width":width*zoom});this.view.moveTo(x,y);this.view.lineTo(x,y);PXN8.freehand.paths.push(this);return this;};PXN8.freehand.Path.prototype.lineTo=function(x,y){this.view.lineTo(x,y);var zoom=PXN8.zoom.value();this.d.push(x / zoom,y / zoom);};PXN8.freehand.Path.prototype.refresh=function(){var x,y=0;var zoom=PXN8.zoom.value();x=this.d[0]*zoom;y=this.d[1]*zoom;var i=0;this.view=PXN8.freehand.paper.path(
{stroke: this.color,"fill-opacity":this.opacity,"stroke-width":this.width*zoom});this.view.moveTo(x,y);this.view.lineTo(x,y);for (i=2;i < this.d.length; i+=2){x=this.d[i]*zoom;y=this.d[i+1]*zoom;this.view.lineTo(x,y);}};PXN8.tools.freehand=function(paths){if (typeof paths=="undefined"){paths=PXN8.freehand.paths;}var i =0,j=0,path=null,ps="",p=null,image=null,end=0;var ops=[];if (PXN8.ajax.useXHR){var image=PXN8.ImageMagick.start();var paths=PXN8.freehand.getPaths();for (;i < paths.length;i++){path=paths[i];ps=PXN8.freehand.getPoints(path);image.Draw({stroke: path.color, fill: "#00000000", primitive: "path", points: ps, strokewidth: path.width});}PXN8.ImageMagick.end(image);}else
{var chunkedPaths=[];for (i=0; i < paths.length;i++){p=paths[i];j=p.d.length;var start=0;while (j > 0){end=Math.min(start+j,start+100);var tp={width: p.width, color: p.color, d:[]};tp.d=p.d.slice(start,end);chunkedPaths.push(tp);j=j-(end-start);start=end;}}for (i=0;i < chunkedPaths.length;i++){path=chunkedPaths[i];if (path.d.length > 2){image=PXN8.ImageMagick.start();ps=PXN8.freehand.getPoints(path);image.Draw({stroke: path.color, fill: "#00000000", primitive: "path", points: ps, strokewidth: path.width});ops.push(PXN8.ImageMagick.end(image,false));}}PXN8.tools.updateImage(ops);}};var PXN8=PXN8 || {};PXN8.ajax={};PXN8.ajax.useXHR=true;PXN8.ajax.createRequest=function(){if (typeof XMLHttpRequest != 'undefined') {return new XMLHttpRequest();}try {return new ActiveXObject("Msxml2.XMLHTTP");} catch (e) {try {return new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { }}return false;};PXN8.ajax.submitScript=function(script, callback){if (PXN8.log){PXN8.log.trace("PXN8.ajax.submitScript() ----- START -----");var s=PXN8.objectToString(script);PXN8.log.trace(s);PXN8.log.trace("PXN8.ajax.submitScript() ------ END ------");}var path, suffix, i, op, scriptToText, cachedJSON;var urlWithoutScript, url, scriptSizeLimit, bite, c;if (typeof (PXN8.convertToJPEG)=="boolean" && PXN8.convertToJPEG==false){suffix='.jpg';for (i =0;i < script.length; i++){op=script[i];if (op.operation=="fetch"){path=op.url || op.filepath;c=path.indexOf('?');if (c==-1){c=path.length;}suffix=path.substring(path.lastIndexOf('.'),c);break;}if (op.operation=="cache"){path=op.image;c=path.indexOf('?');if (c==-1){c=path.length;}suffix=path.substring(path.lastIndexOf('.'),c);break;}}for (i=0;i < script.length;i++){op=script[i];if (!op.__extension){op.__extension=suffix;}else{suffix=op.__extension;}}}suffix='';for (i=0;i < script.length; i++){op=script[i];if (op.__extension){suffix=op.__extension;}else{if (suffix != ''){op.__extension=suffix;}}}script=PXN8.optimizeScript(script);scriptToText=escape(PXN8.objectToString(script));cachedJSON=PXN8.json.getResponseForScript(scriptToText);if (cachedJSON){callback(cachedJSON);return;}if (PXN8.ajax.useXHR==false){urlWithoutScript=PXN8.server+PXN8.root+"/"+PXN8.basename+"?callback=pxn8cb&script=";url=urlWithoutScript+scriptToText;scriptSizeLimit=2048-urlWithoutScript.length;if (scriptToText.length > scriptSizeLimit){bite="[";c=0;i=0;for (;i < script.length; i++){var optext=escape(PXN8.objectToString(script[i]));if (bite.length+optext.length < scriptSizeLimit){bite=bite+(i>0?",":"");bite=bite+optext;}else{break;}}bite=bite+"]";var remainder=script.slice(i);pxn8cb=function(json) {var script=[{"operation": "cache", "image": json.image}];for (var i=0;i < remainder.length;i++){script.push(remainder[i]);}PXN8.ajax.submitScript(script,callback);};url=urlWithoutScript+bite;}else
{pxn8cb=function(json){PXN8.json.setResponseForScript(scriptToText,json);callback(json);};}var insertScriptTag=function(){var scriptTag=document.createElement("script");scriptTag.setAttribute("type", "text/javascript");scriptTag.setAttribute("src", url);document.getElementsByTagName("head")[0].appendChild(scriptTag);};if (PXN8.browser.isIE6()){setTimeout(insertScriptTag,50);}else
{insertScriptTag();}}else {var req=PXN8.ajax.createRequest();var onJSONerror=function(r){alert(unescape(PXN8.strings.WEB_SERVER_ERROR)+"\n"+r.statusText+"\n"+r.responseText) ;var timer=document.getElementById("pxn8_timer");if (timer){timer.style.display="none";}PXN8.updating=false;};PXN8.json.bindScriptToResponse(req,callback,scriptToText,onJSONerror);req.open("POST", PXN8.root+"/"+PXN8.basename, true);req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');var submission="script="+scriptToText;req.send(submission);}};PXN8.optimizeScript=function(script){var self=PXN8;for (var i=0; i < self.optimizations.length; i++){var optimize=self.optimizations[i];script=optimize(script);}return script;};PXN8.optimizations=[
function(script) {var result=[];for (var i=0;i < script.length; i++){var op=script[i];var nextop=false;if (i+1 < script.length){nextop=script[i+1];}if (nextop && op.operation=='resize' && nextop.operation=='resize'){}else{result.push(op);}}return result;},function(script) {var result=[];for (var i =0; i < script.length;i++){var op=script[i];var nextop=false;if (i+1 < script.length){nextop=script[i+1];}if (nextop && (nextop.operation=='normalize') && (op.operation=='normalize')){}else{result.push(op);}}return result;},function(script) {var result=[];var colorsOp=null;for (var i=0; i < script.length; i++){var op=script[i];if (op.operation != "colors"){if (colorsOp != null){result.push(colorsOp);}result.push(op);colorsOp=null;}else{if (colorsOp != null){colorsOp.saturation=((colorsOp.saturation / 100)*(op.saturation /100))*100;colorsOp.brightness=((colorsOp.brightness / 100)*(op.brightness /100))*100;colorsOp.hue=((colorsOp.hue / 100)*(op.hue /100))*100;colorsOp.contrast=colorsOp.contrast+op.contrast ;}else{colorsOp=op;}}}if (colorsOp != null){result.push(colorsOp);}return result;},function(script) {var result=[];for (var i=0;i < script.length; i++){var op=script[i];var nextop=false;if (i+1 < script.length){nextop=script[i+1];}if (nextop && (nextop.operation=='rotate') && (op.operation=='rotate')){var flipping=(op.flipvt || op.fliphz || nextop.flipvt || nextop.fliphz);if (!flipping) {nextop.angle=(op.angle+nextop.angle) % 360;}else{if ((op.angle==0 && nextop.angle==0) && ((op.flipvt==nextop.flipvt) && (op.fliphz==nextop.fliphz))){i += 1;}else{result.push(op);}}}else{if (op.operation=='rotate'){var flipping=(op.flipvt || op.fliphz || nextop.flipvt || nextop.fliphz);if (!flipping && op.angle==0){}else{result.push(op);}}else{result.push(op);}}}return result;}];PXN8.json=function(){var that={ };var scriptCache={ };function getResponseForScript(script){ return scriptCache[script];};function setResponseForScript(script,json){ scriptCache[script]=json;};function bindScriptToResponse (request,callback,scriptAsString,onerror) {request.onreadystatechange=function(){if (request.readyState==4) {if (request.status==200) {var json ;try{json=eval('('+ request.responseText+')');setResponseForScript(scriptAsString,json);}catch (e){alert("An exception occured tring to evaluate server response:\n"+request.responseText+"\nException: "+e);var wnd=window.open("","","height=200, width=640, scrollbars=1, resizable=1, location=0, menubar=0, toolbar=0");var doc=wnd.document;doc.open("text/plain");doc.writeln("If contacting the site administrator, please copy and paste the following...");doc.writeln("============================================================================");doc.writeln("An exception ("+e+") occured trying to evaluate server response:");doc.writeln(request.responseText);doc.close();return;}callback(json);} else {if (onerror){onerror(request);}else{alert(unescape(PXN8.strings.WEB_SERVER_ERROR)+"\n"+request.statusText+"\n"+request.responseText) ;}}}};};that.bindScriptToResponse=bindScriptToResponse;that.getResponseForScript=getResponseForScript;that.setResponseForScript=setResponseForScript;return that;}();var PXN8=PXN8 || {};PXN8.save={};PXN8.save.toDisk=function(){var uncompressedImage=PXN8.getUncompressedImage();if (uncompressedImage){var newURL=PXN8.server+PXN8.root+"/save.pl?";if (typeof pxn8_original_filename=="string"){newURL += "originalFilename="+pxn8_original_filename+"&";}newURL += "image="+uncompressedImage;document.location=newURL;}else{document.location="#";PXN8.show.alert("You have not changed the image !");}};PXN8.save.toServer=function(){var relativeFilePathToUncompressedImage=PXN8.getUncompressedImage();if (typeof pxn8_save_image=='function'){return pxn8_save_image(relativeFilePathToUncompressedImage);} else {alert("This feature is not available by default.\n"+"To enable this feature you must create a PHP,ASP or JSP page to save the image to your own server.\n"+"You must also create a javascript function called 'pxn8_save_image()'-it's first parameter is the URL of the changed image.\n"+"The path to the changed image (relative to the directory where PXN8 is installed) is "+PXN8.getUncompressedImage());return false;}};
var PXN8 = PXN8 || {};

PXN8.clipart = {};

function correctPNG(){};

function change_clipart(o)
{
    PXN8.clipart = o;
    var selection = PXN8.getSelection();
    //
    // enter 'overlay' mode
    // in this mode, every time the user selects an area of the photo,
    // the overlay image is super-imposed on top so the user knows  where the
    // overlay will appear once the overlay operation is applied.
    //
    var zoom = PXN8.zoom.value();
	 var img = document.all?PXN8.clipart.gif:PXN8.clipart.png;
	 var img = PXN8.clipart.png;

	 PXN8.overlay.start(PXN8.root + img,{width: PXN8.clipart.width /zoom,height: PXN8.clipart.height / zoom, top:selection.top, left: selection.left });

}

function show_clipart_config()
{
    document.getElementById("all_tools").style.display="none";
    document.getElementById("clipart_config").style.display = "block";

	 //
	 // wph 20090128 - loading the clipart images on demand speeds up initial page load
	 //
	 var req = PXN8.ajax.createRequest();
	 req.onreadystatechange = function(){
		  if (req.readyState == 4 && req.status == 200){
				document.getElementById("clipart_table_container").innerHTML = req.responseText;
		  }
	 };
	 req.open("GET", "/pixenate/themes/slick/clipart_table.html");
	 req.send(null);

    var selection = PXN8.getSelection();
    //
    // enter 'overlay' mode
    // in this mode, every time the user selects an area of the photo,
    // the overlay image is super-imposed on top so the user knows  where the
    // overlay will appear once the overlay operation is applied.
    //
    var zoom = PXN8.zoom.value();

    var theImage = document.getElementById("pxn8_image");

    var rw = theImage.width / zoom;
    var rh = theImage.height / zoom;

    if (rh < PXN8.clipart.height || rw < PXN8.clipart.width){
        //
        // zoom the photo so that the clipart doesn't obscure it completely
        //
        var nw = PXN8.clipart.width * 2;
        var nz = nw / rw;
        PXN8.zoom.zoomByValue(nz);
        zoom = nz;
    }
	 // wph 20081125 - allow clipart to clip the bounds of the image
    PXN8.select.constrainToImageBounds = false;
    var theCanvas = document.getElementById("canvas_container");
    theCanvas.style.overflow = "hidden";

    PXN8.overlay.start(PXN8.root + PXN8.clipart.gif,{width: PXN8.clipart.width /zoom,height: PXN8.clipart.height / zoom, top:selection.top, left: selection.left });

	 correctPNG();
}

function hide_clipart_config()
{
    PXN8.select.constrainToImageBounds = true;
    document.getElementById("all_tools").style.display="block";
    document.getElementById("clipart_config").style.display = "none";
    PXN8.overlay.stop();
    PXN8.unselect();
}

function add_clipart_to_photo()
{
    //
    // construct an overlay operation object
    //
    var params = PXN8.getSelection();
    if (PXN8.clipart.png){
        params.filepath = "." + PXN8.clipart.png;
    }else{
        params.filepath = "." + PXN8.clipart.gif;
    }

    params.tile = "false";

    //
    // Overlay the clipart
    //
    PXN8.tools.overlay(params);

    //
    // exit overlay mode after the image has changed
    //
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            PXN8.overlay.stop();
            PXN8.unselect();
        });
}
/*
 * optimized rotation: if rotated 90 degrees x 4 then just undo previous 3 operations
 */
function slickRotate(event)
{
    PXN8.tools.rotate({angle:90});
    return false;
}

function submit_upload_form(form)
{
    var fname = document.getElementById("filename").value;
    if (fname == "" ){
        alert("Press the Browse button to choose a file first");
        return false;
    }
    form.pxn8_root.value = PXN8.root;
    // upload won't work if page is in a frameset.
    var current_page = window.location.href;
    current_page = current_page.split("#")[0];
    current_page = current_page.split("?")[0];
    form.next_page.value = current_page;

    return true;
}
function loadImageFromPrompt()
{
    var loc = prompt("Please enter the web address of the image:","http:/" + "/");
    if (loc){
        toggleVisibility(null,'sourceoptions'); //
        //
        // loadImage is deprecated in favour of PXN8.initialize()
        //
        //PXN8.loadImage(loc);
        //
        PXN8.initialize(loc);

    }
    return false;
}
function toggleVisibility(element, targetId, nodeTexts)
{
    var dom  = PXN8.dom;

    var targetElement = dom.id(targetId);
    if (targetElement.style.display == "none"){
        targetElement.style.display = "block";
        if (nodeTexts){
            element.innerHTML = nodeTexts.hide;
        }
    }else{
        targetElement.style.display = "none";
        if (nodeTexts){
            element.innerHTML = nodeTexts.show;
        }
    }
    return false;
}
function toggleConfigVisibility(visible)
{
    var dom = PXN8.dom;

    var toolPalette = dom.id("all_tools");
    toolPalette.style.display = visible?"none":"block";
    var toolPalette = dom.id("pxn8_config_area");
    toolPalette.style.display = visible?"block":"none";
}

function configureTool (func, element, event)
{
    if (typeof element == "string"){
        element = PXN8.dom.id(element);
    }

    if (!event){
        event = window.event;
    }

    PXN8.tooltip.hide(element);
    toggleConfigVisibility(true);

    var cleanUp = function(){
        var _ = PXN8.dom;
        PXN8.resize.enable(["n","s","e","w","ne","nw","sw"],true);

        var cancelBtn = _.id("pxn8_cancel");
        if (cancelBtn){
            //
            // for the RedEye mode, Change "Done" back to "Cancel"
            //
            _.cl(cancelBtn);
            _.ac(cancelBtn,_.tx("Cancel"));
            //
            // wph 20070120 : remove the 'undo' button
            //
        }
        var undoBtn = _.id("pxn8_redeye_undo_btn");
        if (undoBtn){
            undoBtn.parentNode.removeChild(undoBtn);
        }
    };
    cleanUp();
    func(element,event);
}
/**
 * The following code temporarily highlights the 'Undo' button
 * when the image is modified so that the user is subtly guided
 * to the location of the 'Undo' button.
 */

var undoHilited = false;
PXN8.listener.add(PXN8.ON_IMAGE_CHANGE,function(){
	     if (PXN8.opNumber == 1 && !undoHilited){
            el = document.getElementById("undo").parentNode;
            el.style.backgroundColor = "lemonchiffon";

            setTimeout(function(){
                    el.style.backgroundColor = "transparent";
                },2000);
            undoHilited = true;
        }
    });

function _undo()
{
    PXN8.tooltip.hide(this,"undo");
    PXN8.tools.undo();
    return false;
}

function _redo()
{
    PXN8.tooltip.hide(this,"redo");
    PXN8.tools.redo();
    return false;
}
function _selectall()
{
    PXN8.tooltip.hide(this,"selectall");
    PXN8.selectAll();
    return false;
}
function _selectnone()
{
    PXN8.tooltip.hide(this,"selectnone");
    PXN8.unselect();
    return false;
}
function _zoomin()
{
    PXN8.tooltip.hide(this,"zoomin");
    PXN8.zoom.zoomIn();
}
function _zoomout()
{
    PXN8.tooltip.hide(this,"zoomout");
    PXN8.zoom.zoomOut();
}
function _enhance()
{
    PXN8.tooltip.hide(this,"enhance");
	 PXN8.tools.enhance();
    return false;
}
function _normalize()
{
    PXN8.tooltip.hide(this,"normalize");
	 PXN8.tools.normalize();
    return false;
}
function _fill_flash()
{
    PXN8.tooltip.hide(this,"fill_flash");
    PXN8.tools.fill_flash();
    return false;
}
function _crop()
{
    configureTool(PXN8.tools.ui.config_crop,"crop",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _resize()
{
    configureTool(PXN8.tools.ui.config_resize,"resize",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _rotate()
{
    PXN8.tooltip.hide(this,"rotate");
    PXN8.tools.rotate({angle: 90});
    return false;
}
function _rotateccw()
{
    PXN8.tooltip.hide(this,"rotateccw");
    PXN8.tools.rotate({angle: 270});
    return false;
}
function _flipvertically()
{
    PXN8.tooltip.hide(this,"flipvertically");
    PXN8.tools.rotate({flipvt: true});
    return false;
}
function _fliphorizontally()
{
    PXN8.tooltip.hide(this,"fliphorizontally");
    PXN8.tools.rotate({fliphz: true});
    return false;
}
function _spiritlevel()
{
    configureTool(spiritlevelmode,"spiritlevel",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _redeye()
{
    configureTool(PXN8.tools.ui.config_redeye,"redeye",window.event);
    return false;
}
function _whiten()
{
    configureTool(PXN8.tools.ui.config_whiten,"whiten",window.event);
    return false;
}
function _sepia()
{
    configureTool(PXN8.tools.ui.config_sepia,"sepia",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _bsh()
{
    configureTool(PXN8.tools.ui.config_bsh,"bsh",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _lomo()
{
    configureTool(PXN8.tools.ui.config_lomo,"lomo",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _filter()
{
    configureTool(PXN8.tools.ui.config_filter,"filter",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _roundedcorners()
{
    configureTool(PXN8.tools.ui.config_roundedcorners,"roundedcorners",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _interlace()
{
    configureTool(PXN8.tools.ui.config_interlace,"interlace",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _snow()
{
    PXN8.tooltip.hide(this);
    PXN8.tools.snow();
    return false;
}
function _addtext()
{
    configureTool(showConfigText,"addtext",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}
function _oilpainting()
{
    configureTool(PXN8.tools.ui.config_oilpainting,"oilpainting",window.event);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            toggleConfigVisibility(false);
        });
    return false;
}

function _sketch()
{
	 var image = PXN8.ImageMagick.start();

    var tile = new PXN8.ImageMagick();
    tile.Method("Read",{filename: "images/overlays/pencil_tile.gif"});
	 image.Quantize({colorspace: "Gray"});
	 image.Composite({image: tile, tile: "true", compose: "ColorDodge"});

	 /*
	  * the expensive way
	  *
	  image.Quantize({colorspace: "Gray"});
	  image.Sketch({radius: 0, sigma: 20, angle: 120});
	  */

    PXN8.ImageMagick.end(image);
}

/**
 * Preview the text as it will appear when the AddText operation is performed.
 */
function previewText()
{
    var dom = PXN8.dom;
    var color= showConfigText.color;
    var fontEl = dom.id("font");
    var font = fontEl.options[fontEl.selectedIndex].value;
    var size = parseInt(dom.id("pointsize").value);
    var gravEl = dom.id("gravity");
    var gravity = gravEl.options[gravEl.selectedIndex].value;
    var text = dom.id("text").value;

    var imgBounds = dom.eb(dom.id("pxn8_image"));

	 var zoom = PXN8.zoom.value();

    var preview = dom.ce("div",{id: "pxn8_text_preview"});
    preview.style.position = "absolute";
    preview.style.width = imgBounds.width + "px";
    preview.style.left = imgBounds.x + "px";
    preview.style.color = color;
    preview.style.fontSize = (size * zoom) + "px";
    preview.style.textAlign = "center";
    preview.style.top = imgBounds.y + ((imgBounds.height/2) - (size*zoom)/2) + "px";

    dom.ac(preview,dom.tx(text));
    dom.ac(document.body,preview);

    if (gravity.match("South")){
        preview.style.top = imgBounds.y  + (imgBounds.height - ((size * zoom) + 5)) + "px";
    }
    if (gravity.match("North")){
        preview.style.top = imgBounds.y + "px";
    }
    if (gravity.match("West")){
        preview.style.textAlign = "left";
    }
    if (gravity.match("East")){
        preview.style.textAlign = "right";
    }
    setTimeout(function(){
        document.body.removeChild(preview);
    },3000);
}

/**
 * Show the Text Configuration Tool Panel
 */
function showConfigText()
{
    var dom = PXN8.dom;
	 var defaultColor = "#FFFFFF";
	 showConfigText.color = defaultColor;

    var applyBtn = dom.id("pxn8_apply");
    applyBtn.style.display = "inline";

    var configTitle = dom.cl(dom.id("pxn8_config_title"));
    configTitle.appendChild(dom.tx("Add Text to image"));

    var cfgContent = dom.cl(dom.id("pxn8_config_content"));

	 // wph 20070220 : The pxn8_tool_prompt div must be cleared or
	 // the last tool prompt will appear there.
	 //
	 dom.cl("pxn8_tool_prompt");

    var picker = PXN8.colors.picker(defaultColor,function(v){
		  showConfigText.color = v;
    });

    dom.ac(cfgContent,picker);

    var ih = dom.id("configure_text").innerHTML;
    ih = ih.replace(/&lt;/g,"<");
    ih = ih.replace(/&gt;/g,">");
    /**
     * wph 20060821: Can't just append to cfgContent.innerHTML
     * because doing so wipes out the onclick handler for the color picker.
     * Strangely, creating a div, setting it's innerHTML and appending the div
     * using DOM works.
     */
    var div = dom.ce("div");
    div.innerHTML = ih;
    dom.ac(cfgContent,div);

    applyBtn.onclick = function(){
        var fontEl = dom.id("font");
        var font = fontEl.options[fontEl.selectedIndex].value;
        var size = dom.id("pointsize").value;
        var gravEl = dom.id("gravity");
        var gravity = gravEl.options[gravEl.selectedIndex].value;
        var text = dom.id("text").value;
        PXN8.tools.add_text({
            "gravity": gravity,
            "fill": showConfigText.color,
            "font": font,
            "pointsize": size,
            "text": text});
        return false;
    };

    var text = document.getElementById("text");

    text.focus();
    text.select();

	 var font = document.getElementById("font");
    var _ = PXN8.dom;
	 for (var i in PXN8.fonts){
        var option = _.ce("option",{value: i});

		  _.ac(option,_.ce("img",{src: PXN8.server + PXN8.root + "/" + PXN8.fonts[i]}));
		  _.ac(option,_.tx(i));
        _.ac(font,option);
    }
}
// ========================================================================
//
// SPEECH BUBBLES
//
// ========================================================================

    //
    // where is the speech bubble coming from ?
    //
    var bubble_direction = "left";
	 var bubble_type = "speech";

    function change_bubble(t,d)
    {
        bubble_type = t;
        bubble_direction = d;
        var selection = PXN8.getSelection();
        //
        // enter 'overlay' mode
        // in this mode, every time the user selects an area of the photo,
        // the overlay image is super-imposed on top so the user knows  where the
        // overlay will appear once the overlay operation is applied.
        //
        var zoom = PXN8.zoom.value();

        PXN8.overlay.start(PXN8.server + PXN8.root + "/images/overlays/" + bubble_direction + "_" + bubble_type + "_bubble.gif",
                           {width:150 /zoom,height:100 / zoom, top:selection.top, left: selection.left });
    }

    function show_bubble_config()
    {
	     document.getElementById("all_tools").style.display="none";
        document.getElementById("bubble_config").style.display = "block";
        var selection = PXN8.getSelection();
        //
        // enter 'overlay' mode
        // in this mode, every time the user selects an area of the photo,
        // the overlay image is super-imposed on top so the user knows  where the
        // overlay will appear once the overlay operation is applied.
        //
        var zoom = PXN8.zoom.value();
        PXN8.overlay.start(PXN8.server + PXN8.root + "/images/overlays/" + bubble_direction + "_" + bubble_type + "_bubble.gif",
                           {width:150 / zoom,height:100 /zoom, top: selection.top, left: selection.left});
    }

    function hide_bubble_config()
    {
	     document.getElementById("all_tools").style.display="block";
        document.getElementById("bubble_config").style.display = "none";
        PXN8.overlay.stop();
        PXN8.unselect();

    }

    function add_bubble_to_photo()
    {
        //
        // construct an overlay operation object
        //
        var overlayOp = PXN8.getSelection();
        overlayOp.filepath = "images/overlays/" + bubble_direction + "_" + bubble_type + "_bubble.gif";
        overlayOp.tile = "false";
        overlayOp.operation = "overlay";

        //
        // construct a text operation object
        //
        var zoom = PXN8.zoom.value();
        var theImage = PXN8.dom.id("pxn8_image");

        var iw = theImage.width / zoom;
        var ih = theImage.height / zoom;

        var cix = iw / 2;
        var ciy = ih / 2;

        var sel = PXN8.getSelection();

        var csx = sel.left + (sel.width /2);
        var csy = sel.top + (sel.height /2 );

        var ox = csx - cix;
		  var oy = csy - ciy;

        var textOp = {};
        textOp.top = oy;
        textOp.left = ox;
        textOp.gravity = "Center";
        textOp.operation = "add_text";
        textOp.font = PXN8.fonts["ComicBook"]?"ComicBook":"Arial";

		  var pointSize = document.getElementById("bubble_text_size").value;
        textOp.pointsize = pointSize / zoom;

        textOp.text = document.getElementById("bubble_text").value;

        //
        // Overlay the speech bubble then add text on top
        //
        PXN8.tools.updateImage([overlayOp,textOp]);

        //
        // exit overlay mode after the image has changed
        //
        PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
                PXN8.overlay.stop();
                PXN8.unselect();
        });
    }

function _bubbles()
{
    show_bubble_config();
    return false;
}

var PXN8 = PXN8 || {};

var heart_outline = "images/overlays/heart_outline.gif";
var heart_mask = "images/overlays/heart_mask.jpg";

function create_cutout()
{
    var crop = PXN8.getSelection();
    crop.operation= "crop";
    

    var mask = PXN8.getSelection();
    
    mask.operation = "mask";
    mask.filepath = heart_mask;
    var color = null;
    var pink = document.getElementById("heart_pink");
    var white = document.getElementById("heart_white");
    var trans = document.getElementById("heart_transparent");

    if (pink.checked){
        color = pink.value;
    }
    if (white.checked){
        color = white.value;
    }
    if (trans.checked){
        color = trans.value;
        mask.__extension = ".png";
    }
    
    mask.background_color = color;
    
    PXN8.tools.updateImage([crop,mask]);
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
            hide_valentine_config();
        });
    
}

function show_valentine_config()
{
    
    document.getElementById("all_tools").style.display="none";
    document.getElementById("valentine_config").style.display = "block";
    var selection = PXN8.getSelection();

    //
    // enter 'overlay' mode
    // in this mode, every time the user selects an area of the photo,
    // the overlay image is super-imposed on top so the user knows  where the 
    // overlay will appear once the overlay operation is applied.
    //
    var zoom = PXN8.zoom.value();

    var theImage = document.getElementById("pxn8_image");
    
    var rw = theImage.width / zoom;
    var rh = theImage.height / zoom;

    var minDim = Math.min(rw,rh);

    PXN8.overlay.start(PXN8.root + heart_outline,{width: minDim,height: minDim, top:0, left: 0 });
}

function hide_valentine_config()
{
    document.getElementById("all_tools").style.display="block";
    document.getElementById("valentine_config").style.display = "none";
    PXN8.overlay.stop();
    PXN8.unselect();
}
/**
 * Copyright (c) Sxoop Technologies Ltd. 2008 All rights reserved.
 *
 * This javascript file contains a few function which use the Pixente-ImageMagick bridge to
 * provide custom photo manipulation via javascript.
 *
 * Walter Higgins 22 May 2008
 */

/**
 * Create a warhol-esque 2x2 popart poster
 */
function imagemagick_popart()
{
    var size = PXN8.getImageSize();
    var md = size.width>size.height?size.height: size.width;
    if (md > 1024 ){
        md = 1024;
    }

    var image = PXN8.ImageMagick.start();
    image.Crop({width: md, height: md, x: ((size.width/2)-md/2),y:((size.height/2)-md/2)});
    var canvas = new PXN8.ImageMagick();
    canvas.Set({size: (md * 2) + "x" + (md * 2)});
    canvas.Read("xc:white");
    image.Enhance();
    image.Enhance();

    var level = 4;
    var opacity = "25%";

    var p1 = image.Clone();
    p1.Posterize({levels: level});

    var p2 = p1.Clone();
    p2.Colorize({fill: "red", opacity: opacity});

    var p3 = p1.Clone();
    p3.Colorize({fill: "green", opacity: opacity});

    var p4 = p1.Clone();
    p4.Colorize({fill: "yellow", opacity: opacity});

    canvas.Composite({image: p1, compose: "Over", x: 0, y:0});
    canvas.Composite({image: image, compose: "Over", x: md, y:0});
    canvas.Composite({image: p3, compose: "Over", x: 0, y: md});
    canvas.Composite({image: p4, compose: "Over", x: md, y: md});

    PXN8.ImageMagick.end(canvas);
}

/**
 * Create a vertical reflection
 */
function imagemagick_reflection()
{
    //
    // start an editing session using PXN8.ImageMagick
    //
    var image = PXN8.ImageMagick.start();

    var reflectionHeight = 100;
    var imageWidth = PXN8.getImageSize().width;

    //
    // clone the image and flip the clone
    //
    var flipped = image.Clone();
    flipped.Flip();

    //
    // create a white background for the reflection to fade to.
    //
    var white = new PXN8.ImageMagick();
    white.Set({size: imageWidth + "x" + reflectionHeight});
    white.Read("xc:white");

    //
    // create a gradient mask to apply to the flipped image
    //
    var mask = new PXN8.ImageMagick();
    mask.Set({size: imageWidth + "x" + reflectionHeight});
    mask.Read("gradient:#000000-#FFFFFF");
    mask.Set({matte: false});

	 //
    // apply the mask
    //
    white.Composite({image: mask, compose: "CopyOpacity"});

    //
    // superimpose the faded white on top of the flipped image
    //
    flipped.Composite({image: white, compose: "Over", x:0, y:0});

    //
    // crop the flipped image
    //
    flipped.Crop({x:0,y:0,width: imageWidth, height: reflectionHeight});

    //
    // push the flipped image on to the original
    //
    image.push(flipped);

    //
    // append the images
    //
    var reflection = image.Append(false);

    //
    // Commit the operations to the server
    //
    PXN8.ImageMagick.end(reflection);

}


/**
 * Create a fake polaroid effect using Pixenate's ImageMagick bridge plugin.
 *
 * Pixenate plugin development in Javascript - Yay!
 */
function imagemagick_polaroid(degrees, text)
{
    //
    // image is the current image being edited (see PXN8.initialize())
    //
    var image = PXN8.ImageMagick.start();

    var size = PXN8.getImageSize();

	 var smallestSide = Math.min(size.width, size.height);
    //
    // crop the image to a square shape.
    //
    image.Crop({height: smallestSide, width: smallestSide, x: (size.width-smallestSide)/2, y: (size.height-smallestSide)/2});

    var xBorderWidth = smallestSide / 8;
    var yBorderWidth = xBorderWidth * 2;

    //
    // create a polaroid-style border
    //
    var border = new PXN8.ImageMagick();
    border.Set( {size:  (smallestSide + xBorderWidth*2) + "x" + (smallestSide + yBorderWidth*2)});
    border.Read( "xc:#ffffff");
    //
    // superimpose the cropped photo on top of the border
    //
    border.Composite( {image: image, compose: "Over", x: xBorderWidth, y: xBorderWidth});
	 if (text && text.length > 0){
		  border.Annotate( {text: text, gravity: "South", y: xBorderWidth, pointsize: 12});
	 }

    //
    // create a drop-shadow
    var shadow = new PXN8.ImageMagick();
    shadow.Set({size: (smallestSide + (xBorderWidth * 2) + 4) + "x" + (smallestSide + (yBorderWidth*2)+4)});
    shadow.Read("xc:white");
    shadow.Draw({primitive: "Rectangle",points: "1,1," +(smallestSide+ (xBorderWidth* 2 + 1)) + "," + (smallestSide + (yBorderWidth*2)+1), fill: "#808080"});
    shadow.Blur("2.0x2.0");
    //
    // superimpose the border on top of the shadow
    //
    shadow.Composite({image: border, compose: "Over", x: 1, y: 1});
    //
    // rotate the image slightly
    //
    shadow.Rotate({degrees: degrees, background: "white"});

    PXN8.ImageMagick.end(shadow);
}
/**
 * Blur an oval shaped part of the image.
 * e.g. to heavily blur a face...
 *
 * imagemagick_ovalblur("9.0x9.0",PXN8.getSelection());
 *
 */
function imagemagick_ovalblur(blurRadius,coords)
{
    // get current image being edited
    var image = PXN8.ImageMagick.start();
    // clone it
    var cropped = image.Clone();
    // crop it
    cropped.Crop({x: coords.left, y:coords.top, width: coords.width, height:coords.height});
    // blur it
    cropped.Blur(value);

    // create an alpha mask
    var mask = new PXN8.ImageMagick();
    mask.Set({size: coords.width + "x" + coords.height});
    mask.Read("xc:#000000");
    //
    // draw a white ellipse on the black background
    //
    mask.Draw({
        primitive: "ellipse",
        points: (coords.width/2) + "," + (coords.height/2) + "," + (coords.width/2) + "," + (coords.height/2) + ",0,360",
        method: "Floodfill",
        fill: "#ffffff",
        stroke: "none"
    });
    // blur the mask itself so there isn't a hard transition from blur to non-blur
    mask.Blur("5.0x5.0");

    mask.Set({matte: "false"});

    // apply the mask to the cropped image
    cropped.Composite({image: mask, compose: "CopyOpacity"});

    // insert the cropped image back into the photo
    image.Composite({image: cropped, compose: "Over", x: coords.left, y: coords.top})

    // we're done.
    PXN8.ImageMagick.end(image);
}
/*
 * (c) Copyright SXOOP Technologies Ltd. 2005-2009
 * All rights reserved.
 *
 */
PXN8 = PXN8 || {};
/**
 * NAMESPACE
 */
PXN8.tools.ui = {};
/**
 * NO-OP function
 */
PXN8.tools.ui.nop = function(){return false;};

/* ===========================================================================
 * BLUR RELATED FUNCTIONS
 */
PXN8.tools.ui.blur = function()
{
    var _ = PXN8.dom;

    var radius = _.id("blurRadius").value;

    if (isNaN(radius) || radius < 1 || radius > 8){
        alert(PXN8.strings.BLUR_RANGE);
        return false;
    }

    var sel = PXN8.getSelection();

    sel.radius = radius;

    PXN8.tools.blur(sel);

    return true;
};

/*
 * Configure the blur tool panel
 */
PXN8.tools.ui.config_blur = function(element,event)
{
    var _ = PXN8.dom;

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";
    //applyBtn.onclick = PXN8.tools.ui.blur;
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
        PXN8.tools.ui.blur();
        return false;
    };

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_BLUR_TOOL));

    var form = _.ac(_.cl("pxn8_config_content"),_.ce("form",{onsubmit: function(){PXN8.tools.ui.blur();return false;}}));

    var radiusInput = _.ce("input",{className: "pxn8_small_field",type: "text",id: "blurRadius",value: 2,name: "blurRadius"});

    var table = _.table([[PXN8.strings.RADIUS_LABEL,radiusInput]],{width: "100%"});

    _.ac(form,table);

    radiusInput.onfocus = radiusInput.select;

    _.ac(_.cl("pxn8_tool_prompt"),_.tx(PXN8.strings.BLUR_PROMPT));

    radiusInput.focus();
};

/* ===========================================================================
 * RESIZE RELATED FUNCTIONS
 */

/*
 * Resize the image
 */
PXN8.tools.ui.resize = function()
{
    var _ = PXN8.dom;

    var newWidth = _.id("resizeWidth").value;
    var newHeight = _.id("resizeHeight").value;

    if (newWidth == PXN8.image.width && newHeight == PXN8.image.height){
        return false;
    }
    // wph 20070517 : #18002

    if (isNaN(newWidth) || isNaN(newHeight) || newWidth <= 0 || newHeight <= 0){
        alert(PXN8.strings.NUMERIC_WIDTH_HEIGHT);
        return false;
    }
    if (newWidth.match(/[0-9]+/) && newHeight.match(/[0-9]+/)){
        /* OK */
    }else{
        alert(PXN8.strings.NUMERIC_WIDTH_HEIGHT);
        return false;
    }
    if (newWidth > PXN8.resizelimit.width || newHeight > PXN8.resizelimit.height){
        alert(PXN8.strings.LIMIT_SIZE + PXN8.resizelimit.width + "x" + PXN8.resizelimit.height);
        return false;
    }
    PXN8.unselect();
    PXN8.tools.resize(newWidth,newHeight);

    return true;
};
/**
 *
 */
PXN8.tools.ui.config_resize = function(element,event)
{
    var _ = PXN8.dom;

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";

    /* fix #17996 */
    var oldSelection = PXN8.getSelection();
    var cancelBtn = _.id("pxn8_cancel");

    _.onceOnlyClickEvent(cancelBtn,function(){
        PXN8.select(oldSelection);
        return false;
    });


    //applyBtn.onclick = PXN8.tools.ui.resize;
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //

    applyBtn.onclick = function(){
        PXN8.tools.ui.resize();
        return false;
    };

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_RESIZE_TOOL));

    var configContent = _.cl("pxn8_config_content");

    _.cl("pxn8_tool_prompt");

	 var form = _.ac(configContent,_.ce("form"));
    form.onsubmit = function(){ PXN8.tools.ui.resize(); return false; };

    var preserveRatioCheckbox = _.ce("input",{type: "checkbox", id: "preserve", value: true, defaultChecked: true});
	 preserveRatioCheckbox.onclick = function(){ if (this.checked){ matchHeightToWidth();}return true;};

    var iwidth = _.ce("input",{className: "pxn8_small_field", type: "text", value: PXN8.image.width, id: "resizeWidth", name: "resizeWidth"});
    iwidth.onfocus = iwidth.select;

    iwidth.onblur = function(){ changeDim('width'); };
    var iheight  = _.ce("input",{className: "pxn8_small_field",type: "text", value: PXN8.image.height, id: "resizeHeight", name: "resizeHeight"});
    iheight.onfocus =  iheight.select;
    iheight.onblur = function(){ changeDim('height');};

    var resizeToSelectedArea = _.ce("a",{href: "#resize_to_selected_area"});
    _.ac(resizeToSelectedArea,_.tx(PXN8.strings.RESIZE_SELECT_LABEL ));
    resizeToSelectedArea.onclick = function(){
        var sel = PXN8.getSelection();
        if (sel.width <= 0 || sel.height <= 0){
            PXN8.show.alert(PXN8.strings.RESIZE_SELECT_AREA);
            return false;
        }
        PXN8.unselect();
        PXN8.tools.resize(sel.width,sel.height);
        return false;
    };

    var table = _.table([[PXN8.strings.ASPECT_LABEL, preserveRatioCheckbox],
                           [PXN8.strings.WIDTH_LABEL,  iwidth],
                           [PXN8.strings.HEIGHT_LABEL, iheight],
                           [resizeToSelectedArea] ]);
    _.ac(form,table);

    iwidth.focus();

    /**
     * default to 75% of image size
     */
    PXN8.select(0,0,PXN8.image.width * 0.75,PXN8.image.height * 0.75);

    iwidth.setAttribute('value', PXN8.image.width);
    iheight.setAttribute('value', PXN8.image.height);

};

/**
 * Change the brightness, hue and saturation
 */
PXN8.tools.ui.bsh = function()
{

    var _ = PXN8.dom;

    var bright = _.id("brightness");
    var sat = _.id("saturation");
    var h = _.id("hue");
    var contrast = _.id("contrast");
    var contrastValue = contrast.options[contrast.selectedIndex];


    if (isNaN(bright.value) || bright.value < 0 || bright.value.match(/\S+/) == null){
        alert(PXN8.strings.BRIGHTNESS_RANGE);
        return false;
    }
    if (isNaN(h.value) || h.value < 0 || h.value > 200 || h.value.match(/\S+/) == null){
      alert (PXN8.strings.HUE_RANGE);
      return false;
    }
    if (isNaN(sat.value) || sat.value < 0 || sat.value.match(/\S+/) == null){
        alert(PXN8.strings.SATURATION_RANGE);
        return false;
    }

    if (bright.value == 100 && h.value == 100 && sat.value == 100 && contrastValue.value == 0){
        return false;
    }


    PXN8.tools.colors ({brightness: bright.value,
                        hue: h.value,
                        saturation: sat.value,
                        contrast: contrastValue.value});
    return true;

};


PXN8.tools.ui.config_oilpainting = function(element, event)
{
    var _ = PXN8.dom;

    var cancelBtn = _.id("pxn8_cancel");

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";

    _.cl("pxn8_tool_prompt");

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_OILPAINT_TOOL));

    var configContent = _.cl("pxn8_config_content");

    var form = _.ac(configContent,_.ce("form",{onsubmit: function(){
        return false;
    }}));

    /**
     * Construct a slider control to control the brightness
     */
    var slide = _.ce("div");
    _.ac(slide,_.tx(PXN8.strings.RADIUS_LABEL));

    var radius_input =   _.ce("input",{className: "pxn8_slidervalue", type: "text", name: "oilpaint_radius", id: "oilpaint_radius"});

    var table = _.table([[ slide,     radius_input]],{width: "90%"});
    _.ac(form,table);

    var previewer = PXN8.preview.initialize("pxn8_preview");

    // make it a slide
    PXN8.slide.bind(slide,'oilpaint_radius',1,7,4,1,function(){oilpaint_preview(previewer);});

    var cells = table.getElementsByTagName("td");
    for (var i = 0 ; i < cells.length; i++){
        cells[i].vAlign = "bottom";
    }
    radius_input.focus();
    radius_input.select();

    PXN8.preview.show(previewer,{operation: "oilpaint", radius: 4});

    _.onceOnlyClickEvent(cancelBtn,function(){
        PXN8.preview.hide(previewer);
        return false;
    });
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
        var radius = _.id("oilpaint_radius").value;
        PXN8.tools.oilpaint(Math.max(1,Math.min(10,radius)));
        PXN8.preview.hide(previewer);
        return false;
    };

};

function oilpaint_preview(previewer)
{
    var _ = PXN8.dom;
    var radius = _.id("oilpaint_radius").value;
    radius = isNaN(radius)?4:radius;
    var limited = Math.max(1,Math.min(8,radius));
    var op = {operation: "oilpaint", radius: limited};
    PXN8.preview.show(previewer,op);
}

PXN8.tools.ui.config_charcoal = function(element, event)
{
    var _ = PXN8.dom;

    var previewer = PXN8.preview.initialize("pxn8_preview");

    var cancelBtn = _.id("pxn8_cancel");
    _.onceOnlyClickEvent(cancelBtn,function(){
        PXN8.preview.hide(previewer);
        return false;
    });

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
        var radius = _.id("charcoal_radius").value;
        var limited = Math.max(1,Math.min(8,radius));
        PXN8.tools.charcoal(limited);
        PXN8.preview.hide(previewer);
        return false;
    };

    _.cl("pxn8_tool_prompt");

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_CHARCOAL_TOOL));

    var configContent = _.cl("pxn8_config_content");

    var form = _.ac(configContent,_.ce("form",{onsubmit: function(){
        return false;
    }}));

    /**
     * Construct a slider control to control the brightness
     */
    var slide = _.ce("div");
    _.ac(slide,_.tx(PXN8.strings.RADIUS_LABEL));

    var radius_input =   _.ce("input",{className: "pxn8_slidervalue", type: "text", name: "charcoal_radius", id: "charcoal_radius"});

    var table = _.table([[ slide,     radius_input]],{width: "90%"});
    _.ac(form,table);

    // make it a slide
    PXN8.slide.bind(slide,'charcoal_radius',1,7,4,1,function(){charcoal_preview(previewer);});

    var cells = table.getElementsByTagName("td");
    for (var i = 0 ; i < cells.length; i++){
        cells[i].vAlign = "bottom";
    }
    radius_input.focus();
    radius_input.select();

    PXN8.preview.show(previewer,{operation: "charcoal", radius: 4});

};

function charcoal_preview(previewer)
{
    var _ = PXN8.dom;
    var radius = _.id("charcoal_radius").value;
    radius = isNaN(radius)?4:radius;
    var limited = Math.max(1,Math.min(8,radius));
    var op = {operation: "charcoal", radius: limited};
    PXN8.preview.show(previewer,op);
}

/*
 * ----------------------------------------------------------------
 * Setup the Tool configuration panel for Brightness/Hue/Saturation
 * ----------------------------------------------------------------
 */
PXN8.tools.ui.config_bsh = function(element,event)
{
    var _ = PXN8.dom;

    var previewer = PXN8.preview.initialize("pxn8_preview");

    var cancelBtn = _.id("pxn8_cancel");
    _.onceOnlyClickEvent(cancelBtn,function(){
        PXN8.preview.hide(previewer);
        return false;
    });

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
        PXN8.preview.hide(previewer);
        PXN8.tools.ui.bsh();
        return false;
    };

    _.cl("pxn8_tool_prompt");

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_COLOR_TOOL));

    var configContent = _.cl("pxn8_config_content");

    var form = _.ac(configContent,_.ce("form",{onsubmit: function(){
        PXN8.tools.ui.bsh();
        return false;
    }}));

    /**
     * Construct a slider control to control the brightness
     */
    var brightness_slide = _.ce("div");
    _.ac(brightness_slide,_.tx(PXN8.strings.BRIGHTNESS_LABEL));

    var brightness_input =   _.ce("input",{className: "pxn8_slidervalue",
                                   type: "text",
                                   name: "brightness",
                                   id: "brightness", value: 100});

    /**
     * Construct a slider control to control the saturation
     */
    var saturation_slide = _.ce("div");
    _.ac(saturation_slide,_.tx(PXN8.strings.SATURATION_LABEL));

    var saturation_input = _.ce("input",{className: "pxn8_slidervalue", type: "text", name: "saturation", id: "saturation", value: 100});

    /**
     * Construct a slider control to control the HUE
     */
    var hue_slide =  _.ce("div");

    _.ac(hue_slide,_.tx(PXN8.strings.HUE_LABEL));

    var hue_input = _.ce("input",{className: "pxn8_slidervalue",
                               type: "text",
                               name: "hue",
                               id: "hue",
                               value: 100});

    /**
     * Construct a 'contrast' dropdown combobox
     */
    var sel = _.ce("select",{name: "contrast", id: "contrast" });
    var options = {"-3": "-3", "-2": "-2", "-1": "-1", "0": PXN8.strings.CONTRAST_NORMAL, "1": "+1", "2": "+2", "3": "+3"};
    var j  = 0;
    for (var i in options){
        if (typeof options[i] != "function"){
            sel.options[j++] = new Option(options[i],i);
        }
    }
    sel.selectedIndex = 3;

    var table = _.table([[ brightness_slide,     brightness_input,   "%"],
                           [ saturation_slide,    saturation_input,     "%"],
                           [ hue_slide,    hue_input,     "%"],
                           [ PXN8.strings.CONTRAST_LABEL, sel]],{width: "90%"});
    _.ac(form,table);

    // make it a slide
    PXN8.slide.bind(brightness_slide,'brightness',0,200,100,5,function(){colors_preview(previewer);});
    PXN8.slide.bind(saturation_slide,'saturation',0,200,100,5,function(){colors_preview(previewer);});
    PXN8.slide.bind(hue_slide,'hue',0,200,100,5,function(){colors_preview(previewer);});

    var cells = table.getElementsByTagName("td");
    for (var i = 0 ; i < cells.length; i++){
        cells[i].vAlign = "bottom";
    }

    sel.onchange = function(){colors_preview(previewer);};

    var br = _.id("brightness");
    br.focus();
    br.select();

    PXN8.preview.show(previewer);

};

/*
 * -------------------------------------------------------------------------
 * CROP RELATED FUNCTIONS
 * -------------------------------------------------------------------------
 */

/*
 * perform crop operation
 */
PXN8.tools.ui.crop = function()
{
    var sel = PXN8.getSelection();

    if (sel.width <= 0 || sel.height <= 0){
        PXN8.show.alert(PXN8.strings.CROP_SELECT_AREA);
        return false;
    }

    PXN8.tools.crop(sel);

    PXN8.unselect();

    PXN8.selectByRatio("free");

    return true;
};

/*
 * Configure the Crop tool panel
 */
PXN8.tools.ui.config_crop = function(element,event)
{
    var _ = PXN8.dom;

    var oldSelection = PXN8.getSelection();

    var selH = _.ce("input",{className: "pxn8_small_field", type: "text", value: oldSelection.height});
    var selW = _.ce("input",{className: "pxn8_small_field", type: "text", value: oldSelection.width});

    var onSelChange = function(){
        var selection = PXN8.getSelection();
        selH.value = selection.height;
        selW.value = selection.width;
    };

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
        PXN8.tools.ui.crop();
        PXN8.listener.remove(PXN8.ON_SELECTION_CHANGE,onSelChange);
        return false;
    };


    var cancelBtn = _.id("pxn8_cancel");
    _.onceOnlyClickEvent(cancelBtn,function(){
        /* change the aspect ratio back to 'free select' */
        PXN8.selectByRatio("free");
        /* fix #17971 */
        PXN8.select(oldSelection);
        PXN8.listener.remove(PXN8.ON_SELECTION_CHANGE,onSelChange);
        return false;
    });

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_CROP_TOOL));

    var theImg = _.id("pxn8_image");

    var helpArea = _.cl("pxn8_tool_prompt");

    var form = _.ac(_.cl("pxn8_config_content"),_.ce("form"));

    form.onsubmit =  function(){
        PXN8.tools.ui.crop();
        return false;
    };

    var sel = _.ce("select",{id: "aspect_ratio", name: "aspect_ratio"});
    sel.onchange = function() {
        var selected = sel.options[sel.selectedIndex];
        PXN8.selectByRatio(selected.value);
    };
    var options = {"free": PXN8.strings.CROP_FREE,
                   "1x1" : PXN8.strings.CROP_SQUARE,
						 "1x1.618": "Golden Ratio",
                   "4x6" : "4x6",
                   "5x7" : "5x7",
                   "8x10": "8x10",
                   "6x8" : "6x8"};
    var j = 0;
    for (var i in options){
        if (typeof options[i] != "function"){
            sel.options[j++] = new Option(options[i],i);
        }
    }

    /**
     * Preview Crop link
     */
    var prevCropLink = _.ce("a",{href: "#preview_crop",onclick: function(){PXN8.tools.preview_crop()}});
    // wph 20070517
    _.ac(prevCropLink,_.tx("Preview"));

    var rotateSelLink = _.ce("a",{href: "#rotate_selection",onclick: PXN8.rotateSelection});

    _.ac(rotateSelLink,_.tx("Rotate selection"));


    var onSelDimChange = function(){

        var ih = selH.value;
        var iw = selW.value;
        if (isNaN(ih) || isNaN(iw) || ih < 0 || iw < 0){
            return;
        }
        var image = _.id("pxn8_image");
        var zoom = PXN8.zoom.value();

        var realdims = {width: image.width / zoom, height: image.height / zoom};

        var nw = Math.min(realdims.width , iw);
        var nh = Math.min(realdims.height , ih);

        PXN8.select(0, 0,nw,nh);

    };

    selH.onchange = onSelDimChange;
    selW.onchange = onSelDimChange;

    PXN8.listener.add(PXN8.ON_SELECTION_CHANGE,onSelChange);


    var table = _.table([[PXN8.strings.ASPECT_CROP_LABEL, sel],
                         [prevCropLink, rotateSelLink],
                         ["Width:", selW],
                         ["Height:",selH]], {width: "100%"});

    _.ac(form,table);

    sel.focus();

};


/* ===========================================================================
 * FILTER RELATED FUNCTIONS
 * ===========================================================================
 */

/*
 * Add a lens filter to the image
 */
PXN8.tools.ui.filter = function(x,y,c,o)
{
    var _ = PXN8.dom;

    var applyBtn  = _.id("pxn8_apply");
    applyBtn.style.display = "inline";

    PXN8.tools.filter({top: y, color: c, opacity : o} );
    return true;
};

/*
 *
 */
PXN8.tools.ui.config_filter = function (element, event)
{
    var _ = PXN8.dom;
    var defaultColor = "#FFA500";
	 var color = defaultColor;

    var applyBtn = _.id("pxn8_apply");

    applyBtn.style.display = "none";

    var canvas = _.id("pxn8_canvas");
    var oldonmousedown = canvas.onmousedown;

    var onImageUpdated = null;
    onImageUpdated = function()
	 {
        applyBtn.style.display = "inline";
        var pin1 = _.id("left_pin");
        if (pin1){
            pin1.style.display = "none";
        }
        canvas.onmousedown = oldonmousedown;
    };
    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,onImageUpdated);


    var cancelBtn = _.id("pxn8_cancel");
    _.onceOnlyClickEvent(cancelBtn,onImageUpdated);

	 _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_FILTER_TOOL));

    PXN8.unselect();

    var configContent = _.cl("pxn8_config_content");


    var picker = PXN8.colors.picker(defaultColor,function(v)
	 {
		  color = v;
    });

	 _.ac(configContent,picker);

    /**
     * Construct a slider control to control opacity
     */
    var opacitySliderDiv = _.ce("div");
    _.ac(opacitySliderDiv,_.tx(PXN8.strings.OPACITY_LABEL));

    var opacityInput = _.ce("input",{className: "pxn8_slidervalue", type: "text", name: "filter_opacity", id: "filter_opacity", value: 75});

    var table3 = _.table([[opacitySliderDiv,         opacityInput, _.tx("%")]]);

    _.ac(configContent,table3);

    cells = table3.getElementsByTagName("td");
    for (var i = 0;i < cells.length; i++){
        cells[i].vAlign = "bottom";
    }

    _.ac(_.cl("pxn8_tool_prompt"),_.tx(PXN8.strings.FILTER_PROMPT));

    var newonmousedown = function(event){

        if (!event) event = window.event;
        var cursorPos = _.cursorPos(event);

        var imagePoint = PXN8.mousePointToElementPoint(cursorPos.x,cursorPos.y);

        canvas.onmousedown = oldonmousedown;

        // show pin
        var pin1 = _.id("left_pin");
        if (pin1 == null){
            pin1 = PXN8.createPin("left_pin", PXN8.root + "/images/bluepin.gif");
            document.body.appendChild(pin1);
        }

        pin1.style.display = "block";
        pin1.style.left = "" + (cursorPos.x -7) + "px";
        pin1.style.top = "" + (cursorPos.y - 7) + "px";
		  var opacity = _.id("filter_opacity").value;
        PXN8.tools.ui.filter(imagePoint.x,imagePoint.y,color,opacity);
        return true;
    };

    // make it a slide
    PXN8.slide.bind(opacitySliderDiv,'filter_opacity',0,100,75);

    canvas.onmousedown = newonmousedown;

};

/* ===========================================================================
 * INTERLACE RELATED FUNCTIONS
 * ===========================================================================
 */


/*
 * Setup the configuration panel for the interlace effect
 */
PXN8.tools.ui.config_interlace = function (element,event)
{
    var _ = PXN8.dom;
    var defaultColor = "#000000";
    var defaultOpacity = 20;
    var previewer = PXN8.preview.initialize("pxn8_preview");

    var cancelBtn = _.id("pxn8_cancel");
    _.onceOnlyClickEvent(cancelBtn,function()
	 {
        PXN8.preview.hide(previewer);
        return false;
    });
	 var color = defaultColor;

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";

    //
    // apply   button is a link and therefore it's onclick
    // Must return false to work correctly in IE
    //
    applyBtn.onclick = function()
	 {
		  var opacity = _.id("interlace_opacity").value;
        PXN8.tools.ui.interlace(color,opacity);
        PXN8.preview.hide(previewer);
        return false;
    };

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_INTERLACE_TOOL));

    var configContent = _.cl("pxn8_config_content");

    var picker = PXN8.colors.picker(defaultColor,function(v){
		  color = v;
        interlace_preview(previewer,color,PXN8.dom.id("interlace_opacity").value);
    });

    _.ac(configContent,picker);

    /**
     * Construct a slider control to control opacity
     */
    var opacitySliderDiv = _.ce("div");
    _.ac(opacitySliderDiv,_.tx(PXN8.strings.OPACITY_LABEL));

    var opacityInput = _.ce("input",
	 {
		  className: "pxn8_slidervalue",
		  type: "text",
		  name: "interlace_opacity",
		  id: "interlace_opacity",
		  value: defaultOpacity
	 });

    _.ac(configContent,_.table([[opacitySliderDiv, opacityInput, _.tx("%")]]));

    // make it a slide
    PXN8.slide.bind(opacitySliderDiv,'interlace_opacity',0,100,defaultOpacity,5,function(){
        interlace_preview(previewer,color,_.id("interlace_opacity").value);
    });

    var helpArea = _.id("pxn8_tool_prompt");
    _.cl(helpArea);
    helpArea.appendChild(_.tx(PXN8.strings.INTERLACE_PROMPT));

    opacityInput.focus();

    PXN8.preview.show(previewer, {"operation": "interlace", "color": defaultColor, "opacity": defaultOpacity});

};

/*
 * Add an interlace effect to the image
 */
PXN8.tools.ui.interlace = function(lineColor,opacity)
{
    var _ = PXN8.dom;

    if (lineColor.match(/#[a-fA-F0-9]{6}/)){
        /* it's OK */
    }else{
        alert(PXN8.strings.INVALID_HEX_VALUE);
        return false;
    }
    var sel = PXN8.getSelection();
    sel.opacity = opacity;
    sel.color = lineColor;
    PXN8.tools.interlace(sel);

    return true;
};

/* ===========================================================================
 * LOMO RELATED FUNCTIONS
 * ===========================================================================
 */
function lomo_preview(previewer)
{
    var _ = PXN8.dom;
    var opacity = _.id("opacity").value;
    var saturate = _.id("saturate").checked;
    var op = {operation: "lomo"};
    op.opacity = opacity;
    op.saturate = saturate;

    PXN8.preview.show(previewer,op);

}
/*
 * Configure the lomo tool panel
 */
PXN8.tools.ui.config_lomo = function (element,event)
{
    var _ = PXN8.dom;
    var previewer = PXN8.preview.initialize("pxn8_preview");

    var cancelBtn = _.id("pxn8_cancel");
    _.onceOnlyClickEvent(cancelBtn,function(){
        PXN8.preview.hide(previewer);
        return false;
    });

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
        PXN8.tools.ui.lomo();
        PXN8.preview.hide(previewer);
        return false;
    };

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_LOMO_TOOL));

    _.ac(_.cl("pxn8_tool_prompt"),_.tx(PXN8.strings.OPACITY_PROMPT));

    var form = _.ac(_.cl("pxn8_config_content"),_.ce("form",{name: "lomoform"}));

    form.onsubmit = function(){
        PXN8.tools.ui.lomo();
        return false;
    };

    var defaultOpacity = 60;

    /**
     * Construct a slider control to control opacity
     */
	 var opslide = _.ce("div");
	 var opacity_label = _.tx(PXN8.strings.OPACITY_LABEL);
	 opslide.appendChild(opacity_label);
    //_.ac(opslide,);

    var opacityField = _.ce("input",{className: "pxn8_slidervalue", type:"text", name:"opacity", id:"opacity"});

    var saturateCheckbox = _.ce("input",{type:"checkbox",name: "saturate", defaultChecked: true, id:"saturate"});

    saturateCheckbox.onclick = function(){lomo_preview(previewer);};

    var table = _.table([[opslide,                   [opacityField,"%"]],
                         [PXN8.strings.SATURATE_LABEL, saturateCheckbox]],{width: "100%"});



	 form.appendChild(table);

    // make it a slide
    PXN8.slide.bind(opslide,'opacity',0,100,defaultOpacity,5,function(){lomo_preview(previewer);});

    //_.ac(form,table);
    var cells = table.getElementsByTagName("td");
    for (var i = 0; i < cells.length; i++){
        cells[i].vAlign = "bottom";
    }

    opacityField.focus();

    PXN8.preview.show(previewer,{operation: "lomo", opacity: defaultOpacity, saturate: true});


};


/*
 * Add a lomo effect to the image
 */
PXN8.tools.ui.lomo = function()
{
    var _ = PXN8.dom;

    var opacity = _.id("opacity");
    var saturate = _.id("saturate");

    if (isNaN(opacity.value) || opacity.value <0 || opacity.value > 100){
        alert(PXN8.strings.OPACITY_RANGE);
        return false;
    }

    PXN8.tools.lomo({ "opacity": opacity.value, "saturate": saturate.checked });

    return true;
};


/*
 * whiten teeth
 */
PXN8.tools.ui.whiten = function()
{

    var selection = PXN8.getSelection();
    if (selection.width == 0 || selection.height == 0){
        PXN8.show.alert(PXN8.strings.WHITEN_SELECT_AREA);
        return false;
    }

    if (selection.width * selection.height > 16000){
        PXN8.show.alert (PXN8.strings.SELECT_SMALLER_AREA);
        return false;
    }

    PXN8.tools.whiten(selection);

    //
    // wph 20070221 : Clear selection
    //
    PXN8.unselect();

    return true;
};


/*
 * -------------------------------------------------------------------------
 * RED EYE RELATED FUNCTIONS
 * -------------------------------------------------------------------------
 */
/*
 * Fix red eye
 */
PXN8.tools.ui.redeye = function ()
{
    var selection = PXN8.getSelection();
    if (selection.width == 0 || selection.height == 0){
        alert(PXN8.strings.REDEYE_SELECT_AREA);
        return false;
    }
    var selChanged = false;

    if (selection.width > 100){
        selection.left = selection.left + ((selection.width - 100) / 2);
        selection.width = 100;
        selChanged = true;

    }
    if (selection.height > 100){
        selection.top = selection.top + ((selection.height - 100) / 2);
        selection.height = 100;
        selChanged = true;

    }
    if (selChanged){
        PXN8.select(selection);
    }

    PXN8.tools.fixredeye(selection);

    PXN8.unselect();
    return true;
};

PXN8.tools.ui.config_whiten = function()
{
    var _ = PXN8.dom;

    var applyBtn = _.id("pxn8_apply");
    var cancelBtn = _.id("pxn8_cancel");

    applyBtn.style.display = "inline";
    applyBtn.onclick = PXN8.tools.ui.whiten;

    var cleanUp = function(){
        var _ = PXN8.dom;
        PXN8.resize.enable(["n","s","e","w","ne","nw","sw"],true);

        //
        // for this mode, Change "Done" back to "Cancel"
        //
        _.cl(cancelBtn);
        _.ac(cancelBtn,_.tx("Cancel"));
        //
        // wph 20070120 : remove the 'undo' button
        //
        var undoBtn = _.id("pxn8_redeye_undo_btn");
        if (undoBtn){
            undoBtn.parentNode.removeChild(undoBtn);
        }
    };
    _.onceOnlyClickEvent(cancelBtn,function(){
        cleanUp();
    });
    //
    // for this mode, Change Cancel to Done.
    //
    _.cl(cancelBtn);
    _.ac(cancelBtn,_.tx("Done"));

    //
    // wph 20070120 add 'undo' button to panel
    //
    var buttons = _.id("pxn8_apply").parentNode;
    var undoBtn = _.id("pxn8_redeye_undo_btn");
    if (undoBtn == null){
        undoBtn = _.ce("button", {id: "pxn8_redeye_undo_btn"});

        buttons.insertBefore(undoBtn,cancelBtn);
        buttons.insertBefore(_.tx("\n"),cancelBtn);

        undoBtn.onclick = function(){
            PXN8.tools.undo();
            return false;
        };
        _.ac(undoBtn,_.tx("Undo"));
    }



    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_WHITEN_TOOL));

    _.ac(_.cl("pxn8_config_content"),_.tx("Select the area you wish to whiten. Then click 'Apply'."));

    _.cl("pxn8_tool_prompt");

};


/*
 * Configure the red eye tool panel
 */
PXN8.tools.ui.config_redeye = function (element,event)
{
    var _ = PXN8.dom;

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";
    var cancelBtn = _.id("pxn8_cancel");

    PXN8.resize.enable(["n","s","e","w","ne","nw","sw"],false);

    var cleanUpAfterRedEye = function(){
        var _ = PXN8.dom;
        PXN8.resize.enable(["n","s","e","w","ne","nw","sw"],true);

        //
        // for the RedEye mode, Change "Done" back to "Cancel"
        //
        _.cl(cancelBtn);
        _.ac(cancelBtn,_.tx("Cancel"));
        //
        // wph 20070120 : remove the 'undo' button
        //
        var undoBtn = _.id("pxn8_redeye_undo_btn");
        if (undoBtn){
            undoBtn.parentNode.removeChild(undoBtn);
        }
    };
    _.onceOnlyClickEvent(cancelBtn,function(){
        cleanUpAfterRedEye();
    });

    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
        var selectionAreaOK = PXN8.tools.ui.redeye();
        if (selectionAreaOK){
            //
            // wph 20070119
            // Don't clean up after apply button.
            // cleanup should only occur after the 'cancel/done' button is clicked.
            // cleanUpAfterRedEye();
        }
        return false;
    };

    //
    // for the RedEye mode, Change Cancel to Done.
    //
    _.cl(cancelBtn);
    _.ac(cancelBtn,_.tx("Done"));

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_REDEYE_TOOL));

    //
    // wph 20070120 add 'undo' button to panel
    //
    var buttons = _.id("pxn8_apply").parentNode;
    var undoBtn = _.id("pxn8_redeye_undo_btn");
    if (undoBtn == null){
        undoBtn = _.ce("button", {id: "pxn8_redeye_undo_btn"});


        buttons.insertBefore(undoBtn,cancelBtn);
        buttons.insertBefore(_.tx("\n"),cancelBtn);

        undoBtn.onclick = function(){
            PXN8.tools.undo();
            return false;
        };
        _.ac(undoBtn,_.tx("Undo"));
    }

    var table = _.table([[PXN8.strings.REDEYE_PROMPT]],{width: "100%"});
    _.ac(_.cl("pxn8_config_content"),table);

    _.cl("pxn8_tool_prompt");

    applyBtn.focus();
};


/*
 *
 */
function matchHeightToWidth(){

    var _ = PXN8.dom;

    var width = _.id("resizeWidth").value;
    var heightInput = _.id("resizeHeight");

    var expr = /^([0-9]+)(%*)$/;
    var match = width.match(expr);
    if (match != null){
        if (match[2] == '%'){
            heightInput.value = Math.round(PXN8.image.height *  (match[1] / 100));
        }else{
            heightInput.value = Math.round(PXN8.image.height * (width / PXN8.image.width));
        }
    }
}
/*
 *
 */
function matchWidthToHeight(){
    var _ = PXN8.dom;

    var height = _.id("resizeHeight").value;
    var widthInput = _.id("resizeWidth");

    var expr = /^([0-9]+)(%*)$/;
    var match = height.match(expr);
    if (match != null){
        if (match[2] == '%'){
            widthInput.value = Math.round(PXN8.image.width *  (match[1] / 100));
        }else{
            widthInput.value = Math.round(PXN8.image.width * (height / PXN8.image.height));
        }
    }
}
/*
 *
 */
function changeDim(axis){
    var _ = PXN8.dom;

    var preserve = _.id("preserve");
    if (preserve.checked){
        if (axis == 'width'){
            matchHeightToWidth();
        }else{
            matchWidthToHeight();
        }
    }
    return true;
};

/* ===========================================================================
 * ROTATE RELATED FUNCTIONS
 */

/*
 *
 */
PXN8.tools.ui.rotate = function ()
{
    var _ = PXN8.dom;

    var angleCombo = _.id("angle");
    var angle = angleCombo.options[angleCombo.selectedIndex].value;
    var flipVt = _.id("flipvt").checked;
    var flipHz = _.id("fliphz").checked;

    if (angle == 0 && flipVt == false && flipHz == false ){
        alert(PXN8.strings.PROMPT_ROTATE_CHOICE);
        return false;
    }

    PXN8.tools.rotate({"angle": angle, "flipvt": flipVt, "fliphz": flipHz});

    return false;
};

/*
 * ROTATE IMAGE
 */
PXN8.tools.ui.config_rotate = function (element,event)
{
    var _ = PXN8.dom;

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";
    //applyBtn.onclick = PXN8.tools.ui.rotate;
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
        PXN8.tools.ui.rotate();
        return false;
    };

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_ROTATE_TOOL));

    PXN8.unselect();

    _.cl("pxn8_tool_prompt");

    var form = _.ac(_.cl("pxn8_config_content"), _.ce("form"));
    form.onsubmit =  function(){
        PXN8.tools.ui.rotate();
        return false;
    };

	 var flipvt = _.ce("input", {type: "checkbox", name:"flipvt", id:"flipvt"});

    var fliphz = _.ce("input", {type: "checkbox", name: "fliphz", id: "fliphz"});

    var sel = _.ce("select",{name: "angle", id: "angle", className: "pxn8_small_field"});

    var options = {"0": "   ", "90": "90", "180": "180", "270": "270  "};
    var j = 0;
    for (var i in options){
        if (typeof options[i] != "function"){
            sel.options[j++] = new Option(options[i], i);
        }
    }

    var table = _.table([[PXN8.strings.FLIPVT_LABEL, flipvt],
                           [PXN8.strings.FLIPHZ_LABEL, fliphz],
                           [PXN8.strings.ANGLE_LABEL,  sel ]],
        {width: "100%"});


    _.ac(form,table);

    flipvt.focus();
};


/*
 * Called when the user clicks the 'spirit-level' checkbox
 */
function spiritlevelmode ()
{
    var _ = PXN8.dom;

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "none";

    var oldOnImageUpdated = PXN8.onImageUpdated;

    var tidyup = function(){

        var _ = PXN8.dom;

        var blackout= _.id("blackout");
        if (blackout){
            document.body.removeChild(blackout);
        }
        var prompt = _.id("prompt");
        if (prompt){
            document.body.removeChild(prompt);
        }
        /**
         * muy importante !
         */
        PXN8.initializeCanvas();
        /**
         * ^^^^^^^^^^^^^^^
         */
        var pin1 = _.id("left_pin");
        if (pin1){
            pin1.style.display = "none";
        }
        var pin2 = _.id("right_pin");
        if (pin2){
            pin2.style.display = "none";
        }

    };

    var cancelBtn = _.id("pxn8_cancel");
    _.onceOnlyClickEvent(cancelBtn,tidyup);

    var onImageUpdated = null;

    PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,tidyup);

    var blackout = document.createElement("div");
    blackout.id = "blackout";

    var imgBounds = _.eb("pxn8_image");
    PXN8.unselect();
    blackout.style.position = "absolute";
    blackout.style.backgroundColor = "black";
    _.opacity(blackout,0.7);

    blackout.style.top = imgBounds.y + "px";
    blackout.style.left = imgBounds.x + (imgBounds.width/2) + "px";
    blackout.style.width = (imgBounds.width/2)+"px";
    blackout.style.height = imgBounds.height + "px";
    document.body.appendChild(blackout);

    var prompt = document.createElement("div");
    prompt.id = "prompt";
    prompt.style.position = "absolute";
    prompt.style.backgroundColor = "white";
    prompt.style.padding = "4px";

    prompt.style.top = imgBounds.y + 10 + "px";
    prompt.style.left = imgBounds.x + 10 + "px";
    prompt.style.width = (imgBounds.width/2)- 20 + "px";
    prompt.style.overflow = "auto";

    _.ac(_.cl(prompt),_.tx(PXN8.strings.SPIRIT_LEVEL_PROMPT1));

    document.body.appendChild(prompt);


    var configContent = _.cl("pxn8_config_content");
    _.ac(configContent,_.tx(PXN8.strings.SPIRIT_LEVEL_PROMPT1));

    _.ac(_.cl("pxn8_config_title"),_.tx(PXN8.strings.CONFIG_SPIRITLVL_TOOL));

    var instructionIndex = 0;
    var points = { left: {x: 0, y: 0},
                   right: {x: 0, y: 0}};

    _.cl("pxn8_tool_prompt");

    var canvas = _.id("pxn8_canvas");
    canvas.onmousedown = function (event){
        var _ = PXN8.dom;

        event = (event)?event:window.event;
        _.ac(_.cl(configContent),_.tx(PXN8.strings.SPIRIT_LEVEL_PROMPT2));

        // show pin
        var pin1 = _.id("left_pin");
        if (pin1 == null){
            pin1 = PXN8.createPin("left_pin",PXN8.root + "/images/bluepin.gif");
            document.body.appendChild(pin1);
        }

        pin1.style.display = "block";
        var cursorPos = _.cursorPos(event);
        pin1.style.left = "" + (cursorPos.x -7) + "px";
        pin1.style.top = "" + (cursorPos.y - 7) + "px";

        points.left.x = PXN8.position.x;
        points.left.y = PXN8.position.y;

        blackout.style.left = imgBounds.x + "px";

        prompt.style.left = (imgBounds.x + (imgBounds.width/2)) + 10 + "px";
        _.ac(_.cl(prompt),_.tx(PXN8.strings.SPIRIT_LEVEL_PROMPT2));

        canvas.onmousedown = function (event){
            var _ = PXN8.dom;

            event = (event)?event:window.event;

            points.right.x = PXN8.position.x;
            points.right.y = PXN8.position.y;
            // show pin
            var pin2 = _.id("right_pin");
            if (pin2 == null){
                pin2 = PXN8.createPin("right_pin",PXN8.root + "/images/redpin.gif");
                document.body.appendChild(pin2);
            }
            pin2.style.display = "block";
            var cursorPos = _.cursorPos(event);
            pin2.style.left = "" + (cursorPos.x -7) + "px";
            pin2.style.top = "" + (cursorPos.y - 7) + "px";

            PXN8.initializeCanvas();

            var blackout= _.id("blackout");
            if (blackout){
                document.body.removeChild(blackout);
            }
            var prompt = _.id("prompt");
            if (prompt){
                document.body.removeChild(prompt);
            }

            PXN8.tools.spiritlevel(points.left.x,
                                   points.left.y,
                                   points.right.x,
                                   points.right.y);
            /**
             * wph 20070102
             * Automatically select an optimal area to crop so that the user
             * doesn't have to manually select the area.
             *
             */
				var oldSize = PXN8.getImageSize();
            PXN8.listener.onceOnly(PXN8.ON_IMAGE_CHANGE,function(){
					 var newSize = PXN8.getImageSize();
					 var wd = Math.floor(newSize.width - oldSize.width);
					 var hd = Math.floor(newSize.height - oldSize.height);
                PXN8.select(wd,hd,oldSize.width-wd,oldSize.height-hd);
            });
        };

    };
}


/* ===========================================================================
 * ROUNDED_CORNERS RELATED FUNCTIONS
 * ===========================================================================
 */

/*
 * Configure the rounded-corners tool panel
 */
PXN8.tools.ui.config_roundedcorners = function(element,event)
{
    var _ = PXN8.dom;
    var defaultColor = "#FFFFFF";
	 var color = defaultColor;

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";
    //applyBtn.onclick = PXN8.tools.ui.roundedcorners;
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
		  var radius = _.id("pxn8_corner_radius").value;
        PXN8.tools.ui.roundedcorners(color,radius);
        return false;
    };

    var configTitle = _.cl("pxn8_config_title");
    configTitle.appendChild(_.tx(PXN8.strings.CONFIG_ROUNDED_TOOL));


    var helpArea = _.id("pxn8_tool_prompt");
    _.cl(helpArea);

    var configContent = _.cl("pxn8_config_content");

    var picker = PXN8.colors.picker(defaultColor,function(v){
		  color = v;
    });

    _.ac(configContent,picker);

    var input = _.ce("input", {className: "pxn8_small_field", type: "text", name: "pxn8_corner_radius",id: "pxn8_corner_radius",value: "32"});

    var table = _.table([[PXN8.strings.RADIUS_LABEL, input,""]]);

    _.ac(configContent,table);

};

/*
 * Add rounded corners to the image
 */
PXN8.tools.ui.roundedcorners = function (color,radius)
{
    if (isNaN(radius) || radius < 1){
        alert("Radius must be a positive numeric value");
        return false;
    }
    PXN8.tools.roundedcorners(color, radius);
    return true;
};

/*
 * Make the image sepia tone or black&white
 */
PXN8.tools.ui.sepia = function(color)
{
    var _ = PXN8.dom;

   /*
    * n.b. the order in which the grayscale/sepia elements are declared is important.
    * for the following line to work since it uses an index - not a name (can't use
    * name because they're radio buttons )
    */
   //var operation = document.forms["sepia"].elements[1].checked?"grayscale":"sepia";

    var operation = "sepia";
    var gs = _.id("gs");
    if (gs.className == "pxn8_checked"){
        operation = "grayscale";
    }


    if (operation == "sepia"){
        PXN8.tools.sepia(color);
    }else{
        PXN8.tools.grayscale();
    }

    return true;
};

/* ===========================================================================
 * SEPIA + B&W RELATED FUNCTIONS
 * ===========================================================================
 */


/*
 * Configure the sepia/black & white tool panel
 */
PXN8.tools.ui.config_sepia = function(element, event)
{
    var _ = PXN8.dom;
    var defaultColor = "#A28A65";
	 var color = defaultColor;
    var previewer = PXN8.preview.initialize("pxn8_preview");

    var cancelBtn = _.id("pxn8_cancel");
    _.onceOnlyClickEvent(cancelBtn,function(){
        PXN8.preview.hide(previewer);
        return false;
    });

    var applyBtn = _.id("pxn8_apply");
    applyBtn.style.display = "inline";

    //applyBtn.onclick = sepiaTone;
    //
    // apply   button is a link and therefore it's onclick
    // must return false to work correctly in IE
    //
    applyBtn.onclick = function(){
        PXN8.tools.ui.sepia(color);
        PXN8.preview.hide(previewer);
        return false;
    };

    var configTitle = _.cl("pxn8_config_title");
    configTitle.appendChild(_.tx(PXN8.strings.CONFIG_BW_TOOL));

    var configContent = _.cl("pxn8_config_content");



    var picker = PXN8.colors.picker(defaultColor,function(v){
		  color = v;
        var _ = PXN8.dom;
        sepia_preview(previewer,(_.id("sep").className == "pxn8_checked"),color);

    });

    _.ac(configContent,picker);

    var form2 = _.ac(configContent,_.ce("form", {name: "sepia"}));

    form2.onsubmit = function(){
        PXN8.tools.ui.sepia();
        return false;
    };
    /**
     * Sepia radio button
     */
    var d1 = _.ce("div",{className:"pxn8_checked", id: "sep"});
    _.ac(d1,_.tx(PXN8.strings.SEPIA_LABEL));

    d1.onclick = function(){
        var _ = PXN8.dom;

        d1.className = "pxn8_checked";
        var gs = _.id("gs");
        gs.className = "pxn8_unchecked";
        _.opacity(picker,1.0);

        sepia_preview(previewer,true,color);

    };
    d1.style.cursor = "pointer";
    /**
     * Grayscale radio button
     */
    var d2 = _.ce("div",{className:"pxn8_unchecked", id: "gs"});
    _.ac(d2,_.tx(PXN8.strings.GRAYSCALE_LABEL));
    d2.onclick = function(){
        var _ = PXN8.dom;
        d2.className = "pxn8_checked";
        var sep = _.id("sep");
        sep.className = "pxn8_unchecked";
        _.opacity(picker,0.5);

        sepia_preview(previewer,false);

        return true;
    };
    d2.style.cursor = "pointer";

    var table = _.table([[d1],
                           [d2]],
        {width: "100%"});

    _.ac(form2,table);

    _.ac(_.cl("pxn8_tool_prompt"),_.tx(PXN8.strings.BW_PROMPT));

    PXN8.preview.show(previewer,{operation: "sepia", color: defaultColor});

};

function sepia_preview(previewer,sepia, color)
{
    var op = {};
    if (sepia){
        op.operation = "sepia";
        op.color = color;
    }else{
        op.operation = "grayscale";
    }

    PXN8.preview.show(previewer,op);
}

function colors_preview(previewer)
{
    var _ = PXN8.dom;

    var op = {operation: "colors"};
    op.brightness = _.id("brightness").value;
    op.saturation = _.id("saturation").value;
    op.hue = _.id("hue").value;
    var contrastCombo = _.id("contrast");
    if (contrastCombo){
        op.contrast = contrastCombo.options[contrastCombo.selectedIndex].value;
    }
    PXN8.preview.show(previewer,op);
}

function interlace_preview(previewer,color,opacity)
{
    var _ = PXN8.dom;

    var op = {"operation": "interlace","color": color, "opacity": opacity};

    PXN8.preview.show(previewer,op);

}

PXN8.listener.add(PXN8.ON_SELECTION_COMPLETE,function(){
    var applyBtn = document.getElementById("pxn8_apply");
    if (applyBtn){
        //
        // IE will complain if you try to focus when the
        // control is not visible !
        //
        try{
            applyBtn.focus();
        }catch(e){
        }
    }
});
/* ============================================================================
 *
 * (c) Copyright SXOOP Technologies Ltd. 2005-2009
 * All rights reserved.
 *
 *
 */
var PXN8 = PXN8 || {};

PXN8.tooltip = {
    forDisplay: {}
};
PXN8.tooltip._show = function(tipId)
{
    var dom = PXN8.dom;

	 var tipDiv = null;

	 if (PXN8.tooltip.forDisplay[tipId] == false){
		  return;
	 }

	 tipDiv = dom.id(tipId);

	 if (tipDiv == null){
		  return;
	 }
	 if (tipDiv.style == null){
		  return;
	 }
	 tipDiv.style.display = "block";

	 var imgBounds = dom.eb(dom.id("pxn8_image"));

	 tipDiv.style.top  = imgBounds.y + 10 + "px";
	 tipDiv.style.left = imgBounds.x + 10 + "px";
	 var shadow = dom.id("tipshadow");
	 if (!shadow){
		  shadow = dom.ac(document.body,dom.ce("div"));
	 }
	 shadow.id = "tipshadow";
	 shadow.style.backgroundColor = "black";
	 var opacity = 50;
	 shadow.style.opacity = opacity/100;
	 shadow.style._moz_opacity = opacity/100;
	 shadow.style.filter = "alpha(opacity:" + opacity + ")";
	 var tipBounds = dom.eb(tipDiv);
	 shadow.style.position = "absolute";
	 shadow.style.top = tipBounds.y + 3 + "px";
	 shadow.style.left = tipBounds.x + 3 + "px";
	 shadow.style.width = tipBounds.width+ "px";
	 shadow.style.height = tipBounds.height + "px";
};

PXN8.tooltip.show = function(element, elementId)
{
	 var tipId = null;
	 if (elementId){
		  tipId = elementId + "_tip";
	 }else{
		  tipId = element.id + "_tip";
	 }
	 PXN8.tooltip.forDisplay[tipId] = true;
	 setTimeout("PXN8.tooltip._show('" + tipId + "');",300);
};

PXN8.tooltip.hide = function (element, elementId)
{
    var dom = PXN8.dom;

	 var tipDiv = null;
	 var tipId = null;

	 if (elementId){
		  tipId = elementId + "_tip";
	 }else{
		  tipId = element.id + "_tip";
	 }

	 PXN8.tooltip.forDisplay[tipId] = false;

	 tipDiv = dom.id(tipId);

	 if (tipDiv){
		  tipDiv.style.display="none";
	 }
	 var shadow = dom.id("tipshadow");
	 if (shadow){
		  document.body.removeChild(shadow);
	 }
};

PXN8.dom.addLoadEvent(function(){
    var haveTooltips = PXN8.dom.clz("pxn8_has_tooltip");

    for (var i = 0;i < haveTooltips.length; i++){
        var el = haveTooltips[i];
        el.onmouseover = PXN8.curry(PXN8.tooltip.show,el);
        el.onmouseout = PXN8.curry(PXN8.tooltip.hide,el);
    }
});
