// ===============================================================
// CBkort version 2.x, copyright Carl Bro GIS&IT, 2006
// ===============================================================
// $Archive: /Products/CBKort2/development/2.5/standard_upgrade_01/wwwroot/WEB-INF/config/modules/standard/print/js/print_config.js $ 
// $Date: 28-05-09 11:27 $
// $Revision: 27 $ 
// $Author: Kpo $
// =============================================================== 


/*********************************************/
/* Global objeject containing print config   */
/*********************************************/
var printObject;

function PrintObject(name)
{
    this.name = name;
    this.title = cbInfo.getString('print.print_config.title1');
    this.header = '';
    this.page = 'print.pdf';
    this.printOptions = new Array();
    this.dialog;
    this.toolMode = -1;
    this.fence;
    this.fenceVisible = false;
    this.fenceReady = true;
    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;
    this.inputdropdown;
}

/*********************************************/
/* Set global print objeject                 */
/*********************************************/
function print_getConfig(name,simplefence)
{
    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();
    
    if(simplefence)
        printObject.simplefence = simplefence;
    //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();
    cbKort.registerMapChangeHandler(printObject.closeHandler);
}

/*********************************************/
/* 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':
        case 'inputdropdown':
        case 'angleinput':
            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' || po.type == 'inputdropdown')
        {
            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>';
        }
        else if(po.type == 'angleinput')
        {
            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" onchange="printObject.setFence()" onkeyup="if (event.keyCode>=32){printObject.setFence()}" style="width:50px;" type="text"/>';
            html+='                        <button class="menubutton" style="width:20px;font-size: 10pt;margin-left : 0px;" onclick="printObject.addToAngleInput(\''+this.name+'_'+po.name+'_print_input\',-5);">-</button>';
            html+='                        <button class="menubutton" style="width:20px;font-size: 10pt;margin-left : 0px;" onclick="printObject.addToAngleInput(\''+this.name+'_'+po.name+'_print_input\',5);">+</button>';
            html+='                    </td>';
            html+='                </tr>';
        }
        else if(po.type == 'text')
        {
            var style = 'vertical-align: top;';
            if(po.height)
                style+='height:'+po.height+';';
            if(po.width)
                style+='width:'+po.width+';';
            html+='                <tr style="height:3px"></tr>';
            html+='                <tr>';
            html+='                    <td colspan="2" style="'+style+'">'+po.displaytext+'</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.doPrint();">' +cbInfo.getString('print.button.print') +'</button>';
    html+='                    </td>';
    html+='                </tr>';
    html+='            </table>';

    this.dialog.addContentHTML(html);
    this.setDefaultValues();
    this.dialog.showDialog();
    
    for(var i=0;i<this.printOptions.length;i++)
    {
        var po = this.printOptions[i];
        if(po.type == 'inputdropdown')
        {
            var a = [];
            for(var j=0;j<po.input.length;j++)
                a[j] = {text:po.input[j].postvalue,value:po.input[j].postvalue};
            po.inputdropdown = new DropdownButton(this.name+'_'+po.name+'_print_input',a);
        }
    }
}

/*********************************************/
/* 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' || po.type == 'angleinput' || po.type == 'inputdropdown')
            {
                if(po.input[0])
                    e.value = po.getDefaultValue(po.input[0].defaultvalue);
            }
        }
    }
}
PrintObject.prototype.addToAngleInput = function(elementid,value)
{
    var e = getElement(elementid);
    var newvalue = parseInt(e.value) + value;
    newvalue = newvalue % 360;
    if(newvalue < 0) newvalue += 360;
    e.value = newvalue;
    this.setFence();
}

/*********************************************/
/* 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
}
function getDefaultPrintScaleValue()
{
    return parseInt(cbKort.getCurrentScale());
}



/*********************************************/
/* Show select fence                         */
/*********************************************/
PrintObject.prototype.select = function()
{
    if(!this.fenceVisible)
    {
        if(!this.fence)
            this.fence = new Fence();
        this.fenceVisible = true;
        this.fence.simple = this.simplefence;
    }
    this.getPrintValuesAndSetFence()
}

/*********************************************/
/* Read selected options and set fence       */
/*********************************************/
PrintObject.prototype.setFence = function()
{
    this.getPrintValuesAndSetFence();
}
/*********************************************/
/* Dialog close handler                      */
/*********************************************/
PrintObject.prototype.closeHandler = function()
{
    if(printObject.fence)
    {
        printObject.fence.clear();
        printObject.fence = null;
    }

    for(var i=0;i<printObject.printOptions.length;i++)
    {
        var po = printObject.printOptions[i];
        if(po.type == 'inputdropdown' && po.inputdropdown)
        {
            po.inputdropdown.hideSelect();
        }
    }
}
/*********************************************/
/* map change handler                        */
/*********************************************/
PrintObject.prototype.mapChangeHandler = function()
{
    this.closeHandler();
}

/*********************************************/
/* Print the map                             */
/*********************************************/
PrintObject.prototype.doPrint = function(mouseX,mouseY)
{
    if(this.fenceReady && this.fence && this.fence.centerPoint)
    {
        var url = getServletUrl();
        url+= '?page='+this.page;
        url+= "&sessionid="+getSessionId();
        url+= "&profile="+getProfile();
    
        // get current layers
        var layers = cbKort.getLayers();
    
        // set scalebarname
        if(getElement('scalebarname'))
            url+='&scalebarname=pdf';
        
        url+='&mapext='+this.fence.extent;
        
        // set pageformat and orientation
        var printformats = this.getOptionValue('printformats').split('_');
        url+='&pageformat='+printformats[0];
        url+='&orientation='+printformats[1];
    
        // add config params
        var cparams = '';
        for(var i=0;i<this.printOptions.length;i++)
        {
            var v = this.printOptions[i].getValue().toString();
            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(this.printOptions[i].type=='checkbox' || (v != 'UNDEFINED' && v != '' && v != null))
            {
                if(this.printOptions[i].name=='map_angle')
                {
                    var v = 360-v;
                    cparams+= '&map_angle='+v;
                }
                else if(this.printOptions[i].name=='arrowhead')
                {
                    if(v=='true')
                        layers+= ' northarrow';
                }
                else
                {
                    cparams+= '&'+this.printOptions[i].name+'_base64='+encode64(v);
                }

                if(this.printOptions[i].name=='ppi')
                {
                    cparams+= '&map_resolution='+v;
                }
            }
        }
        //Worksace
        try
        {
            var wid = workspace.getId()-0;
            if(wid>0)
                url += '&wrkspcid='+wid;
        }
        catch (e) {}
        
        url+= "&layers="+layers;
        url+= cparams;
        
        // show pdf in a popup
        if(testPopupBlocker())
        {
            window.open(url);
            this.dialog.closeDialog();
        }
        else
        {
            alert(this.popUpBlockerAlertText);
        }
    }
}

/*********************************************/
/* Get paper size in meter from config       */
/* - requires: option name="printformats"    */
/*********************************************/
PrintObject.prototype.getPrintformatValues = function(printformat)
{
    this.lastPrintformats = 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()
{
    if(!this.fence)
        return;

    var size = this.getPrintformatValues(this.getOptionValue('printformats'));
    var scalevalue = this.getOptionValue('printscale');
    var scl = (cbKort.extentArr[2]-cbKort.extentArr[0])/cbKort.mapWidth-0;

    this.width = parseInt((scalevalue*size.outputwidth)/scl);
    this.height = parseInt((scalevalue*size.outputheight)/scl);

    var angle = this.getOptionValue('map_angle');
    var pixelsize = cbKort.getMapPhysicalSize().width/cbKort.mapWidth;

    if(angle == 'UNDEFINED')
        angle = 0;
    this.fence.rotation = parseInt(angle);
    
    //brug centerpoint
    this.fence.cbdraw.rotateObject(this.fence.rotation,this.fence.centerPoint);
    
    if(this.fenceVisible)
        this.fence.set(this.width*pixelsize,this.height*pixelsize);
}

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.rotation = 0;
    this.centerPoint = null;
    this.simple = false;
    this.cbdraw = new CBdraw('POLYGON','print_fence',-1, false);
}
/*********************************************/
/* Set new fence                             */
/*********************************************/
var printFenceCallback;
Fence.prototype.set = function(wm,hm)
{
    if(!wm) wm = 1000;
    if(!hm) hm = 1000;
    var mode = 'move';
    if(this.simple) mode = 'movesimple';
    printFenceCallback = new PrintFenceCallback();
    this.printFenceOptions = {
        "silent":"true",
        "mode":mode,
        "startwkt":"POINT(0 0)",
        "endwkt":"POINT("+wm+" "+hm+")",
        "show_angle_option":"false",
        "angle":"0",
        "title":"",
        "autook":"false",
        "info":""}; 
    
    CBMapDrawer_drawRectangle(printFenceCallback, this.printFenceOptions);
    this.rotate(this.rotation);
}
Fence.prototype.rotate = function(angle)
{
    cbmapdrawer_currentDrawer.rotate(this.rotation)
}
Fence.prototype.clear = function()
{
    this.cbdraw.clear();
    if(cbmapdrawer_currentDrawer)
        cbmapdrawer_currentDrawer.dialogCancel();
    printObject.fenceVisible = false;
    printObject.fenceReady = false;
}
function PrintFenceCallback()
{
    PrintFenceCallback.prototype.onDrawSuccess = function(CBMapDrawer)
    {
        printObject.fenceReady = true;
        printObject.fenceVisible = false;
        //var p = CBMapDrawer.getPointsAsString();
        //p = p.split(',');
        wkt = CBMapDrawer.getWKT();
        printObject.fence.extent = getExtentFromWKT(wkt);

        //Store centerpoint (pixelcoordinates) in printObject.fence.centerPoint
        var ext = printObject.fence.extent.split(' ');
        var centerx = ext[0] - 0 + (ext[2] - ext[0])/2;
        var centery = ext[1] - 0 + (ext[3] - ext[1])/2;
        printObject.fence.centerPoint = cbKortUdstyr.getPixelCoords(centerx,centery);
        
        printObject.fence.cbdraw.reset();
        printObject.fence.cbdraw.addPointsFromWKT(wkt);
    }
}









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
}
