﻿var drawingModeOn = false;
var moWhiteBoard;
moWhiteBoard = new WhiteBoard(d('page'), document);

var objShapeXml;
var currentToolName = "";
var selectedLineId = "";

var lineObj;
var lineStrokeObj;

var fhlineObj;
var fhlineStrokeObj;

var rectSqrObj;
var rectSqrStrokeObj;

var circleObj;
var circleStrokeObj;

var currentLineNode; 
var drawStarted = false;
var drawLineContinue = false;
var currentLineVml;
var currentLineId;
var currentLineElement;

var ddm = false;

function DrawingDeleteModeOn()
{    
    
    ddm = true;
    makeToolSelected('delete');    
    UnRegisterDrawMouseEvents();
    UnRegisterSkrblMouseEvents();
    UnRegisterDrawSelectEvents();
    RegisterDDMEvents();
    //s('main_canvas').display = 'none';
    drawingModeOn=false;
}


function ddm_md(e)
{
    
    var event = e;
	
	var node = e.target;
	while(node.nodeType != node.ELEMENT_NODE)
		node = node.parentNode;
	event.srcElement = node;
/*	
	
    if(currentShapeId != null)
    {
        unselectshape(d(currentShapeId).getAttribute("shape"), currentShapeId);
        currentShapeId = null;
    }
*/
	
	if(event.srcElement.getAttribute("shape"))
	{	    
	    currentShapeId = event.srcElement.id;
	    var shapeType = event.srcElement.getAttribute("shape");	    	    
	    DeleteDrawingObj();
	    return;
	}    
}

function ddm_mm(e)
{    
}

function ddm_mu(e)
{    
}

function RegisterDDMEvents()
{    
    if(BrowserDetect.OS == "Mac")
    {
        d('page').style.cursor = "no-drop";
    }
    else
    {
        d('page').style.cursor = "URL('images/arrow-del.cur'),auto";   
    } 
    addEventListeners(document,"mousedown", ddm_md);
	addEventListeners(document,"mouseup", ddm_mu);
	addEventListeners(document,"mousemove", ddm_mm);
}

function UnRegisterDDMEvents()
{
    d('page').style.cursor = "default";   
    removeEventListeners(document,"mousedown", ddm_md);
	removeEventListeners(document,"mouseup", ddm_mu);
	removeEventListeners(document,"mousemove", ddm_mm);
}

function RegisterSkrblMouseEvents()
{
    //alert('RegisterSkrblMouseEvents');
    addEventListeners(document,"mousedown",m_d); 
	addEventListeners(document,"mouseup",m_u);
	addEventListeners(document,"mousemove",m_m);
}

function UnRegisterSkrblMouseEvents()
{
    //alert('UnRegisterSkrblMouseEvents');
    removeEventListeners(document,"mousedown",m_d);
	removeEventListeners(document,"mouseup",m_u);
	removeEventListeners(document,"mousemove",m_m);
}

function RegisterDrawMouseEvents()
{
    //alert('RegisterDrawMouseEvents');
    addEventListeners(document,"mousedown",moWhiteBoard.addLine2);
	addEventListeners(document,"mouseup",moWhiteBoard.stopLine2);
	addEventListeners(document,"mousemove",moWhiteBoard.updateLine2);
}

function UnRegisterDrawMouseEvents()
{
    //alert('UnRegisterDrawMouseEvents');
    removeEventListeners(document,"mousedown",moWhiteBoard.addLine2);
	removeEventListeners(document,"mouseup",moWhiteBoard.stopLine2);
	removeEventListeners(document,"mousemove",moWhiteBoard.updateLine2);
}

function insertAfter(parent, node, referenceNode) 
{
    parent.insertBefore(node, referenceNode.nextSibling);
}
function prependChild(parent, node) 
{
    parent.insertBefore(node, parent.firstChild);
}

var lastCurrentColor = "silver";
var LINE_SELECTED_COLOR = "silver";

function selectshape(shapetype, shape_id)
{    
    var shapeObj = d(shape_id);
    //alert(shape_id + " : " + shapeObj + " : " + shapetype);
    switch(shapetype)
    {
        case "line":                            
            var stokeObj = shapeObj.parentNode;
            lastCurrentColor = stokeObj.getAttribute("stroke");
            stokeObj.setAttribute("stroke", LINE_SELECTED_COLOR);            
            break;
        
        case "fhline":         
            lastCurrentColor = shapeObj.getAttribute("stroke");
            shapeObj.setAttribute("stroke", LINE_SELECTED_COLOR);
            break;
        
        default:
            try
            {
                lastCurrentColor = shapeObj.getAttribute("stroke");
                shapeObj.setAttribute("stroke", LINE_SELECTED_COLOR);
            }catch(e){}
            break;
    }
}

function unselectshape(shapetype, shape_id)
{
    var shapeObj = d(shape_id);
    switch(shapetype)
    {
        case "line":                            
            var stokeObj = shapeObj.parentNode;            
            try{stokeObj.setAttribute("stroke", lastCurrentColor);}catch(e){}
            break;
        
        case "fhline":            
            try{shapeObj.setAttribute("stroke", lastCurrentColor);}catch(e){}
            break;
        
        default:
            try{shapeObj.setAttribute("stroke", lastCurrentColor);}catch(e){}
            break;
    }
}

function setDrawingMode(modeVal)
{
    drawingModeOn = modeVal;
}

function makeToolSelected(toolId)
{
    var toolArray = new Array('select','fhline','delete','line','rectsqr','circle');
    for(var i=0; i<toolArray.length; i++)
    {
        if(toolId != toolArray[i])
        {
            s(toolArray[i] + 'ToolImg').borderStyle = 'solid';
        }
    }
    
    d('page').style.cursor = 'default';
    
    toolId = toolId+'ToolImg'
    
    if (s(toolId).borderStyle == 'inset')
    {
		s(toolId).borderStyle = 'solid';
	}
	else
	{
		s(toolId).borderStyle = 'inset';
    }
}

function InitDrawingMode2(toolName)
{
    
    ddm=false;
    drawingModeOn = false;
    makeToolSelected(toolName);
    currentToolName = toolName;
    UnRegisterDrawSelectEvents();
    UnRegisterDDMEvents();
    UnRegisterSkrblMouseEvents();
    RegisterDrawMouseEvents();    
    
//	s("main_canvas").top = (document.documentElement.scrollTop - 25) + 'px';
//	s("main_canvas").left = (document.documentElement.scrollLeft - 5) + 'px';
//	s("main_canvas").width = (document.documentElement.clientWidth + 5) + 'px';
//	s("main_canvas").height = (document.documentElement.clientHeight +25) + 'px';
//	s('main_canvas').display = '';
    //d('page').style.cursor = "URL('images/pen_m.cur'),auto";
    d('page').style.cursor = 'crosshair';//"URL('images/pencil.cur'),auto";   //
    drawingModeOn = true;
}

function InitTextMode()
{
    UnRegisterDDMEvents();    
    UnRegisterDrawMouseEvents();    
    UnRegisterDrawSelectEvents(); 
    RegisterSkrblMouseEvents();
}

function DrawingModeOff()
{    
    ddm=false;
    UnRegisterDDMEvents();
    makeToolSelected('select');    
    UnRegisterDrawMouseEvents();
    UnRegisterSkrblMouseEvents();
    RegisterDrawSelectEvents();
    //s('main_canvas').display = 'none';
    drawingModeOn=false;
    d('page').style.cursor = "default";
}

function RegisterDrawSelectEvents()
{
    addEventListeners(document,"mousedown",dms_md);
	addEventListeners(document,"mouseup",dms_mu);
	addEventListeners(document,"mousemove",dms_mm);
}

function UnRegisterDrawSelectEvents()
{
    removeEventListeners(document,"mousedown",dms_md);
	removeEventListeners(document,"mouseup",dms_mu);
	removeEventListeners(document,"mousemove",dms_mm);
}

function dms_md(e)
{
    var event = e;
	
	var node = e.target;
	while(node.nodeType != node.ELEMENT_NODE)
		node = node.parentNode;
	event.srcElement = node;
	
	if(currentShapeId != null)
	{	    
	    unselectshape(d(currentShapeId).getAttribute("shape"), currentShapeId);
	    currentShapeId = null;	   
	}
	
	if(event.srcElement.getAttribute("shape"))
	{	    
	    currentShapeId = event.srcElement.id;	    
	    var shapeType = event.srcElement.getAttribute("shape");	    
	    selectshape(shapeType, currentShapeId);
	    return;
	}
	
	s('main_fillcolorTable2').display = 'none';
}

function dms_mu(event)
{
    if(currentShapeId != null)
	{   
	    if(BrowserDetect.OS == "Mac" && event.ctrlKey) //right click is with control key on mac
	    {   
	        s('main_drawingmenu_page').top = event.clientY + d('page').scrollTop + self.pageYOffset + 'px'; 
		    s('main_drawingmenu_page').left = event.clientX + d('page').scrollLeft + self.pageXOffset + 'px';
		    s('main_drawingmenu_page').display = '';
		    d('main_drawingmenu_page').focus();
	    }	    
	    else if (event.button == 2 || event.button == 3) 
		{		    
		    s('main_drawingmenu_page').top = event.clientY + d('page').scrollTop + self.pageYOffset + 'px'; 
		    s('main_drawingmenu_page').left = event.clientX + d('page').scrollLeft + self.pageXOffset + 'px';		    
		    s('main_drawingmenu_page').display = '';
		    d('main_drawingmenu_page').focus();
		}
    }    
}

function dms_mm(event)
{
}

function WhiteBoard(psCanvas, psLines) 
{
   this._penColor = "blue";    // pen color
   this._penColorSelected = "yellow";    // pen color
   this.Line = "";             // current line
   this.Canvas = psCanvas;     // background and boundary area in document
   this.Lines = psLines;       // lines collection area in document
   //this.zindex = 1;            // increment to ensure newest line is always on top 
   // methods
   this.addLine2 = addLine2;     // make the functions methods
   this.updateLine2 = updateLine2;
   this.stopLine2 = stopLine2;
   this.deleteLine2 = deleteLine2;
   //this.allLines = allLines;
}

function deleteLine2(psLineId) 
{
    alert(psLineId);
    var lineElement = document.getElementById(psLineId);
   //alert(document.getElementById(psLineId).outerHTML);
   //alert(lineElement.path);
   //alert(lineElement.path.v);
   //alert(document.getElementById(psLineId).getAttribute("strokecolor"));
   if( document.getElementById(psLineId).getAttribute("strokecolor")  == "blue")
   {
        document.getElementById(psLineId).setAttribute("strokecolor", "Yellow");
        //sample locked state above - now send the line data as a tag
        SaveLine(lineElement);
   }
   else
   {
        document.getElementById(psLineId).setAttribute("strokecolor", "blue");
   }
}


var pX;var pY;
function getMouse(e)
{
    pX=0;pY=0;
    var ev=(!e)?window.event:e;//IE:Moz

    if (ev.pageX)
    {
        //Moz
        pX=ev.pageX+window.pageXOffset;
        pY=ev.pageY+window.pageYOffset;
    }
    else if(ev.clientX)
    {
        //IE
        pX=ev.clientX+document.body.scrollLeft;
        pY=ev.clientY+document.body.scrollTop;
    }
    else
    {
        return false
    }//old browsers      
}

var LINE_STROKE_WEIGHT = "2.6px";
var LINE_STROKE_COLOR = "#46ADFC";
var LINE_FILLCOLOR_DEFAULT = '#FF7400';

function SetStrokeColor(color)
{
    LINE_STROKE_COLOR = color;
    s('main_strokecolorTable').display = 'none';
    if(currentShapeId != null)
    {
        d(currentShapeId).setAttributeNS(null, "stroke", LINE_STROKE_COLOR);
        lastCurrentColor = LINE_STROKE_COLOR;
        unselectshape(d(currentShapeId).getAttribute("shape"), currentShapeId);  
        SaveShape(d(currentShapeId));
    }
}

function SetFillColorOn(id, color)
{
    d(id).setAttributeNS(null, "fill", color);
    LINE_FILLCOLOR_DEFAULT = color;
}

function SetFillColor(color)
{    
    if(currentShapeId != null)
    {
        SetFillColorOn(currentShapeId, color);    
        unselectshape(d(currentShapeId).getAttribute("shape"), currentShapeId);
        SaveShape(d(currentShapeId));
    }
    LINE_FILLCOLOR_DEFAULT = color;
    s('main_fillcolorTable').display = 'none';
    s('main_fillcolorTable2').display = 'none';
    s('main_drawingmenu_page').display = 'none';
}

function SetStrokeWidth(wid, stk_tr_id)
{
    LINE_STROKE_WEIGHT = wid;
    s('main_strokewidthTable').display = 'none';
    if(currentShapeId != null)
    {
        d(currentShapeId).setAttributeNS(null, "stroke-width", wid);
        unselectshape(d(currentShapeId).getAttribute("shape"), currentShapeId);  
        SaveShape(d(currentShapeId));
    }
}

function SetStrokeColor2(color, currentcol_id)
{
    LINE_STROKE_COLOR = color;
    var stk_col_array = new Array('strokecolor1', 'strokecolor2', 
    'strokecolor3', 'strokecolor4', 'strokecolor5');
    
    for(var i=0; i<stk_col_array.length; i++)
    {   
        s(stk_col_array[i]).borderStyle = 'none';        
    }
    
    s('strokecolor' + currentcol_id).border = '2px solid black';
}

function cumulativeOffset(element)
{
    var valueT = 0, valueL = 0;
    do 
    {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } 
    while (element);
    return [valueL, valueT];
}

function GetScrollOffsetY()
{
    if (document.documentElement && document.documentElement.scrollTop)
	    // Explorer 6 Strict
    {
	    return document.documentElement.scrollTop;
    }
    else if (document.body) // all other Explorers
    {
	    return document.body.scrollTop;
    }
}

function GetScrollOffsetX()
{
    if (document.documentElement && document.documentElement.scrollLeft)
	    // Explorer 6 Strict
    {
	    return document.documentElement.scrollLeft;	    
    }
    else if (document.body) // all other Explorers
    {
	    return document.body.scrollLeft;	    
    }   
}

function addLine2(event) 
{
    
    var offset = cumulativeOffset(d('main_svgrootobj_div'));
    var pX = event.pageX - offset[0];//event.clientX + self.pageXOffset - 0;
    var pY = event.pageY - offset[1];//event.clientY + self.pageYOffset - 0;
    var safeX_val = startupWH.w + GetScrollOffsetX();
    var safeY_val = startupWH.h + GetScrollOffsetY();
    if((pX < safeX_val - 10) && (pY < safeY_val - 10))
    {
        
        if(currentToolName == "line")
        {            
            lineStrokeObj = document.createElementNS(svgns, "g");
            lineStrokeObj.setAttribute("stroke", LINE_STROKE_COLOR);                
           
            lineObj = document.createElementNS(svgns, "line");        
            lineObj.setAttribute("x1", pX);
            lineObj.setAttribute("y1", pY);
            lineObj.setAttribute("x2", pX);
            lineObj.setAttribute("y2", pY);
            lineObj.setAttribute("stroke-width", LINE_STROKE_WEIGHT);    
            lineObj.style.position = "absolute";        
            lineObj.style.cursor = "default";
            lineObj.setAttribute("onMouseOver","function(){this.style.cursor='default';};");
            lineObj.setAttribute("id", "line_" + guid + "_" + Math.random().toString());
            lineObj.setAttribute("page", current_pageId);
            lineObj.setAttribute("shape", "line");
            lineStrokeObj.appendChild(lineObj); 
            svgRoot.appendChild(lineStrokeObj);
        }
        else if(currentToolName == "fhline")
        {             
             fhlineObj = document.createElementNS(svgns, "polyline");
             fhlineObj.setAttribute("fill", "none");
             fhlineObj.setAttribute("stroke", LINE_STROKE_COLOR);
             fhlineObj.setAttribute("stroke-width", LINE_STROKE_WEIGHT);             
             fhlineObj.id = "fhline_" + guid + "_" + Math.random().toString();
             fhlineObj.setAttribute("page", current_pageId);
             fhlineObj.setAttribute("shape", "fhline");
             fhlineObj.style.position = "absolute";
             fhlineObj.style.cursor = "default";
             fhlineObj.setAttribute("onMouseOver","function(){this.style.cursor='default';};");
             fhlineObj.setAttribute("points", pX + "," + pY);             
             svgRoot.appendChild(fhlineObj);
        }
        else if(currentToolName == "rectsqr")
        {            
            rectSqrObj = document.createElementNS(svgns, "rect");            
            rectSqrObj.id = "rectsqr_" + guid + "_" + Math.random().toString();
            rectSqrObj.setAttribute("page", current_pageId);
            rectSqrObj.setAttribute("shape", "rectsqr"); 
            rectSqrObj.style.position = "absolute";
            rectSqrObj.style.cursor = "default";
            rectSqrObj.setAttribute("onMouseOver","function(){this.style.cursor='default';};");
            rectSqrObj.setAttributeNS(null, 'x', pX + 'px');
            rectSqrObj.setAttributeNS(null, 'y', pY + 'px');
            rectSqrObj.setAttributeNS(null, 'width', '0px');
            rectSqrObj.setAttributeNS(null, 'height', '0px');
            rectSqrObj.setAttributeNS(null, 'fill', 'none');
            rectSqrObj.setAttributeNS(null, 'stroke', LINE_STROKE_COLOR);
            rectSqrObj.setAttributeNS(null, 'stroke-width', parseInt(LINE_STROKE_WEIGHT) + 'px');
            svgRoot.appendChild(rectSqrObj);
        }
        else if(currentToolName == "circle")
        {
            circleObj = document.createElementNS(svgns, 'ellipse');
            circleObj.id = "rectsqr_" + guid + "_" + Math.random().toString();
            circleObj.setAttribute("page", current_pageId);
            circleObj.setAttribute("shape", "circle"); 
            circleObj.style.position = "absolute";
            circleObj.style.cursor = "default";
            circleObj.setAttribute("onMouseOver","function(){this.style.cursor='default';};");
            
            circleObj.setAttribute("fromX", pX);
            circleObj.setAttribute("fromY", pY);
            
            circleObj.setAttributeNS(null, 'cx', (pX + 1/2) + 'px');
            circleObj.setAttributeNS(null, 'cy', (pY + 1/2) + 'px');
            circleObj.setAttributeNS(null, 'rx', (1/2) + 'px');
            circleObj.setAttributeNS(null, 'ry', (1/2) + 'px');
            circleObj.setAttributeNS(null, 'fill', 'none');
            circleObj.setAttributeNS(null, 'stroke', LINE_STROKE_COLOR);
            circleObj.setAttributeNS(null, 'stroke-width', parseInt(LINE_STROKE_WEIGHT) + 'px');
            svgRoot.appendChild(circleObj);
        }
        
        drawStarted = true;   
   }     
}

// adds new segment to current drawn line if canvas coordinate
function updateLine2(event) 
{    
    var offset = cumulativeOffset(d('main_svgrootobj_div'));
    var pButton = event.button;
    var pX = event.pageX - offset[0];//event.clientX + self.pageXOffset - 0;
    var pY = event.pageY - offset[1];//event.clientY + self.pageYOffset - 0;
   
   if (pButton == 0)
   {
          if(drawStarted)
          {
            if(currentToolName == "line")
            {
                if(lineObj != null)
                {
                    lineObj.setAttribute("x2", pX);
                    lineObj.setAttribute("y2", pY);
                }
                else
                {
                    this.addLine(pX, pY);
                }
            }
            else if(currentToolName == "fhline")
            {
                if(fhlineObj != null)
                {                    
                    var tmp = fhlineObj.getAttribute("points");                    
                    tmp += " " + pX + "," + pY;                    
                    fhlineObj.setAttribute("points", tmp);                    
                }
                else
                {
                    this.addLine2(pX, pY);
                }
            }
            else if(currentToolName == "rectsqr")
            {
                if(rectSqrObj != null)
                {
                    var deltaX = pX - parseInt(rectSqrObj.getAttributeNS(null, 'x'));
                    var deltaY = pY - parseInt(rectSqrObj.getAttributeNS(null, 'y'));
                    //window.status = pX + " : " + pY + " : "  + deltaX + " : " + deltaY + " : " + rectSqrObj.getAttributeNS(null, 'x') + " : " + rectSqrObj.getAttributeNS(null, 'y'); 
                    
                    if (deltaX < 0) 
                    {
                      rectSqrObj.setAttributeNS(null, 'x', pX + 'px');
                      rectSqrObj.setAttributeNS(null, 'width', -deltaX + 'px');                      
                    }
                    else 
                    {
                      rectSqrObj.setAttributeNS(null, 'width', deltaX + 'px');
                    }
                  
                    if (deltaY < 0) 
                    {
                      rectSqrObj.setAttributeNS(null, 'y', pY + 'px');
                      rectSqrObj.setAttributeNS(null, 'height', -deltaY + 'px');                      
                    }
                    else 
                    {
                      rectSqrObj.setAttributeNS(null, 'height', deltaY + 'px');
                    }
                }
                else
                {
                    this.addLine2(pX, pY);
                }                
            }
            else if(currentToolName == "circle")
            {
                if(circleObj != null)
                {             
                    var toX = parseInt(pX);
                    var toY = parseInt(pY);
                    var fromX = parseInt(circleObj.getAttribute("fromX"));
                    var fromY = parseInt(circleObj.getAttribute("fromY"));
                    var deltaX = toX - fromX;
                    var deltaY = toY - fromY;   
                    
                    if (deltaX < 0) 
                    {
                      circleObj.setAttributeNS(null, 'cx', (fromX + deltaX / 2) + 'px');
                      circleObj.setAttributeNS(null, 'rx', (-deltaX / 2) + 'px');
                    }
                    else 
                    {
                      circleObj.setAttributeNS(null, 'cx', (fromX + deltaX / 2) + 'px');
                      circleObj.setAttributeNS(null, 'rx', (deltaX / 2) + 'px');
                    }
                  
                    if (deltaY < 0) 
                    {
                      circleObj.setAttributeNS(null, 'cy', (fromY + deltaY / 2) + 'px');
                      circleObj.setAttributeNS(null, 'ry', (-deltaY / 2) + 'px');
                    }
                    else 
                    {
                      circleObj.setAttributeNS(null, 'cy', (fromY + deltaY / 2) + 'px');
                      circleObj.setAttributeNS(null, 'ry', (deltaY / 2) + 'px');
                    }
                }
                else
                {
                    this.addLine2(pX, pY);                    
                }           
            }
          
      }
   } 
   else 
   {
        //this.stopLine2();
   }
}

function newDrawingItemNew(id, vmlstr)
{
    document.getElementById('page').innerHTML += vmlstr;
}

var drawingTagCollection = new Object();

function newDrawingItemNew2(id, data, typ, wgt, color, pageId, fcolor)
{
    //update local state
    drawingTagCollection[id] = id;
    
    //try{svgRoot.suspendRedraw(0);}catch(e){alert(e.description);}
    if(fcolor == "") 
    fcolor = "none";
    
    if(d(id) != null)
    {
        /*
        d(id).setAttributeNS(null, "fill", fcolor);
        //d(id).setAttributeNS(null, "fill-opacity", "0.3");
        d(id).setAttributeNS(null, "stroke-width", wgt);
        d(id).setAttributeNS(null, "stroke", color);
        return;
        */
        DelDrawingEl(id);
    }
    wgt = parseInt(wgt) * 1.3;
    var svgChildObj = null;
    var svgRootObj = document.createElementNS(svgns, "svg");
    
    
    if(typ == "line")
    {
        //SVGElement
        svgChildObj = RenderLine(id, data, wgt, color, pageId, typ, fcolor);
    }
    
    if(typ == "fhline")
    {   
        //SVGPolylineElement     
        svgChildObj = Renderfhline(id, data, wgt, color, pageId, typ, fcolor);        
    }
    
    if(typ == "rectsqr")
    {
        //SVGRectElement
        svgChildObj = RenderRectSqr(id, data, wgt, color, pageId, typ, fcolor);
    }
    
    if(typ == "circle")
    {
        //SVGEllipseElement
        svgChildObj = RenderCircle(id, data, wgt, color, pageId, typ, fcolor);
    }
    //try{svgRoot.unsuspendRedraw(0);}catch(e){alert(e.description);}
    
    svgRoot.appendChild(svgChildObj);
    
    /*
    //append svgChildObj to svgRootObj
    svgRootObj.appendChild(svgChildObj);
	svgRootObj._childObj = svgChildObj;
	
    //append svgRootObj to a div
    var svgRootObjDiv = document.createElement("div");
    svgRootObjDiv.id = "main_div_" + svgChildObj.id;
    svgRootObjDiv.setAttribute("isDrawing", "1");
    svgRootObjDiv.style.position = 'absolute';   
    svgRootObjDiv.style.backgroundColor = 'yellow';
    svgRootObjDiv.style.overflow = 'hidden';	
	svgRootObjDiv.style.display = 'block';
    
    svgRootObjDiv.style.left = svgChildObj.getAttribute("divLeft");
    svgRootObjDiv.style.top = svgChildObj.getAttribute("divTop");
    svgRootObjDiv.style.width = svgChildObj.getAttribute("divWidth");
    svgRootObjDiv.style.height = svgChildObj.getAttribute("divHeight"); 
    
    svgRootObjDiv.appendChild(svgRootObj);    
    document.body.appendChild(svgRootObjDiv);
    */
}

function RenderCircle(id, data, wgt, color, pageId, typ, fcolor)
{    
    try
    {
        //cx:cy:rx:ry
        var circleObj = null;
        var circleObj = document.createElementNS(svgns, "ellipse");        
        circleObj.id = id;
        circleObj.setAttribute("page", pageId);
        circleObj.setAttribute("shape", typ); 
        //circleObj.style.position = "absolute";
        circleObj.style.cursor = "default";
        var LTWH = data.split(':');
        
        var leftVal =  LTWH[0];
        var topVal = LTWH[1];
        var widthVal = LTWH[2];
        var heightVal = LTWH[3];
        
        var cxVal = parseInt(leftVal) + parseInt(widthVal)/2 + "px";
        var cyVal = parseInt(topVal) + parseInt(heightVal)/2 + "px";;
        var rxVal = parseInt(widthVal)/2 + "px";
        var ryVal = parseInt(heightVal)/2 + "px";
        
        circleObj.setAttributeNS(null, 'cx', cxVal);
        circleObj.setAttributeNS(null, 'cy', cyVal);
        circleObj.setAttributeNS(null, 'rx', rxVal);
        circleObj.setAttributeNS(null, 'ry', ryVal);
        circleObj.setAttributeNS(null, 'fill', fcolor);
        circleObj.setAttributeNS(null, 'stroke', color);
        circleObj.setAttributeNS(null, 'stroke-width', parseInt(wgt) + 'px');
        //svgRoot.appendChild(circleObj);
        
//        var divLeft, divTop, divWidth, divHeight;
//        circleObj.setAttribute("divLeft", divLeft);
//        circleObj.setAttribute("divTop", divTop);
//        circleObj.setAttribute("divWidth", divWidth); 
//        circleObj.setAttribute("divHeight", divHeight);
        
        return circleObj;
    }
    catch(e)
    {
        //throw e;
    }
}
    

function RenderRectSqr(id, data, wgt, color, pageId, typ, fcolor)
{    
    try
    {
        var rectSqrObj = null;
        var rectSqrObj = document.createElementNS(svgns, "rect");        
        rectSqrObj.id = id;
        rectSqrObj.setAttribute("page", pageId);
        rectSqrObj.setAttribute("shape", typ); 
        //rectSqrObj.style.position = "absolute";
        rectSqrObj.style.cursor = "default";
        var LTWH = data.split(':');
        rectSqrObj.setAttributeNS(null, 'x', LTWH[0]);
        rectSqrObj.setAttributeNS(null, 'y', LTWH[1]);
        rectSqrObj.setAttributeNS(null, 'width', LTWH[2]);
        rectSqrObj.setAttributeNS(null, 'height', LTWH[3]);
        rectSqrObj.setAttributeNS(null, 'fill', fcolor);
        rectSqrObj.setAttributeNS(null, 'stroke', color);
        rectSqrObj.setAttributeNS(null, 'stroke-width', parseInt(wgt) + 'px');
        //svgRoot.appendChild(rectSqrObj);
        
//        var divLeft, divTop, divWidth, divHeight;
//        rectSqrObj.setAttribute("divLeft", divLeft);
//        rectSqrObj.setAttribute("divTop", divTop);
//        rectSqrObj.setAttribute("divWidth", divWidth); 
//        rectSqrObj.setAttribute("divHeight", divHeight);
    
        return rectSqrObj;
    }
    catch(e)
    {
        //throw e;
    }
}

function Renderfhline(id, data, wgt, color, pageId, typ, fcolor)
{       
    if(d(id) != null)
    {
        return;
    }
    
    var ln = document.createElementNS(svgns, "polyline");        
    ln.setAttributeNS(null, "fill", fcolor);//ln.setAttribute("fill", "none");
    ln.setAttributeNS(null, "stroke", color);//ln.setAttribute("stroke", color);
    ln.setAttributeNS(null, "stroke-width", wgt);//ln.setAttribute("stroke-width", wgt);               
    
    //ln.style.zIndex = "inherit";
    //ln.style.position = "absolute";
    ln.style.cursor = "default";   
    ln.setAttribute("onMouseOver","function(){this.style.cursor='default';};");
    ln.setAttribute("id", id);
    ln.setAttribute("page", pageId);
    ln.setAttribute("shape", typ);              
    
    //trim m and e from the beginning and end of the string.
    //m and e come as part of the vml data string        
    //alert(data);
    data = data.replace("m", "");
    data = data.replace("e", "");
    data = data.replace("|", "");
    data = data.replace("l", " ");
    data = data.replace(" ", "");  
    
    ln.setAttributeNS(null, "points", data);//ln.setAttribute("points", data);   
    
    //try suspend unsuspend here.. svgRoot.suspendRedraw(0);svgRoot.unsuspendRedraw(0);svgRoot.forceRedraw()    
    //svgRoot.appendChild(ln);               
    regaincursor();
    
//    var divLeft, divTop, divWidth, divHeight;
//    ln.setAttribute("divLeft", divLeft);
//    ln.setAttribute("divTop", divTop);
//    ln.setAttribute("divWidth", divWidth); 
//    ln.setAttribute("divHeight", divHeight);
    
    return ln;
    
}

function RenderLine(id, data, wgt, color, pageId, typ, fcolor)
{
    
    //alert(id +  ' - '+ data +  ' - '+ wgt +  ' - '+ color +  ' - '+ pageId +  ' - '+ typ);
    try
    {
                
        var gElement = document.createElementNS(svgns, "g");
        gElement.setAttributeNS(null, "stroke", color);
        var fromToTokens = data.split('|');        
        //alert("loading : " + fromToTokens);
        var fromTokens = fromToTokens[0].split(',');
        var toTokens = fromToTokens[1].split(',');    
        
        var ln = document.createElementNS(svgns, "line");        
        ln.setAttributeNS(null, "x1", fromTokens[0]);
        ln.setAttributeNS(null, "y1", fromTokens[1]);
        ln.setAttributeNS(null, "x2", toTokens[0]);
        ln.setAttributeNS(null, "y2", toTokens[1]);        
        ln.setAttributeNS(null, "stroke-width", wgt);    
        //ln.setAttribute("stroke-opacity", "1.0");    
        ln.style.position = "absolute";        
        ln.style.cursor = "default";  
        ln.setAttribute("onMouseOver","function(){alert(this.id);this.style.cursor='default';};");      
        ln.setAttribute("id", id);
        ln.setAttribute("page", pageId);
        ln.setAttribute("shape", typ);   
        
        gElement.appendChild(ln);
        //svgRoot.appendChild(gElement);   
        
        /*
        var divLeft, divTop, divWidth, divHeight;
        divLeft = parseInt(fromTokens[0]) + "px"; //x1
        divTop = parseInt(fromTokens[1]) + "px"; //y1
        divWidth = parseInt(toTokens[0]) - parseInt(fromTokens[0]) + "px"; //x2 - x1
        divHeight = parseInt(toTokens[1]) - parseInt(fromTokens[1]) + "px"; //y2 - y1
        
        alert("hello? " + divLeft + " : " + divTop + " : " + divWidth + " : " + divHeight);  
        
        gElement.setAttribute("divLeft", divLeft);
        gElement.setAttribute("divTop", divTop);
        gElement.setAttribute("divWidth", divWidth); 
        gElement.setAttribute("divHeight", divHeight);
        */             
        return gElement;
    }
    catch(e)
    {
        //alert(e.description);
    }    
}

function MoveToTop( svgNode )
{
   svgNode.parent.appendChild( svgNode );
}


function MoveToBottom( svgNode )
{
   //alert(svgNode.parentNode.id);   
   svgNode.parentNode.insertBefore(svgNode, svgNode.parentNode.firstChild);
}


var svgns = "http://www.w3.org/2000/svg";

var svgRoot = null;
function CheckSvgParent()
{
    //alert(document);
    //alert(svgRoot.parentNode);
}

var svgDiv;
function InitSvgRoot()
{    
    svgRoot = document.createElementNS(svgns, "svg");
    svgRoot.id = "main_svgrootobj";
    svgRoot.setAttribute("width", "100%");
    svgRoot.setAttribute("height", "100%");
    svgRoot.setAttribute("overflow", "visible");    
    svgRoot.setAttribute("preserveAspectRatio", "none");
    svgRoot.setAttributeNS(null,'x','0px');
    svgRoot.setAttributeNS(null,'y','0px');
    svgRoot.setAttributeNS(null,'width',2000+'px');
    svgRoot.setAttributeNS(null,'height',2000+'px');     
    
    svgDiv = document.createElement("div");
    svgDiv.style.zIndex = '10';
    svgDiv.id = "main_svgrootobj_div";
    //svgDiv.style.backgroundColor = 'transparent';
    svgDiv.style.position = 'relative';
    document.body.appendChild(svgDiv);    
    svgDiv.appendChild(svgRoot);
}


function trimPt(inputstr)
{   
    //vml points have pt - trim the 'pt' portion 
    var retVal = inputstr.substring(0, inputstr.indexOf('pt'));    
    return retVal;
}



var maxZindex = 200;


// ends line being drawn
function stopLine2(event) 
{
    var offset = cumulativeOffset(d('main_svgrootobj_div'));
    var pX = event.pageX - offset[0];//event.clientX + self.pageXOffset - 0;
    var pY = event.pageY - offset[1];//event.clientY + self.pageYOffset - 0;
    
    //mousex = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    //mousey = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    
    if(drawStarted)
    {
        drawStarted = false;
        if(currentToolName == "line")
        {  
           lineObj.setAttribute("x2", pX + 'px');
           lineObj.setAttribute("y2", pY + 'px');
           
           SaveShape(lineObj);           
        }
        else if(currentToolName == "fhline")
        {
            var tmp = fhlineObj.getAttribute("points");
            tmp += " " + pX + "," + pY;
            fhlineObj.setAttribute("points", tmp);
            
            SaveShape(fhlineObj);
        }    
        else if(currentToolName == "rectsqr")
        {
            SaveShape(rectSqrObj);
        }
        else if(currentToolName == "circle")
        {
            //alert('1');
            SaveShape(circleObj);
        }
    }
}

function DelDrawingEl(d_ID)
{   
    try 
    {
        d('main_svgrootobj').removeChild(d(d_ID));
    } catch(e) {}
    try 
    {
        d('main_svgrootobj').removeChild(d(d_ID).parentNode);
    } catch(e) {}
        
}

function SaveLine(elTag)
{
	var data = "a=su&pt0=" + escape(txt) 
	    + "&tc=1&cd0=1D&ti0=" + elTag.id 
	    + "&fc0=" + parseInt(elTag.style.width) + "&bc0=0" +
	    "&px0=" + parseInt(elTag.style.left) 
	    + "&py0=" + parseInt(elTag.style.top) 
	    + "&sy0=0" + "&pg0=" + elTag.getAttribute('page');
	clearTimeout(autoSaveTimeout);
	queue.push(data);
	SendData(1);
}

function GetPtValueFromPx(px_val)
{
    //1 pt = 1.3px
    return Math.ceil(parseInt(px_val)/1.333) + "pt";
}

function SaveShape(shapeObj)
{
    //update local state
    drawingTagCollection[shapeObj.id] = shapeObj.id;
    
    var shapeType = shapeObj.getAttribute("shape");
    var data;
    if(shapeType)
    {
        if(shapeType == "line")
        {
            //read from, to, stroke object's - weight, color
            var pathData = 
            GetPtValueFromPx(shapeObj.getAttribute("x1")) + "," + GetPtValueFromPx(shapeObj.getAttribute("y1")) + "|" +
            GetPtValueFromPx(shapeObj.getAttribute("x2")) + "," + GetPtValueFromPx(shapeObj.getAttribute("y2")); 
            //alert("saving : " + pathData);
            /*+ "|" + 
            document.defaultView.getComputedStyle(shapeObj, null).marginLeft + "," +
            document.defaultView.getComputedStyle(shapeObj, null).marginTop;
            */
            var fillcolval = shapeObj.getAttribute("fill")!= null ? shapeObj.getAttribute("fill") : "none";
            data = "a=su&dt0=" + pathData 
            + "&tc=1&cd0=1&di0=" + shapeObj.id 
            + "&stype0=" + shapeObj.getAttribute("shape")
            + "&wgt0=" + GetPtValueFromPx(shapeObj.getAttribute("stroke-width"))
            + "&col0=" + shapeObj.parentNode.getAttribute("stroke")
            + "&fillcol0=" + fillcolval
            + "&fc0=" + "" + "&bc0=0" 
            + "&px0=" + "" + "&py0=" + "" + "&sy0=0" 
	        + "&pg0=" + shapeObj.getAttribute('page');
	        
	        //alert(pathData + " : " + document.defaultView.getComputedStyle(shapeObj, null).marginLeft
	        //+ ":" + document.defaultView.getComputedStyle(shapeObj, null).marginTop);
        }
        
        if(shapeType == "fhline")
        {
            //read from, to, stroke object's - weight, color
            var pathData = shapeObj.getAttribute("points");
            //transform pathData to vml 
            //prefix m to first point, l to second point and suffix with e
            //m x1,y1 
            var allTokens = pathData.split(' ');
            var pathDataFinal = "";
            if(allTokens.length > 0)
            {
                if(allTokens.length == 1)
                {
                    //one point                    
                    pathDataFinal = "m" + allTokens[0] + " e";
                }
                else if(allTokens.length == 2)
                {
                    pathDataFinal = "m" + allTokens[0] + " l" + allTokens[1] + " e";
                }            
                else if(allTokens.length == 3)
                {
                    pathDataFinal = "m" + allTokens[0] + " l" + allTokens[1] + "," +allTokens[2] + " e";
                }
                else
                {
                    pathDataFinal = "m" + allTokens[0] + " l" + allTokens[1] + ",";
                    for(var i=2; i<allTokens.length; i++)
                    {
                        pathDataFinal += allTokens[i] + ",";
                    }
                    //var lastPointTokens = allTokens[allTokens.length-1].split(',')
                    //pathDataFinal += 
                }
            }
            
            var fillcolval = shapeObj.getAttribute("fill")!= null ? shapeObj.getAttribute("fill") : "none";
            //alert(pathDataFinal);
            data = "a=su&dt0=" + pathDataFinal + "&tc=1&cd0=1&di0=" + shapeObj.id 
            + "&stype0=" + shapeObj.getAttribute("shape")
            + "&wgt0=" + GetPtValueFromPx(shapeObj.getAttribute("stroke-width"))
            + "&col0=" + shapeObj.getAttribute("stroke")
            + "&fillcol0=" + fillcolval
            + "&fc0=" + "" + "&bc0=0" +
	        "&px0=" + "" + "&py0=" + "" + "&sy0=0" + "&pg0=" + shapeObj.getAttribute('page');	        
	       
        }
        
        if(shapeType == "rectsqr")
        {            
            if(parseInt(shapeObj.getAttributeNS(null, "height")) != 0 && parseInt(shapeObj.getAttributeNS(null, "width")) != 0)
            {
                var fillcolval = shapeObj.getAttribute("fill")!= null ? shapeObj.getAttribute("fill") : "none";
                //alert(shapeObj.style.cssText); LTWH order
                var styleProps = shapeObj.getAttributeNS(null, "x") + ":" + shapeObj.getAttributeNS(null, "y") + ":" + shapeObj.getAttributeNS(null, "width") + ":" + shapeObj.getAttributeNS(null, "height");
                data = "a=su&dt0=" + styleProps + "&tc=1&cd0=1&di0=" + shapeObj.id 
                + "&stype0=" + shapeObj.getAttribute("shape")
                + "&wgt0=" + GetPtValueFromPx(shapeObj.getAttribute("stroke-width"))
                + "&col0=" + shapeObj.getAttribute("stroke")
                + "&fillcol0=" + fillcolval
                + "&fc0=" + "" + "&bc0=0" +
	            "&px0=" + "" + "&py0=" + "" + "&sy0=0" + "&pg0=" + shapeObj.getAttribute('page');
	            
	            //alert(data);
            }
        }        
        
        if(shapeType == "circle")
        {
            //alert('1');
            /*
            var styleProps = circleObj.getAttributeNS(null, "cx") + " : " +
                            circleObj.getAttributeNS(null, "cy") + " : " +
                            circleObj.getAttributeNS(null, "rx") + " : " +
                            circleObj.getAttributeNS(null, "ry");
            */
            
            
            var leftVal =  parseInt(shapeObj.getAttributeNS(null, "cx")) - parseInt(shapeObj.getAttributeNS(null, "rx")) + "px";
            var topVal = parseInt(shapeObj.getAttributeNS(null, "cy")) - parseInt(shapeObj.getAttributeNS(null, "ry")) + "px";
            var widthVal = parseInt(shapeObj.getAttributeNS(null, "rx")) * 2 + "px";
            var heightVal = parseInt(shapeObj.getAttributeNS(null, "ry")) * 2 + "px";
            var fillcolval = shapeObj.getAttribute("fill")!= null ? shapeObj.getAttribute("fill") : "none";
            var styleProps = leftVal + ":" + topVal + ":" + widthVal + ":" + heightVal; 
            
            data = "a=su&dt0=" + styleProps + "&tc=1&cd0=1&di0=" + shapeObj.id 
                + "&stype0=" + shapeObj.getAttribute("shape")
                + "&wgt0=" + GetPtValueFromPx(shapeObj.getAttribute("stroke-width"))
                + "&col0=" + shapeObj.getAttribute("stroke")
                + "&fillcol0=" + fillcolval 
                + "&fc0=" + "" + "&bc0=0" +
	            "&px0=" + "" + "&py0=" + "" + "&sy0=0" + "&pg0=" + shapeObj.getAttribute('page');
	            
	        //alert(styleProps);
        }
        
        clearTimeout(autoSaveTimeout);
	    queue.push(data);
	    SendData(0);	    
    }
}
