// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.4/standard/wwwroot/WEB-INF/config/modules/standard/print/js/print_config.js $ 
// $Date: 29-01-08 12:55 $
// $Revision: 12 $ 
// $Author: Kpo $
// =============================================================== 


/*********************************************/
/* Global objeject containing print config   */
/*********************************************/
var printObject;

function PrintObject(name)
{
    this.name = name;
    this.title = cbInfo.getString('print.jsprint_config.title');
    this.header = '';
    this.page = 'print.pdf';
    this.printOptions = new Array();
    this.dialog;
    this.toolMode = -1;
    this.fence;
    this.fenceVisible = false;
    this.popUpBlockerAlertText = cbInfo.getString('standard.error.browser_blocks_popups');
}

function PrintObjectOption()
{
    this.name;
    this.type = 'input';
    this.displaytext = '-';
    this.input = new Array();
    this.width = '185px';
    this.height = null;
    this.attributelist;
}

/*********************************************/
/* Set global print objeject                 */
/*********************************************/
function print_getConfig(name)
{
    if(!printObject)  //if printObject not defined create new
        printObject = new PrintObject(name);
    if(printObject.name != name)  //if printObject not current create new
        printObject = new PrintObject(name);

    //clean fence
    if(printObject.fence)
        printObject.fence.clear();
    
    //read config
    var url = getServletUrl();
    url+= "?page=print.config";
    url+= "&sessionid="+getSessionId();
    url+= "&profile="+getProfile();
    url+= "&printconfig="+printObject.name;
    printObject.print_getConfigRequest(url);

    // Create and show dialog
    printObject.addDialog();
}




/*********************************************/
/* Get an option value                       */
/*********************************************/
PrintObjectOption.prototype.getValue = function()
{
    var value = 'UNDEFINED';
    switch(this.type)
    {
        case 'dropdown':
            var e = getElement(printObject.name+'_'+this.name+'_print_input');
            value = e.options[e.selectedIndex].value;
            if(value==null || value=='null')
                value = 'UNDEFINED';
        break;
        case 'checkbox':
            var e = getElement(printObject.name+'_'+this.name+'_print_input');
            value = e.checked;
            if(value==true)
            {
                if(this.input[0].postvalue)
                    value = this.input[0].postvalue;
            }
        break;
        case 'textarea':
        case 'hidden':
        case 'input':
            var e = getElement(printObject.name+'_'+this.name+'_print_input');
            value = e.value;
        break;
    }
    return value
}

/*********************************************/
/* Get an option value from name             */
/*********************************************/
PrintObject.prototype.getOptionValue = function(name)
{
    for(var i=0;i<this.printOptions.length;i++)
    {
        if(this.printOptions[i].name == name)
            return this.printOptions[i].getValue();
    }
    return 'UNDEFINED';
}



/*********************************************/
/* Get config                                */
/*********************************************/
PrintObject.prototype.print_getConfigRequest = function(url)
{
    var domDoc = cbhttp_getRequestDom(url);
    var root = domDoc.getElementsByTagName("printconfig")[0];
    var j = cbhttp_getLength(root);
    var node = cbhttp_getFirstChild(root);
    for (var iNode = 0; iNode < j; iNode++) 
    {
        if(node.nodeName == 'title')
            this.title = cbhttp_getNodeValue(node);
        if(node.nodeName == 'header')
            this.header = cbhttp_getNodeValue(node);
        if(node.nodeName == 'page')
            this.page = cbhttp_getNodeValue(node);
        if(node.nodeName == 'options')
        {
            var optionArray = node.getElementsByTagName("option");
            //for hver optionnode
            for (var m = 0; m < optionArray.length; m++) 
            {
                this.printOptions[m] = new PrintObjectOption();
                if(optionArray[m].getAttribute('name'))
                    this.printOptions[m].name = optionArray[m].getAttribute('name');
                if(optionArray[m].getAttribute('type'))
                    this.printOptions[m].type = optionArray[m].getAttribute('type');
                if(optionArray[m].getAttribute('width'))
                    this.printOptions[m].width = optionArray[m].getAttribute('width');
                if(optionArray[m].getAttribute('height'))
                    this.printOptions[m].height = optionArray[m].getAttribute('height');
                
                this.printOptions[m].attributelist = optionArray[m].attributes;

                if(optionArray[m].getElementsByTagName("displaytext"))
                    this.printOptions[m].displaytext = optionArray[m].getElementsByTagName("displaytext")[0].firstChild.nodeValue

                if(optionArray[m].getElementsByTagName("inputvalues"))
                {
                    var inputvalues = optionArray[m].getElementsByTagName("inputvalues");
                    if(inputvalues.length)
                    {
                        if(inputvalues[0].getElementsByTagName("input"))
                        {
                            var inputv = inputvalues[0].getElementsByTagName("input");
                            
                            for(var n=0;n<inputv.length;n++)
                            {
                                var pr_postvalue = null;
                                if(inputv[n].getAttribute('inputvalue'))
                                    pr_postvalue = inputv[n].getAttribute('inputvalue');

                                var pr_defaultvalue = null;
                                if(inputv[n].getAttribute('default'))
                                    pr_defaultvalue = inputv[n].getAttribute('default');

                                var pr_text = null;
                                if(inputv[n].firstChild)
                                {
                                    if(inputv[n].firstChild.nodeValue)
                                        pr_text = inputv[n].firstChild.nodeValue;
                                }
                                var attlist = inputv[n].attributes;
                                
                                this.printOptions[m].input[n] = {text:pr_text,postvalue:pr_postvalue,defaultvalue:pr_defaultvalue,attributelist:attlist};
                            }
                        }
                    }
                }
            }
        }
        node = cbhttp_getNextNode(node)
    }
}

/*********************************************/
/* Create dialog                             */
/*********************************************/
PrintObject.prototype.addDialog = function()
{
    this.dialog = new Dialog(this.title,printObject.closeHandler,this.name+'_print');
    var html = '';
    html+='            <table id="'+this.name+'_print_dialog_table" class="divtable" style="width:100%;">';
    if(this.header)
    {
        html+='                <tr align="left">';
        html+='                    <td colspan="2" id="'+this.name+'_print_header">'+this.header+'</td>';
        html+='                </tr>';
    }

    for(var i=0;i<this.printOptions.length;i++)
    {
        var po = this.printOptions[i];
        if(po.type == 'dropdown')
        {
            html+='                <tr>';
            html+='                    <td colspan="2">'+po.displaytext+'</td>';
            html+='                </tr>';
            html+='                <tr>';
            html+='                    <td colspan="2" align="left">';
            html+='                        <select onfocus="" onchange="printObject.setFence()" size="1" id="'+this.name+'_'+po.name+'_print_input" style="width:'+po.width+';">';
            for(var j=0;j<po.input.length;j++)
            {
                html+='                            <option value="'+po.input[j].postvalue+'">'+po.input[j].text+'</option>';
            }
            html+='                        </select>';
            html+='                    </td>';
            html+='                </tr>';
        }
        else if(po.type == 'checkbox')
        {
            html+='                <tr>';
            html+='                    <td align="left" style="width:10px;">';
            html+='                        <input value="'+po.input[0].postvalue+'" id="'+this.name+'_'+po.name+'_print_input" type="checkbox" onclick="printObject.setFence()"/>';
            html+='                    </td>';
            html+='                    <td>'+po.displaytext+'</td>';
            html+='                </tr>';
        }
        else if(po.type == 'textarea')
        {
            var style = '';
            if(po.height)
                style+='height:'+po.height+';';
            if(po.width)
                style+='width:'+po.width+';';
            html+='                <tr>';
            html+='                    <td colspan="2">'+po.displaytext+'</td>';
            html+='                </tr>';
            html+='                <tr>';
            html+='                    <td colspan="2" align="left">';
            html+='                        <textarea id="'+this.name+'_'+po.name+'_print_input" style="'+style+'"></textarea>';
            html+='                    </td>';
            html+='                </tr>';
        }
        else if(po.type == 'hidden')
        {
            html+='                <tr>';
            html+='                    <td colspan="2" align="left" style="display:none;">';
            html+='                        <input id="'+this.name+'_'+po.name+'_print_input" type="hidden"/>';
            html+='                    </td>';
            html+='                </tr>';
        }
        else if(po.type == 'input')
        {
            var style = '';
            var type = '';
            if(po.type != 'input')
                type = ' type="'+po.type+'"';
            if(po.height)
                style+='height:'+po.height+';';
            if(po.width)
                style+='width:'+po.width+';';
            html+='                <tr>';
            html+='                    <td colspan="2">'+po.displaytext+'</td>';
            html+='                </tr>';
            html+='                <tr>';
            html+='                    <td colspan="2" align="left">';
            html+='                        <input id="'+this.name+'_'+po.name+'_print_input" style="'+style+'"'+type+'/>';
            html+='                    </td>';
            html+='                </tr>';
        }
        
    }
    html+='                <tr style="height:5px"></tr>';
    html+='                <tr>';
//    html+='                    <td colspan="2" align="right">';
    html+='                    <td colspan="2">';
    html+='                        ' +cbInfo.getString('print.js.printrequire') +' <a href="http://www.adobe.com/products/acrobat/readstep2.html" target="_blank">Adobe Reader</a>';
    html+='                    </td>';
    html+='                </tr>';
    html+='                <tr style="height:5px"></tr>';
    html+='                <tr align="right">';
    html+='                    <td colspan="2" align="right">';
    html+='                        <button class="menubutton" onclick="printObject.select()" style="width:110px;">' +cbInfo.getString('standard.button.select_mapextent') +'</button>';
    html+='                        <button class="menubutton" onclick="printObject.dialog.closeDialog()">' +cbInfo.getString('standard.button.cancel') +'</button>';
    html+='                    </td>';
    html+='                </tr>';
    html+='            </table>';

    this.dialog.addContentHTML(html);
    this.setDefaultValues();
    this.dialog.showDialog();
}

/*********************************************/
/* set default values i dialog               */
/*********************************************/
PrintObject.prototype.setDefaultValues = function()
{
    for(var i=0;i<this.printOptions.length;i++)
    {
        var po = this.printOptions[i];
        for(var j=0;j<po.input.length;j++)
        {
            var e = getElement(this.name+'_'+po.name+'_print_input');
            if(po.type == 'dropdown')
            {
                var defaultvalue = po.getDefaultValue(po.input[j].defaultvalue);
                if(defaultvalue == true)
                    e.options[j].selected = 'selected';
            }
            else if(po.type == 'checkbox')
            {
                var defaultselect = 'false';
                if(po.input)
                    defaultselect = po.getDefaultValue(po.input[0].defaultvalue);
                e.checked = defaultselect;
            }
            else if(po.type == 'textarea' || po.type == 'input' || po.type == 'hidden')
            {
                if(po.input[0])
                    e.value = po.getDefaultValue(po.input[0].defaultvalue);
            }
        }
    }
}

/*********************************************/
/* default function to set current scale on  */
/* printscale dropdown                       */
/* - use custom function if necessary        */
/*********************************************/
function setPrintScaleValue()
{
    var oe = getElement(printObject.name+'_printscale_print_input');
    oe.options[0].text = '1:'+parseInt(cbKort.getCurrentScale());
    oe.options[0].value = parseInt(cbKort.getCurrentScale());
    return true; //return true if current scale schould be selected by default
}



/*********************************************/
/* Show select fence                         */
/*********************************************/
PrintObject.prototype.select = function()
{
    if(!this.fenceVisible)
    {
        if(this.toolMode==-1)
            this.toolMode = cbKort.registerToolMode(printObject.init, printObject.down, printObject.move, null, null, printObject.toolChangeHandler);
        cbKort.setToolMode(this.toolMode);
        if(!this.fence)
            this.fence = new Fence();
        this.fenceVisible = true;
        this.setFence();
    }
}

/*********************************************/
/* Read selected options and set fence       */
/*********************************************/
PrintObject.prototype.setFence = function()
{
    if(this.fenceVisible)
    {
        this.getPrintValuesAndSetFence();
    }
}

/*********************************************/
/* Toolmode activated                        */
/*********************************************/
PrintObject.prototype.init = function()
{
    cbKort.map.style.cursor = 'url("images/standard/cursors/print_fence.cur"),crosshair';
}
/*********************************************/
/* Toolmode down handler                      */
/*********************************************/
PrintObject.prototype.down = function(mouseX,mouseY)
{
    var pc = cursorLocationCorrection(mouseX,mouseY);
    mouseX = pc.x;
    mouseY = pc.y;
    
    printObject.doPrint(mouseX,mouseY);
}
/*********************************************/
/* Toolmode move handler                      */
/*********************************************/
PrintObject.prototype.move = function(mouseX,mouseY)
{
    var pc = cursorLocationCorrection(mouseX,mouseY);
    mouseX = pc.x;
    printObject.fence.setFencePosition(mouseX,mouseY);
}
/*********************************************/
/* Dialog close handler                      */
/*********************************************/
PrintObject.prototype.closeHandler = function()
{
    if(cbKort.toolMode == printObject.toolMode)
        cbKort.setToolMode(cbKort.lastMode);
}
/*********************************************/
/* Toolmode change handler                   */
/*********************************************/
PrintObject.prototype.toolChangeHandler = function()
{
    printObject.fence.clear();
    printObject.fenceVisible = false;
}

/*********************************************/
/* Print the map                             */
/*********************************************/
PrintObject.prototype.doPrint = function(mouseX,mouseY)
{
    var url = getServletUrl();
    url+= '?page='+this.page;
    url+= "&sessionid="+getSessionId();
    url+= "&profile="+getProfile();

    // get current layers
	var layers = cbKort.getLayers();
    var wrkspce = getElement('wrkspcid');
    if(wrkspce)
    {
        var wrkspcid = wrkspce.value-0;
        if(wrkspcid>0)
            layers = layers+' theme-workspace&wrkspcid='+wrkspcid;
    }
    url+= "&layers="+layers;

    // set scalebarname
    if(getElement('scalebarname'))
        url+='&scalebarname=pdf';
    
    // get mapext
    var minx = mouseX - parseInt(this.width/2);
    var miny = mouseY + parseInt(this.height/2);
    var maxx = mouseX + parseInt(this.width/2);
    var maxy = mouseY - parseInt(this.height/2);
    
    var llcoords = cbKort.getWorldCoordinate(minx,miny);
    var urcoords = cbKort.getWorldCoordinate(maxx,maxy);
    var mapext = llcoords+'_'+urcoords;
    mapext = mapext.replace(/_/g,',');
    mapext = mapext.replace(/ /g,',');
    url+='&mapext='+mapext;
    
    // set pageformat and orientation
    var printformats = this.getOptionValue('printformats').split('_');
    url+='&pageformat='+printformats[0];
    url+='&orientation='+printformats[1];

    // add config params
    for(var i=0;i<this.printOptions.length;i++)
    {
        var v = this.printOptions[i].getValue();
        if(this.printOptions[i].type=='textarea')
        {
            var e = getElement(this.name+'_'+this.printOptions[i].name+'_print_input');
            var ret = true;
            if(v.length>0)
                ret = validRegex( e, cbInfo.getString('print.js.text_not_valid_1'), '[^\<\>]', v );
            if(!ret)
                return false;
            v = v.replace(/&/g,'');
            v = v.replace(/#/g,'');
            v = v.replace(/\n/g,'QQQX');
        }
        if(v != 'UNDEFINED' && v != '' && v != null)
        {
            url+= '&'+this.printOptions[i].name+'='+v;
            if(this.printOptions[i].name=='ppi')
                url+= '&map_resolution='+v;
        }
        else if(this.printOptions[i].type=='checkbox')
            url+= '&'+this.printOptions[i].name+'='+v;
    }

    // show pdf in a popup
    if(testPopupBlocker())
    {
        window.open(url);
        this.closeHandler();
        this.dialog.closeDialog();
    }
    else
        alert(this.popUpBlockerAlertText);
}

/*********************************************/
/* Get paper size in meter from config       */
/* - requires: option name="printformats"    */
/*********************************************/
PrintObject.prototype.getPrintformatValues = function(printformat)
{
    var outputwidth = 0;
    var outputheight = 0;
    
    var url = getServletUrl();
    url+= "?page=print.formats";
    url+= "&sessionid="+getSessionId();
    url+= "&printformat="+printformat;
    
    var domDoc = cbhttp_getRequestDom(url);
    var outputsize = domDoc.getElementsByTagName("map")[0];
    if(outputsize.getAttribute('width'))
    {
        outputwidth = outputsize.getAttribute('width');
        outputwidth = (outputwidth-0)/100;
    }
    if(outputsize.getAttribute('height'))
    {
        outputheight = outputsize.getAttribute('height');
        outputheight = (outputheight-0)/100;
    }

    return {outputwidth:outputwidth,outputheight:outputheight};
}
/*********************************************/
/* Get paper size from config                */
/*********************************************/
PrintObject.prototype.getPrintValuesAndSetFence = function()
{
    var size = this.getPrintformatValues(this.getOptionValue('printformats'));
    var outputwidth = size.outputwidth;
    var outputheight = size.outputheight;

    var scalevalue = this.getOptionValue('printscale');
	var scl = (cbKort.extentArr[2]-cbKort.extentArr[0])/cbKort.mapWidth-0;

    this.width = parseInt((scalevalue*outputwidth)/scl);
	this.height = parseInt((scalevalue*outputheight)/scl);

    this.fence.setFenceSize(this.width,this.height);
}






PrintObjectOption.prototype.getDefaultValue = function(inputdefault)
{
    var inputdefaultvalue = '';
    try {
        var inputdefaulthandler = new Function('return '+inputdefault);
        inputdefaultvalue = inputdefaulthandler();
    }
    catch(e) {
        alert(cbInfo.getString('print.js.text_not_valid_2', inputdefault));
    }
    return inputdefaultvalue;
}








/*********************************************/
/* Fence                                     */
/*********************************************/
function Fence()
{
    this.container = this.createContainer();
    this.box = new jsGraphics('fencecontainer');
    this.box.setColor("#ff0000");
    this.width = 0;
    this.height = 0;
    this.rotation = 0;
}
/*********************************************/
/* Set fence size                            */
/*********************************************/
Fence.prototype.setFenceSize = function(width,height)
{
    if(width)
        this.width = width;
    if(height)
        this.height = height;

    this.box.clear();
    if(this.rotation==0)
    {
        this.box.drawLine(0, 0, this.width, 0);
        this.box.drawLine(this.width, 0, this.width, this.height);
        this.box.drawLine(this.width, this.height, 0, this.height);
        this.box.drawLine(0, this.height, 0, 0);
    }
    else
    {
        // Håndtering af rotationer
    }
    this.box.paint();

    this.setContainerSize()
}
/*********************************************/
/* Set fence size                            */
/*********************************************/
Fence.prototype.clear = function()
{
    this.width = 0;
    this.height = 0;
    this.box.clear();
    this.setContainerSize()
}
/*********************************************/
/* Set fence size                            */
/*********************************************/
Fence.prototype.setFencePosition = function(left,top)
{
    if(this.rotation==0)
        this.setContainerPosition(left,top);
    else
    {
        // tag højde for rotation
        var newwidth = this.width; //skal ændres
        var newheight = this.height; //skal ændres
        this.setContainerPosition(left,top,newwidth,newheight);
    }
}
/*********************************************/
/* Create fence container                    */
/*********************************************/
Fence.prototype.createContainer = function()
{
    var e = getElement('fencecontainer');
    if(!e)
    {
        var mapboxElement = document.createElement('div');
        mapboxElement.id = 'fencecontainer';
        mapboxElement.style.position = 'absolute';
        mapboxElement.style.zIndex = '2';
        getElement('mapcontainer').appendChild(mapboxElement);
    }
}
/*********************************************/
/* Set fence container size                  */
/*********************************************/
Fence.prototype.setContainerSize = function()
{
    var width = this.width+1;
    var height = this.height+1;
    var e = getElement('fencecontainer');
    if(ie)
    {
        e.style.overflow = 'hidden';
        e.style.width = width +'px';
        e.style.height = height +'px';
    }
    else
        e.style.clip = 'rect(0px, '+ width +'px, '+ height +'px, 0px)';
}

/*********************************************/
/* Set fence container position              */
/*********************************************/
Fence.prototype.setContainerPosition = function(left,top,width,height)
{
    if(!width)
        width = this.width;
    if(!height)
        height = this.height;
    
    var corr = (ie)?1:0;
    if(!left)
        left = 0;
    else
        left-=(1+corr+width/2);
    if(!top)
        top = 0;
    else
        top-=(2+corr+height/2);
    
    var e = getElement('fencecontainer');
    e.style.left = left+'px';
    e.style.top  = top+'px';
}





function transformLayer (x,y,w,h,id,duration,steps) {
  
  //duration is in seconds
  stepDuration = Math.round(duration/steps) ; // Value is in miliseconds.

  obj = getElement(id);

  // Get original values: x,y = top left corner;  w,h = width height   
  x1 = obj.x;  
  y1 = obj.y;  
  w1 = obj.w;  
  h1 = obj.h;  

  // If values not set, or zero, we do not modify them, and take original as final as well
  x = (x)?x:x1;
  y = (y)?y:y1;
  w = (w)?w:w1;
  h = (h)?h:h1;

  // how much do we need to modify our values for each step?
  // The WZ library moveBy and resizeBy takes the diff with inverted sign as from original ce script:
  difX = (x - x1)/steps;  
  difY = (y - y1)/steps;  
  difW = (w - w1)/steps;  
  difH = (h - h1)/steps;  
 
  obj.moveBy(difX,difY);
  obj.resizeBy(difW,difH);

  //We take out the amount of time used, and a step already being executed
  duration = (duration - stepDuration);
  steps --;

  //If there is any step left, we execute again
  if(steps>=0)
    setTimeout('transformLayer('+x+','+y+','+w+','+h+',"'+id+'",'+duration+','+steps+')',stepDuration);
  //If Return... we could set some api here as to call a function to be evaluated by the javascript,if set, on return
  //for example to call the function that has to populate the div with content
  //but WZ has already thought on it :-)
  return;

}











function trimString(sInString) 
{
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
}
