/*
 * Copyright 2007-2008 fyiReporting Software, LLC  (www.fyireporting.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *
*/


var barHeight=18;
var phHeight=30, bodyHeight=80-barHeight-phHeight, pfHeight=120-phHeight-bodyHeight-barHeight-barHeight;

var mouseDownPositionY = -9999;
var mouseDownPositionX = -9999;
var mouseObj;

var ri_selected;

var insert_onclick;

// Size the object based on the size of the text
function autoSizeSelected() {
    autoSize(ri_selected);
}
function autoSize(ri) {
    if (ri == null)
        return;

    var ah = getRIProperty(ri, "ActualHeight");
    var aw = getRIProperty(ri, "ActualWidth");
    
    ri.height = ah;
    ri.width = aw;
    ri.Clip.Rect = "0, 0, " + aw.toString() + ", " + ah.toString();
}

function insertCurrent(sender, args) {
    setStatus(sender, "Insert:" + insert_onclick);
    if (insert_onclick == null)
        return;
    var io=null;
    switch (insert_onclick)
    {
        case "text":
            io=insertText(sender, "text", args.getPosition(null).x, args.getPosition(null).y);
            break;
    }
    insert_onclick=null;
    if (io != null)
        selectRIObj(io);
}

function insertText(sender, name, x, y) {
    var i=1;
    var newname=name;
    while (sender.FindName(newname) != null)
    {
        newname = name + i;
        i++;
    }
    var props = getUIObject();          // get the current UI properties

    var rpos = sender["Canvas.Top"];
    var txt=
        "<Canvas Name ='"+ newname+"' Canvas.Left='" + x + "' Canvas.Top='"+(y-rpos)+"' Height='12' Width='60' "+
        "Background='" + props.bkcolor+"'" +
		" MouseLeftButtonDown='riDown' MouseMove='riMove' MouseLeftButtonUp='riUp'>" +
		" <Canvas.Clip> <RectangleGeometry Rect='0,0,60,12' /></Canvas.Clip>" +
		" <TextBlock FontFamily='" + props.font + 
		    "' FontSize='"+   ConvertPointToPixel(props.fontSize-0) +
		    "' FontWeight='"+ (props.isBold?"Bold":"Normal")+ 
		    "' FontStyle='"+ (props.isItalic?"Italic":"Normal")+ 
		    "' TextDecorations='"+ (props.isUL?"Underline":"None")+ 
		    "' Foreground='"+ props.color + "' "+
		     
		    ">Text</TextBlock>" +
		"</Canvas>";
 
    var plugin = sender.getHost();
 
    var tb = plugin.Content.CreateFromXaml(txt);
    sender.Children.Add(tb);
    autoSize(tb);
    return tb;
}

function setCurrentInsert(type) {
    insert_onclick=type;
}

function moveBars(sender, name, offset) {
    switch (name)
    {
        case "rph":
            phHeight += offset;
            if (phHeight < 0)
                phHeight = 0;
            break;
        case "rpf":
            pfHeight += offset;
            if (pfHeight < 0)
                pfHeight = 0;
            break;
        case "rbody": 
            bodyHeight += offset;
            if (bodyHeight < 0)
                bodyHeight = 0;
            break;
        default:
            return;
    }

    try
    {
        var bar;
        
        bar = sender.findName("rpf_data");
        bar["Canvas.Top"] = phHeight + barHeight + bodyHeight + barHeight;
        bar = sender.findName("rpf");
        bar["Canvas.Top"] =  phHeight + barHeight + bodyHeight + barHeight + pfHeight;

        bar = sender.findName("rbody_data");
        bar["Canvas.Top"] = phHeight + barHeight;
        bar = sender.findName("rbody");
        bar["Canvas.Top"] = phHeight + barHeight + bodyHeight;

        bar = sender.findName("rph");
        bar["Canvas.Top"] = phHeight;        
        
    }
    catch (err)
    {
    setStatus(sender, err);
    }

}

function barDown(sender, args) {
    sender.captureMouse();
    mouseObj = sender.Name;
    setStatus(sender, "mousedown: " + mouseObj);
    mouseDownPositionY = args.getPosition(null).y;
}

function barUp(sender, args) {
    sender.releaseMouseCapture();
    mouseDownPositionY = -9999;
    setStatus(sender, "mouseup: " + mouseObj);
}
function barLeave(sender, args) {
    return;
 /*  this is too sensitive   
    if (mouseDownPositionY == -9999)
        return;
    sender.releaseMouseCapture();
    mouseDownPositionY = -9999;
    setStatus(sender, "mouse leave: " + sender.Name);
 */
}

function barMove(sender, args) {
    if (mouseDownPositionY == -9999)
        return;

    var offset = args.getPosition(null).y - mouseDownPositionY;    
    mouseDownPositionY = args.getPosition(null).y;
    setStatus(sender, "mousemove: " + offset);

    moveBars(sender, mouseObj, offset);
}

function deleteCurrent() {
    if (ri_selected == null)
        return;
    var p = ri_selected.GetParent();
    p.Children.Remove(ri_selected);
    ri_selected=null;
}

function riDown(sender, args) {
    sender.captureMouse();
    mouseObj = sender.Name;
    mouseDownPositionY = args.getPosition(null).y;
    mouseDownPositionX = args.getPosition(null).x;
    selectRIObj(sender);
}

function riUp(sender, args) {
    sender.releaseMouseCapture();
    mouseDownPositionY = -9999;
    mouseDownPositionX = -9999;
    setStatus(sender, "mouseup: " + mouseObj);
}
function riLeave(sender, args) {
    return;
    /* this is too sensitive
    if (mouseDownPositionY == -9999)
        return;
    sender.releaseMouseCapture();
    mouseDownPositionY = -9999;
    mouseDownPositionX = -9999;
    setStatus(sender, "mouse leave: " + sender.Name);
*/
}
function riMove(sender, args) {
    if (mouseDownPositionY == -9999)
        return;
    if (ri_selected == null)
        return;
    if (ri_selected.Name != sender.Name)
    {
        // this happens when user moves mouse out of bounds of canvas and then comes back
        sender.releaseMouseCapture();
        mouseDownPositionY = -9999;
        mouseDownPositionX = -9999;
        return;
    }
        
    var yoffset = args.getPosition(null).y - mouseDownPositionY;    
    mouseDownPositionY = args.getPosition(null).y;
    var xoffset = args.getPosition(null).x - mouseDownPositionX;    
    mouseDownPositionX = args.getPosition(null).x;
    setStatus(sender, "mousemove: (" + xoffset + ", " + yoffset + ")");
    if (yoffset != 0)
    {
        var t = ri_selected["Canvas.Top"] - 0 + yoffset;
        if (t >= 0)
            ri_selected["Canvas.Top"] = t;
    }
    if (xoffset != 0)
    {
        var l = ri_selected["Canvas.Left"] - 0 + xoffset;
        if (l >= 0)
            ri_selected["Canvas.Left"] = l;
    }

//    riBars(sender, mouseObj, offset);
}

function setStatus(sender, msg) {
    sender.findName("status").Text = msg;
}

function selectRIObj(sender) {
    ri_selected = sender;
    setStatus(sender, ri_selected.Name + " selected");
    
    var text = getRIProperty(ri_selected, "text");
    var isBold = getRIProperty(ri_selected, "FontWeight") == "Bold";
    var isItalic = getRIProperty(ri_selected, "FontStyle") == "Italic";
    var isUL = getRIProperty(ri_selected, "textDecorations") == "Underline";
    var font = getRIProperty(ri_selected, "FontFamily");
    var fontSize = ConvertPixelToPoint(getRIProperty(ri_selected, "FontSize")).toString();
    var color = getRIProperty(ri_selected, "foreground").Color.toString();
    var bcolor = ri_selected.background.Color.toString();
    setUIObject(ri_selected, text, isBold, isItalic, isUL, font, fontSize, color, bcolor);
}

function changeFont(cb) {
    var f =cb[cb.selectedIndex].text; 

    changeRIProperty("FontFamily", f);
}
function changeFontBold(isBold) {
    changeRIProperty("FontWeight", isBold? "Bold": "Normal");
}
function changeFontItalic(isItalic) {
    changeRIProperty("FontStyle", isItalic? "Italic": "Normal");
}
function changeFontUL(isUL) {
    changeRIProperty("textDecorations", isUL? "Underline": "None");
}
function changeFontHeight(cb) {
    if (ri_selected == null)
        return;
    var fhpt =cb[cb.selectedIndex].text; 
    var fh = ConvertPointToPixel(fhpt - 0);

    changeRIProperty("FontSize", fh);
}

function changeBackColor(cb) {
    if (ri_selected == null)
        return;
    var c =cb[cb.selectedIndex].text; 

    ri_selected.background = c;    

}

function changeColor(cb) {
    if (ri_selected == null)
        return;
    var c =cb[cb.selectedIndex].text; 

    changeRIProperty("foreground", c);
}

function changeText(txt) {
    if (ri_selected == null)
        return;
    changeRIProperty("text", txt);
}

function getRIProperty(ri, property) {
    if (ri == null)
        return "";

   for (i=0; i < ri.children.count; i++) {     
        tb = ri.children.getItem(i);
        if (tb == "TextBlock")
        {
            return tb[property];    
        }
   }
   return "";
}

function changeRIProperty(property, val) {
    if (ri_selected == null)
        return;

   for (i=0; i < ri_selected.children.count; i++) {     
        tb = ri_selected.children.getItem(i);
        if (tb == "TextBlock")
        {
            try {
                tb[property] = val;    
            } catch (ex) {alert("Exception:" + ex + " Prop=" + property  + " Old val=" + tb.Text + " New val=" + val);}
        }
   }
}


function ConvertPointToPixel(px) {
    var result = px * 96 / 72.27;	// convert to pixels

    return Math.round(result);

}
function ConvertPixelToPoint(pt) {
	var result = (pt * 72.27) / 96;	// convert to points from pixels
	return Math.round(result);
}

function keyUp(sender, keyEventArgs) {
    // due to a bug in Silverlight 1.0 arrow keys aren't passed on the keyDown event
    //  remove event when this is fixed (or we'll get double the action)
    
    if (keyEventArgs.key >= 14 && keyEventArgs.key <= 17)
        keyHit(sender, keyEventArgs);

    setStatus(sender, "key up:"+ keyEventArgs.key);
    
}
function keyHit(sender, keyEventArgs) {
    if (ri_selected == null)
        return;

    if (keyEventArgs.shift) {
        keyResize(sender, keyEventArgs);
        return;
    }

    var ri = sender.findName(ri_selected.Name);
    
    switch (keyEventArgs.key)
    {
        case 5:         // ctrl key
            return;
        case 19:        // delete key
            deleteCurrent();
            break;
        case 15:        // up arrow
        case 50:        // 'u'p
            var top = ri["Canvas.Top"];
            top = top - 1;
            if (top > 0)
                ri["Canvas.Top"] = top;
            break;
        case 17:        // down arrow
        case 33:        // 'd'own
            var top = ri["Canvas.Top"];
            top = top + 1;
            ri["Canvas.Top"] = top;
            break;
        case 16:        // right arrow
        case 47:        // 'r'ight
            var left = ri["Canvas.Left"];
            left = left + 1;
            ri["Canvas.Left"] = left;
            break;
        case 14:        // left arrow
        case 41:        // 'l'eft
            var left = ri["Canvas.Left"];
            left = left - 1;
            if (left >= 0)
                ri["Canvas.Left"] = left;
            break;
        default:
            break;
    }
}

function keyResize(sender, keyEventArgs) {

    var ri = sender.findName(ri_selected.Name);
    var h = ri.height;
    var w = ri.width;
    switch (keyEventArgs.key)
    {
        case 5:         // ctrl key
            return;
        case 15:        // up arrow
        case 50:        // 'u'p
            h = h - 1;
            if (h > 0)
                ri.height = h;
            break;
        case 17:        // down arrow
        case 33:        // 'd'own
            h = h + 1;
            ri.height = h;
            break;
        case 16:        // right arrow
        case 47:        // 'r'ight
            w = w + 1;
            ri.width = w;
            break;
        case 14:        // left arrow
        case 41:        // 'l'eft
            w = w - 1;
            if (w > 0)
                ri.width = w;
            break;
        default:
            return;
    }
    
    ri.Clip.Rect = "0, 0, " + w.toString() + ", " + h.toString();
}
