var noteCal_1;
var noteCal_2;
var browserName = navigator.appName;
var device="pc";
var winHasFocus = false;
var usrForWhisper = ""; //stores the receiver's username of our private message.
var chart;//global chart variabele. Holds the charts in htmltable
var mv; //message viewer global object
var us; //global Unit Switcher (autoUnitSwitcher) object

function dateNow(){
	if (!Date.now) { 
       return +(new Date);
   }else{
	return Date.now();
   }
}

//=== BOTTOM FIXED BAR ===
function bottomBar(){
    this.items = new ArrayHash();    
    var $handle = jQuery("<div class='handle bbitem'>&bull;</div>");
    this.expanded = true;
    var ref = this;
    $handle.click(function(){
        if( ref.expanded )  ref.contract();
        else                ref.expand();
    });
    this.$bar = jQuery("<div id='fixedBottomBar'></div>");
    this.$bar.append($handle);
    
    this.$bar.css('width',jQuery(window).width() - parseInt(this.$bar.css('padding-left'), 10) - parseInt(this.$bar.css('padding-right'), 10) );
    jQuery('body').append(this.$bar);
    
    this.append = function(options){
        /*  options obj
            "id":   Onjects id so it can be recoginized and removed
            "html": the contained html.
        */
        var item = new Object();
        var $incHtml = jQuery(options.html);
        var $html = jQuery("<div id='"+options.id+"_bbitem' class='bbitem'>"+options.html+"</div>");
        item.id = $incHtml.attr('id');
        item.$html = $html;
        this.remove(item.id);
        this.items.setItem(item.id, item);
        this.$bar.append(item.$html);
    }    
    this.update = function(id, html){
    
    }    
    this.remove = function(id){
        if( this.items.hasItem(id) ){
            this.items.getItem(id).$html.remove();
            this.items.removeItem(id);
        }
    }  
    
    this.contract = function(){
        if( this.expanded ){
            this.$bar.animate({ left: '+='+(jQuery(window).width()-26) });
            this.expanded = false;
        }
    }
    this.expand = function(){
        if( !this.expanded ){        
            this.$bar.animate({ left: '-='+(jQuery(window).width()-26) });
            this.expanded=true;
        }
    }
      
}
//Translate Months 
function getMonthName(month){
    var mname = new Array(getMessage(113),getMessage(114),getMessage(115),getMessage(116),getMessage(117),getMessage(118),getMessage(119),getMessage(120),getMessage(121),getMessage(122),getMessage(123),getMessage(124));
    return mname[month-1];
}

//toggle the main menu bar, and fixate it on top
function toggleMainHeader(){
    if(!jQuery('.headerWrapper').is(':visible')){
            jQuery('.topAreaWrapper').css('position','relative').css('top','0');
            jQuery('.mainAreaWrapper').css('margin-top','0');
    }
    jQuery('.headerWrapper').slideToggle('slow', function(){
        if(!jQuery(this).is(':visible')){
            jQuery('.topAreaWrapper').css('position','fixed').css('top','0');
            jQuery('.mainAreaWrapper').css('margin-top','42px');
        }
    });
    
}
//simple object to remember where we are coming from, so we can go back to (in terms of units)
//used for example when we take a link for "new" from the dashboard, and upon creating the record we want to go back to the dashboard
// clear() and goback() are arbitrary used on generic functions. clear() for example is used at openUnit(). goback() after the insert of a record (various points)
function autoUnitSwitcher(){
    this.isSet = false;
    this.unit = ""; //the unit to go back
    this.wish = ""; //some javascript to execute while returning
    
    this.comebackto = function(unit, wish){        
        this.unit = unit;
        this.wish = wish;
        this.isSet = true;
    }    
    this.clear = function(){
        this.isSet = false;
    }
    this.goback = function(){
        if( this.isSet ){
            openIdUnit(this.unit);            
            //setTimeout( 'eval(\'openTab("outlook_link_topics", "outlook_content_topics", "outlook");getOutlookTable( "s_Outlook", "topics" );\');', 1500 );             
            eval(this.wish);         
            this.clear(); //which has happened already by "openIdUnit" probably!
        }
    }
}
us = new autoUnitSwitcher();
/*====== CLOCK =========*/
jQuery(document).ready(function(){
	tday  =new Array(getMessage("Sun"),getMessage("Mon"),getMessage("Tue"),getMessage("Wed"),getMessage("Thu"),getMessage("Fri"),getMessage("Sat"));
	tmonth=new Array(getMessage("Jan"),getMessage("Feb"),getMessage("Mar"),getMessage("Apr"),getMessage("May"),getMessage("June"),getMessage("July"),getMessage("Aug"),getMessage("Sep"),getMessage("Oct"),getMessage("Nov"),getMessage("Dec"));
});

function GetClock(){
    d = new Date();
    nday   = d.getDay();
    nmonth = d.getMonth();
    ndate  = d.getDate();
    nyear = d.getYear();
    nhour  = d.getHours();
    nmin   = d.getMinutes();
    if(nyear<1000) nyear=nyear+1900;
         if(nhour ==  0) {ap = " AM";nhour = 12;} 
    else if(nhour <= 11) {ap = " AM";} 
    else if(nhour == 12) {ap = " PM";} 
    else if(nhour >= 13) {ap = " PM";nhour -= 12;}
    if(nmin <= 9) {nmin = "0" +nmin;}
    document.getElementById('clockbox').innerHTML=""+tday[nday]+" "+ndate+" "+tmonth[nmonth]+" "+nyear+", "+nhour+":"+nmin+ap+"";
    setTimeout("GetClock()", 1000);
}
//window.onload=GetClock;
/*====== PLAY SOUNDS ======*/
    function playSound(sound) {
       if ( !(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 9) ){
            var thissound=document.getElementById(sound);
            thissound.play();
        }
    /*    sound.pause();
        sound.currentTime = 0;
        sound.play();*/
    }
/**
* hoverIntent r6 // 2011.02.26 // jQuery 1.5.1+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne brian(at)cherne(dot)net
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev])}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev])};var handleHover=function(e){var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t)}if(e.type=="mouseenter"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob)},cfg.interval)}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob)},cfg.timeout)}}};return this.bind('mouseenter',handleHover).bind('mouseleave',handleHover)}})(jQuery);
/*========= BUBBLE POPUP ===========*/
function bubblePopUp(attachTo,text,style){
$attachTo = jQuery(attachTo);
if ($attachTo.length == 0 ) $attachTo = jQuery('#'+attachTo);
var id = "a"+dateNow()+Math.floor(Math.random()*112548);
$attachTo.unbind('mouseenter mouseleave');
$attachTo.hoverIntent(
                function(){ 
                    playSound('flop');
                    $this = jQuery(this);
                    var css='bubblepopup'; //default css
                    if (style == 1) css = 'bubblepopup';
                    var $bubble = jQuery("<div id='"+id+"' class='popupContainer' style='display:none;'><div class='"+css+"'><p>"+text+"</p></div></div>");
                    jQuery('body').prepend($bubble);
                    $bubble.fadeToggle();                    
                    var top =  $this.offset().top - $bubble.height() - $this.height() - 4 ;
                    var left = $this.offset().left -$bubble.width() + 22 ;
                    $bubble.css('top',top);
                    $bubble.css('left',left);
                 },
                function(){
                    jQuery("#"+id).remove();
                });
}

/*========= HOVER WINDOWS ==========*/
function createHoverWindow( selector ){
    jQuery( selector ).each(function(){  
        if( jQuery(this).data('hasHoverBinded') != true )
        {
            jQuery(this).attr("title"," "); //attempt to cancel the title. Doesnt seem to be working.
            Tipped.create(
                this,
                {
                    ajax: {
                        data:jQuery(this).data( 'querystring'),
						url:"?main",
                        type:'post',
                        cache: false
                    },
                    skin: 'light',
                    hook: 'rightmiddle',
                    showDelay: 400,
                    shadow: {
                        blur: 8,
                        color: '#54718e',
                        offset: { x: 0, y: 0 },
                        opacity: .3
                    }
                }
            );
        }
        jQuery(this).data('hasHoverBinded',true); //its binded
    });
}
/* ====== MESSAGE VIEWER ====== */
//Object responsible to collect messages and display them on screen
function messageViewer(){
    this.defTimeout = 3500;
    
	this.messagesShown = [];
	this.newMessages = [];  //table with pending messages
	this.timeout = [];      //keeps the timeout for each message

    //create the basic html structure
	this.$container = jQuery('<div class="messageViewerContainer"></div>');
        this.$mainTile = jQuery('<div class="mainTile" style="display:none;"></div>');  //background and coloring is used here
        	this.$messagesContainer = jQuery("<div class='messagesContainer'></div>");  
        	this.$extraContainer =    jQuery("<div class='extraTile'></div>");
	this.$mainTile.append(this.$messagesContainer);
	this.$mainTile.append(this.$extraContainer);
	this.$container.append(this.$mainTile);
	jQuery('body').prepend(this.$container);

	this.showing = 0; //how many messages are we currently showing
    var ref = this;
	
	//attempts to extract messages directly from an XML response, and show them
	this.addMsg=function(doc){
		var message = getXmlValue(doc, "message");
		var messageType = getXmlAttribute(doc, "message", "type");
		this.add(message, messageType);
		this.showLast();
	}
	
	//Adds a message to the queue
	this.add=function(msg,type){
		if(!msg || msg==""){
			return;
		}
		if(!type || type==""){
		    type="INFO";//default type
		}
	    var id = "_"+dateNow()+Math.floor(Math.random()*112548);
	    this.newMessages.push( {"id":id, "msg":msg, "type":type} );
	    this._updateInfo();
	}
	
	//shows the oldest message of the queue
	this.showLast=function(){
	    if(this.newMessages.length > 0 ) {//if we have something to show continue
	        if( this.showing == 0 ) {   //if we are not showing everying is ok
	            current = this.newMessages.shift();
                this._showOnScreen(current);
            }
            else {  //but if we are currently showing, just update the info tile
                this._updateInfo();
            }            
        }
	}	
	//Removed the message from the screen, and tries to show the next one
	this.closeMessage=function(current){    	
    	clearTimeout( this.timeout[current.id] );
        this.$mainTile.slideToggle('slow',function(){
	        ref.$messagesContainer.children('#'+current.id).remove();
	        ref.showing--;	   
	        ref.$mainTile.removeClass(current.type);
       	    setTimeout( function() { ref.showLast(); }, 100); //and attempt to load the next, giving some time for visual improvement.
   	    });   
	}
	//---Internal functions
	//Takes a message and show it on screen
	this._showOnScreen=function(current){	
	    this.$mainTile.addClass(current.type);
	    this.$messagesContainer.append( this._createMsgTime(current) );	    
        this._updateInfo();	    
	    this.$mainTile.slideToggle('slow');

	    this.showing++;
	    msgTimeout = this.defTimeout + current.msg.length * 55;
	    this.timeout[current.id] = setTimeout( function() { ref.closeMessage(current); }, msgTimeout);	    
	}
	//Take a message and wrap it in the appropriate div
	this._createMsgTime=function(current){	  
	    //the close button  
	    var $button = jQuery("<div class='closeButDiv'><span class='x'>&times;</span></div>");
	    $button.click(function(){ ref.closeMessage(current) } );
	    //the tiles content
	    var $msgTile = jQuery("<div id='"+current.id+"' class='msgTile'><div class='content'>"+current.msg + "</div></div>");
	    $msgTile.append( $button );   
	    
	    return $msgTile;
	}
	//update the row of extra info
	this._updateInfo = function(){
	    var content = this._createExtraContent();
	    if(content != '' ) { //if we have extra info, show it
            this.$extraContainer.html(content);            
        }
        else{ //else empty it
            this.$extraContainer.html('');
        }
	}
	//create the content for the extra info row
	this._createExtraContent=function(){
	    var html = '';
	    if( this.newMessages.length > 0)
    	    html = "<div class='extraContent'>"+getMessage("And")+" "+this.newMessages.length+" "+getMessage("more messages")+"</div>";    	    
	    return html;
	}
}

/*===== add new email addresses ===== */
function addNewMailsWindow(emails,explanation){
    
    //if no explanation was given, assume its the window after sending a mail
    if(explanation == null ) explanation = getMessage("Some of the mails in your sender list were not in your contacts, do you want to add them now?");  

    //convert the new mails into an appropriate array. from java they come in vector.toString() format
    var emailArray = new Array();
    emails = emails.substr(1,emails.length-2);
    var emailArray = emails.split(', ');
    //No mails, no use
    if (emailArray.length == 0 || ( emailArray.length == 1 && emailArray[0]=="") ) return;
    
    //button titles
    publicTitle = getMessage("Make the contact available to ")+jQuery('#thisActorCode').val();
    privateTitle = getMessage("Allow only me to see this contact");
    
    var html = '<div style="overflow:auto;height:100%;margin:10px;">'+
               '<div style="color:#222;font-size:13px;padding:10px;border-bottom: 1px solid #AAAAAA;">'+explanation+'</div>'+
               '<table style="margin:10px;">';
                for(i = 0; i<emailArray.length; i++) //create a row for each email
                {
                    //create the data in case we chose not to be asked again
                    data = '<el><email>'+emailArray[i]+'</email><hidden>true</hidden></el>';
                    html+= '<tr>'+
                        '<td style="width:340px;white-space:nowrap;overflow:hidden;line-height: 25px;padding:0 10px 0 0;"><span style="color:#222;font-size:13px;">'+emailArray[i]+'&nbsp;</span></td>'+
                        '<td><div style="color:#222;font-size:13px;width:160px;">'+
                        '<button onclick="lastClicked568(this);createContactFlyout(this,\'addNewMailsWindow_publicResult\',\'\',\''+emailArray[i]+'\',\'\',\'public\');" class="stylishBut" title="'+publicTitle+'" >'+getMessage("Public")+'</button>&nbsp;'+
                        '<button onclick="lastClicked568(this);createContactFlyout(this,\'addNewMailsWindow_privateResult\',\'\',\''+emailArray[i]+'\',\'\',\'private\');" class="stylishBut" title="'+privateTitle+'" >'+getMessage("Private")+'</button>&nbsp;'+
                       //more action buttons?
                       // '<button onclick="lastClicked568(this);addNewMailsWindow_dontAddResult();" class="stylishBut" >Don\'t Add</button>&nbsp;'+
                       // '<button onclick="lastClicked568(this);createContact(\''+data+'\',\'addNewMailsWindow_dontInformResult\');" class="stylishBut" >Don\'t ask again</button>'+'</div></td>'+
                    '</tr>';
                 }
       html += '</table>'+
                  "<br><br><br><br><br><button style='float:right;margin:15px;' class='stylishBut' title='"+t('Close the window')+"!' onclick=\"Windows.getWindow('souselessandrandomid').close(); \">"+t('OK')+"</button>"                  +
           '</div>';
        contentWin=new Window({id: 'souselessandrandomid', className: 'windowStyle', title: getMessage("Add New Contacts"), hideEffect:Element.hide, showEffect:Element.show, minimizable:false,maximizable:false, resizable:false, recenterAuto:false, wiredDrag: true, destroyOnClose: true, width:560, height:250,zIndex:100, modal:true});
		contentWin.setHTMLContent(html);
		contentWin.showCenter(true);
}
//leaves a mark in the html so we know what we clicked last
function lastClicked568(element){ //random numbers used avoid mixing up with other functions and classes
    jQuery(element).parent().parent().parent().parent().find('td').removeClass('last568');
    jQuery(element).parent().parent().addClass('last568');    
}
//callback functions to show results after adding a contact through the "addNewMailsWindow"
function addNewMailsWindow_publicResult(){
    var doc=this.req.responseXML;
    text = getMessage("There was a problem while adding the contact");
    if(doc) status = doc.getElementsByTagName("status");    	
	if(status.length > 0 && status[0].firstChild.nodeValue == "0"){	    	
	    text = "<span style='color:green;' >"+getMessage("Your contact was successfully added as public")+"</span>";
	}
    jQuery('.last568').html(text).click(); //we click so the flyout closes       
}
function addNewMailsWindow_privateResult(){
    var doc=this.req.responseXML;
    text = getMessage("There was a problem while adding the contact");
    if(doc) status = doc.getElementsByTagName("status");    	
	if(status.length > 0 && status[0].firstChild.nodeValue == "0"){
	    text = "<span style='color:green;' >"+getMessage("Your contact was successfully added as private")+"</span>";
	}
    jQuery('.last568').html(text).click(); //we click so the flyout closes
}
function addNewMailsWindow_dontAddResult(){
    text = "<span style='color:green;' >"+getMessage("No action was taken")+"</span>";	
    jQuery('.last568').html(text); 
}
function addNewMailsWindow_dontInformResult(){
    var doc=this.req.responseXML;
    text = getMessage("Your preference could not be saved");
    if(doc) status = doc.getElementsByTagName("status");    	
	if(status.length > 0 && status[0].firstChild.nodeValue == "0"){
	    text = "<span style='color:green;' >"+getMessage("You will not be asked about this contact again")+"</span>";
	}   
   jQuery('.last568').html(text); 	
}
/*=== Create Contact ===*/
//Creates a small window where you can fill in username and email, to create a contact.
//attachTo is a dom element after which you want to attach the window (the element you just clicked will usually do)
function createContactFlyout(attachTo,callback,name,email,phone,permission){   
    content = '<style>.fastContactFlyoutTable input{font-size:13px;}</style>'+              
                '<table class="fastContactFlyoutTable">'+
                    '<tr>'+
                        '<td>'+
                            '<select style="width:60px;" id="fastContactFlyoutHonorific">'+//This list should be the same with the lookup values of honorific in jp_contact.xml . Ye it sucks, we know!
                                '<option value="0">Mr</option>'+
                                '<option value="1">Mrs</option>'+
                                '<option value="2">Miss</option>'+
                                '<option value="3">Ms</option>'+
                                '<option value="4">Doc</option>'+
                            '</select>'+
                        '</td>'+
                        '<td><input id="fastContactFlyoutFirstName" class="dfltText pInput" style="width:80px;" dflttxt="'+getMessage("First Name")+'" value="'+getMessage("First Name")+'" onfocus="checkDflt(this,true);" onblur="checkDflt(this,true);" /></td>'+
                        '<td style="text-align:right;"><input id="fastContactFlyoutLasttName" class="dfltText pInput" style="width:115px;" dflttxt="'+getMessage("Last Name")+'" value="'+getMessage("Last Name")+'" onfocus="checkDflt(this,true);" onblur="checkDflt(this,true);" /></td></tr>'+
                    '<tr><td colspan="3"><input id="fastContactFlyoutEmail" style="width:270px;" value="'+email+'" class=" pInput" onblur="seeIfEmailIsUsed(this.value,\'contactFlyout_checkEmailResult\');" /></td></tr>'+
                    '<tr><td colspan="3" style="text-align:right;"><input type="button" value="'+getMessage("Add Contact")+'" onclick="if(checkMandatory(\'fastContactFlyoutLasttName\',\'createContactFlyout_NA\',\'Last Name\')){gatherContactData(\''+callback+'\');}"></td></tr>'+
                '</table><span id="createContactFlyout_NA"></span>'+
                '<input id="fastContactFlyoutPermission" type="hidden" value="'+permission+'">';
    var popup = new flyoutWindow(content, attachTo );
    popup.show();
    seeIfEmailIsUsed(email,'contactFlyout_checkEmailResult');
}
/*  ======= FLYOUT WINDOW ========*/
function flyoutWindow(content,attachTo,cssClass,id){
    this.id = id;
    this.content = content;
    if(typeof area == "string"){
        this.$attachTo = jQuery('#'+attachTo);
	}else{
		this.$attachTo = jQuery(attachTo);
	}
    
    this.cssClass = (cssClass == null ? '' : cssClass );
    //generate a random id if non was given    
    if(id == null || jQuery.trim(id) == '') {
        var randId = Math.floor(Math.random()*100001);
        this.id = randId+'contactFlyout';
    }
    this.html = '';
    this.wrapper_start = '';
    this.wrapper_end = ''; 
    
    this.$flyout = '';
    
    this.create_wrapper();  
}
flyoutWindow.prototype.create_wrapper = function (){
    this.wrapper_start = '<div id="'+this.id+'" style="display:none;position:absolute; top:'+(this.$attachTo.offset().top + 5)+'px; left:'+(this.$attachTo.offset().left + this.$attachTo.width() - 5)+'px; font-family: Arial,Sans;font-size:11px;" class="thisWeirdContactFlyoutDiv generalFlyout Back2 '+this.cssClass+'">';
    this.wrapper_end = '</div>';
}
flyoutWindow.prototype.show = function (effect){
    effect = (effect == null ? '' : effect);
    
    this.$flyout = jQuery( this.wrapper_start + this.content + this.wrapper_end );
    jQuery('body').append( this.$flyout );
    this.$flyout.show(effect);
    //We bind the close to a timer cause else it counts the click we did to open the window, and this gets executed right away, reclosing the window!
    setTimeout('jQuery(\'.thisWeirdContactFlyoutDiv\').bind( \'clickoutside\', function(){ jQuery(\'.thisWeirdContactFlyoutDiv\').remove(); } );',800); 
}
/* ----- end of flyout window ------ */
function gatherContactData(callback){ //gets the contact data from the open flyoutwindow, and creates the contact
    data = '<elements>'+
            '<honorific>'+jQuery('#fastContactFlyoutHonorific').val()+'</honorific>'+
            '<first>'+getRealValue('fastContactFlyoutFirstName')+'</first>'+
            '<last>'+getRealValue("fastContactFlyoutLasttName")+'</last>'+
            '<email>'+getRealValue("fastContactFlyoutEmail")+'</email>'+
            '<phone>'+getRealValue('fastContactFlyoutPhone')+'</phone>'+
            '<permission>'+getRealValue('fastContactFlyoutPermission')+'</permission>'+
           '</elements>';
    
    createContact(data,callback);
}
//makes an ajax call that creates a contact. data is expected in xml.
function createContact(data,callback){   
    var doc;
	if (window.DOMParser){
		var parser=new DOMParser();
		doc=parser.parseFromString(data,"text/xml");
	}else{ // Internet Explorer
		doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(data);
	}
	permission = getXmlValue(doc,"permission");
    if( permission != 'public' && permission != 'private') permission = 'private'; //ensure we add some kind of permission
    if(getXmlValue(doc,"hidden")=="true") intType = "25"; else intType = "1";//default that to a normal contact
    name =getXmlValue(doc,"first")+" "+getXmlValue(doc,"last");
    if(name == " " ) name = getXmlValue(doc,"email");
    
	var dataComp = "s_globalContactRec";
	var xmlString = "<?xml version='1.0' encoding='UTF-8'?>"+
	"<elements>"+
	"<actor>"+document.getElementById('thisActorCode').value+"</actor>"+
	"<unit>"+document.getElementById('unit').value+"</unit>"+
	"<action>CLEAR:set value:insert record</action>"+
	"<component>PlatonAction</component>"+
	"<dataComponent>"+dataComp+":"+dataComp+":"+dataComp+"</dataComponent>"+
	"<information>"+
    	"<HONORIFIC>"+getXmlValue(doc,"honorific")+"</HONORIFIC>"+	
    	"<FIRST_NAME>"+getXmlValue(doc,"first")+"</FIRST_NAME>"+
    	"<LAST_NAME>"+getXmlValue(doc,"last")+"</LAST_NAME>"+	
    	"<E_MAIL>"+getXmlValue(doc,"email")+"</E_MAIL>"+
    	"<NAME>"+name+"</NAME>"+	
    	"<CHANGE_CODE>"+permission+"</CHANGE_CODE>"+
    	"<ACCESS_CODE>"+permission+"</ACCESS_CODE>"+   	 
    	"<INTERNAL_TYPE>"+intType+"</INTERNAL_TYPE>"+	   		    
	"</information>"+
	"</elements>";
	var loader1 = new  net.send("main",window[callback],null, "POST",xmlString,"text/xml");
}
//Binds usability to all candidates for contacts. To create a candidate simply wrap the email in a span with class='createContactSpan'
function createContactSpan(context){
//context   -   the id of an element where you want to limit the effect, if nothing is given "body" is assumed
    if(context!='' && context != null)  //try to search only withing a spesific ID, for extra speed.
         $bindElement = jQuery('#'+context+' .createContactSpan');
    else $bindElement = jQuery('.createContactSpan');

    onclick = ""
    $bindElement.addClass('alink');
    $bindElement.before('<span>&lt;&nbsp;</span>').after('<span>&nbsp;&gt;</span>');
    $bindElement.click( function() { var $each = jQuery(this); sendCustomMailFrame($each.html() +';','', $each.html() + ';','',''); });
    $bindElement.hover(
        function() {
            var $span = jQuery(this);
            var original = $span.html();
            clearTimeout( $span.data('hoveroff'));
            clearTimeout( $span.data('hoveron'));
            if ( $span.find('.originalContent').length == 0 ){    //if hoveron has run, dont run again
                var hon = setTimeout(function() {
                    $span.unbind('click');
                    $span.removeClass('alink');
                    $span.css({'border':'1px dashed #ddd','padding':'0px 2px','background-color':'#f4f4f4'});
                    $span.html('<span class="originalContent">'+original+'</span><span style="color:#666;font-size:14px;font-weight:bold;cursor:pointer;"  onclick="createContactFlyout(jQuery(this).parent(),\'contactFlyout_addContactResult\',\'\',\''+original+'\',\'\',\'public\');">&nbsp;+</span>');
    }, 1000);
                $span.data('hoveron', hon);        
            }        
        }, function() {    
            var $span = jQuery(this);
            clearTimeout( $span.data('hoveron'));
            clearTimeout( $span.data('hoveroff'));
            if ( $span.find('.originalContent').length ){    //if hoveron has run, then go on hoveroff        
                var original = $span.find('.originalContent').html();
                var hoff = setTimeout(function() {
                    $span.click( function() { sendCustomMailFrame(original +';',';', original + ';','',''); });
                    $span.addClass('alink');
                    $span.css({'border':'','padding':'','background-color':''});
                    $span.html(original);
                }, 450);
                $span.data('hoveroff', hoff);
            }
        }
     );
    //also bind the click!
 /*   $bindElement.click(
    function() {
        var $span = jQuery(this);
        if ( $span.find('.originalContent').length == 0 ){ //if it hasnt been clicked, or changed from hoveron, change it!
            var original = $span.html();
            $span.css({'border':'1px dashed #ddd','padding':'0px 2px','background-color':'#f4f4f4'});
            $span.html('<span class="originalContent">'+original+'</span><span style="color:#666;font-size:14px;font-weight:bold;cursor:pointer;"  onclick="createContactFlyout(jQuery(this).parent(),\'contactFlyout_addContactResult\',\'\',\''+original+'\',\'\',\'public\');">&nbsp;+</span>');
        }
    });*/
}
/*----*/
//checks if an email is already beeing used
function seeIfEmailIsUsed(email,callback){
    email = jQuery.trim(email);
    if(email!=null && email != ''){
        var actor=document.getElementById('thisActorCode').value;
        var unit=document.getElementById('unit').value;
        var strParams="actor="+actor+"&unit="+unit+"&action=checkEmail&email="+email;
        new net.ContentLoader("main",window[callback],errorState,"POST",strParams); 
    }
}
//callback used to show results of "seeIfEmailIsUsed" at the "Add Contact" Flyout window
function contactFlyout_checkEmailResult(){
    var doc=this.req.responseXML;
    if(doc)	content = doc.getElementsByTagName("content");  else return;    
	if(content.length > 0) text = content[0].firstChild.nodeValue; else return;
    jQuery('#createContactFlyout_NA').html(text);
}
//callback used to show results of "createContact" at the "Add Contact" Flyout window
function contactFlyout_addContactResult(){
    var doc=this.req.responseXML;
    text = getMessage("There was a problem while adding the contact");
    if(doc)	status = doc.getElementsByTagName("status");
	if(status.length > 0 && status[0].firstChild.nodeValue == "0") text = "<span style='color:green;' >"+getMessage("Your contact was created")+"</span>";
    jQuery('#createContactFlyout_NA').html(text);
}


//======== Takes a string of parameters, converts them to a form, posts the form and then removes it.
function postToUrl(url, params)
{
// Params       - Associative array or Object.
    var form = $('<form>');
    form.attr('action', url);
    form.attr('method', 'POST');
    form.attr('target', '_self');
    var addParam = function(paramName, paramValue){
        var input = $('<input type="hidden">');
        input.attr({ 'id':     paramName,
                     'name':   paramName,
                     'value':  paramValue });
        form.append(input);
    };
    // Params is an Associative array or Object.
    if(params instanceof Object){
        for(var key in params){
            addParam(key, params[key]);
        }
    }
    // Submit the form, then remove it from the page
    form.appendTo(document.body);
    form.submit();
    form.remove();
}
/* ========  ARRAY EXPAND ======== */
	
//Extend Array functionality by adding a method to return whether the array has the given value.
Array.prototype.has = function(value) {
    for (var i = 0; i < this.length; i++) {        
        if (this[i] == value) {
            return true;
        }
    }
    return false;
};
/***********************************GMAPS*************************/
var map;
    var gdir;
    var geocoder = null;
    var addressMarker;
    function initialize() {
      if (GBrowserIsCompatible()) {      
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        
      }
    }
    
    function setDirections(fromAddress, toAddress, locale) {

    	if (jQuery("#directionstable").css('display')=="none")
    		jQuery("#directionstable").css('display',"");
    	else{
    		jQuery("#directionstable").css('display',"none");
    		return;
    	}
    	locale = document.getElementById('platonLanguage').getAttribute('lang');
    	if (toAddress.length<3){
    		alert(getMessage(99));
    	}
    	initialize();
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });
                
    }
    function handleErrors(){
    	alert(getMessage(99));
	   /*if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");*/
	   
	}
	function onGDirectionsLoad(){ 
		var dir = gdir.getRoute(0).getNumSteps();
		var rout = gdir.getRoute(0);
		for(var i=0;i<dir;i++){
			//alert( rout.getStep(i).getDescriptionHtml());
		}
		
      // Use this function to access information about the latest load()
      // results.
      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
	
	
	/********************************************************/
jQuery(document).ready(function() {
	var arefs=jQuery('.imgtoLighBox');
	for(var i=0; i<arefs.length; i++){
		var idi=arefs[i].id;
		jQuery('#'+idi).lightBox();
	}
});

function sendCustomMailFrame(toNew, toContactsIds,toContactsMails, subject, body){
	var strParams="actor="+document.getElementById('thisActorCode').value+"&unit="+document.getElementById('unit').value+"&action=MessengerFrame&component=PlatonAction"+"&wrapper=main_message_div&toNew="+toNew+"&toContactsIds="+toContactsIds+"&toContactsMails="+toContactsMails+"&subject="+subject+"&body="+body+"&standarFields=true";
	var loader = new  net.ContentLoader("main",onOpenTab,null, "POST",strParams);
}

//function used for callbacks when we don't want to do anything
function empty(){

}

String.prototype.endsWith = function(str){
	return (this.match(str+"$")==str);
}

//for jQuery selector: converts special characters to escaped
function jQid(id){
	//var symbols=["#", ";", "&", ",", ".", "+", "*", "~", ":", "!", "^", "$", "[", "]", "(", ")", "=", ">", "|", "/", "\"","@"];
	id = (id ? id : "");
	return id.replace(/\./g,'\\\.');
}
//Strips all symbols from the given string
function stripSymbols(str){
    return str.replace(/[^A-Za-z0-9]/g,'');
}
//normalize astrign for post usage
function norm(str){
	if(str==null)
		return "";
	str=str.replace(/&/g,'&amp;');
	str=str.replace(/"/g,'&quot;');
	str=str.replace(/</g,'&lt;');
	str=str.replace(/>/g,'&gt;');
	return str;
}
//normalize astring for url usage
function hexnorm(str){
	if(str==null)
		return "";
	str=str.replace(/&/g,'%26');
	str=str.replace(/"/g,'%22');
	str=str.replace(/</g,'%3C');
	str=str.replace(/>/g,'%3E');
	str=str.replace(/\+/g,'%2B');
	return str;
}

function showOrous(){
	if (document.getElementById('oroiTr').style.display=='none')
		jQuery('#oroiTr').css('display','');
	else
		jQuery('#oroiTr').css('display','none');
}

function validateFieldId(inpId, type){
	var inp=document.getElementById(inpId);
	validateField(inp, type);
}

function validateField(inp, type){
	var inpId=inp.id;
	var value=inp.value;
	var actor=document.getElementById('thisActorCode').value;
	var unit=document.getElementById('unit').value;
	if(type=="DATE" || type=="TIME"){
		var xmlString="<elements>"+
						"<actor>"+actor+"</actor>"+
						"<unit>"+unit+"</unit>"+
						"<inputId>"+inpId+"</inputId>"+
						"<action>getDateTimeFixed</action>"+
						"<pageAction>s_checkDateTime</pageAction>"+
						"<datetime>"+value+"</datetime>"+
						"<mode>"+type+"</mode>"+
						"</elements>";
		xmlString=xmlString.replace(/&/g,'&amp;');
		var check_loader = new  net.send("main",onValidateField,null,"POST",xmlString,"text/xml");
		return;
	}else if(type=="NUMBER" || type=="DOUBLE"){
		check(inp);
	}else if(type=="CURRENCY"){
		checkCurrency(inp);
	}else if(type=="LONG" || type=="INTEGER"){
		checkNodecimal(inp);
	}else if(type=="LIST" || type=="RECDIS"){
		if(inp.getAttribute('state')!='1'){
			return;
		}
		if(inp.value!=""){
			if(inp.getAttribute('hasCode')=="true"){
				if(value!="" && jQuery(inp).attr('code')!=""){
					value=inp.getAttribute('code');
				}
			}
			var dcomp=inp.getAttribute('formDataComponent');
			if(!dcomp || dcomp=="null"){
				dcomp=inp.getAttribute('dataComponent');
			}
			var xmlString="<elements>"+
							"<actor>"+actor+"</actor>"+
							"<unit>"+unit+"</unit>"+
							"<inputId>"+inpId+"</inputId>"+
							"<action>checkList</action>"+
							"<pageAction>s_checkList</pageAction>"+
							"<value>"+norm(value)+"</value>"+
							"<dataComponent>"+dcomp+"</dataComponent>"+
							"<field>"+inp.getAttribute('datafield')+"</field>"+
							"</elements>";
			var check_loader = new  net.send("main",onValidateField,null,"POST",xmlString,"text/xml");
			return;
		}
	}
	if(inp.getAttribute('post')=="true"){
		postAction(inpId);
	}else{
		//checkDflt(inp, true); //not used pros to paron
		jQuery(inp).trigger("valueChangedEvent");
	}
}

function onValidateField(){
	var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){
		var inputId = doc.getElementsByTagName("inputId")[0].firstChild.nodeValue;
		var inp=document.getElementById(inputId);
		if(doc.getElementsByTagName("value")[0].firstChild!=null){
			inp.value=doc.getElementsByTagName("value")[0].firstChild.nodeValue;
			if(inp.getAttribute('hasCode')=="true"){
				inp.setAttribute('code', doc.getElementsByTagName("code")[0].firstChild.nodeValue);
			}
		}else{
			inp.value="";
			if(inp.getAttribute('hasCode')=="true"){
				inp.setAttribute('code', "");
			}
		}
		if(inp.getAttribute('post')=="true"){
			postAction(inputId);
		}else{
			//checkDflt(inp, true); //not used pros to paron
			jQuery(inp).trigger("valueChangedEvent");
		}
	}else if(status[0].firstChild.nodeValue=='-1'){
		alert(message[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-4'){
	}
}

function check(t){
	var numb = "0123456789,.-";
	var w = "";
	for (i=0; i < t.value.length; i++) {
		x = t.value.charAt(i);
		if (numb.indexOf(x,0) != -1)
			w += x;
	}
	t.value = w;
}

//prepei na elegxei gia morfi currency ###.00
//pros to paron einai to idio me tous arithmous
function checkCurrency(t){
	var numb = "0123456789.,-";
	var w = "";
	for (i=0; i < t.value.length; i++) {
		x = t.value.charAt(i);
		if (numb.indexOf(x,0) != -1)
			w += x;
	}
	t.value = w;
}
//elegxos gia akeraious arithmous
function checkNodecimal(t){
	var numb = "0123456789-";
	var oper = ",.";
	var w = "";
	for (i=0; i < t.value.length; i++) {
		x = t.value.charAt(i);
		if (numb.indexOf(x,0) != -1)
			w += x;
		if(oper.indexOf(x,0)!=-1){
			break;
		}
	}
	t.value = w;
}

function getCommunicationForm(){
	var xmlString = "<?xml version='1.0' encoding='UTF-8'?>"+
		"<elements>"+
		"<actor>"+document.getElementById('thisActorCode').value+"</actor>"+
		"<unit>"+document.getElementById('unit').value+"</unit>"+
		"<pageAction>getCommunicationForm</pageAction>"+
		"<action>getCommunicationForm</action>"+
		"</elements>";
		xmlString=xmlString.replace(/&/g,'&amp;');
		var loader1 = new  net.sendThis("main",this.onGetCommunicationForm,null,this,null, "POST",xmlString,"text/xml");
}

function onGetCommunicationForm(){
	var doc=this.req.responseXML;
	var content=doc.getElementsByTagName("content");
	if (content.length!=0)
		content = content[0].firstChild.nodeValue;
	var status=doc.getElementsByTagName("status")[0].firstChild.nodeValue;
	var message = doc.getElementsByTagName("message");
	if(content.length!=0){
		var contentWin=new Window({id: "main_communication_div", className: 'alphacube', title: getMessage(25), hideEffect:Element.hide, showEffect:Element.show, minimizable:false,maximizable:false, resizable:false, wiredDrag: true, destroyOnClose: true, width:300, height:320, modal:true});
		contentWin.setHTMLContent(content);
		contentWin.showCenter();
		return;
	}
	alert(message[0].firstChild.nodeValue);
	
}

//Fetch the HTML of a single outlook record. i.e. the event page, or the topic page etc
function getOutlookView(table,recordId, comments, placeAt, callback){
//comments  -   The ammount of comments to preload.
//recordId  -   the record where the comments belongs
//placeAt   -   where to place the resulting HTML
        
	var actorCode = document.getElementById('thisActorCode').value;
	var strParams="action=getOutlookView&component=PlatonAction&unit=Outlook";
    if (actorCode) strParams+="&actorCode="+actorCode;
	strParams+="&comments="+comments+"&recordId="+recordId+"&table="+table;
	//in the meantime, empty out holder
    jQuery('#'+placeAt).html("<div class='loading'>"+getMessage("Loading")+"...<br /> <img src='platonimages/images/loading.gif'/> </div>");      
	jQuery.ajax({  
        type:"POST",
		url:"?main",
        data: strParams,  
        success: function(data, textStatus, jqXHR){ 
                if(callback = 'onGetOutlookView_outlook') onGetOutlookView_outlook(jqXHR, placeAt, table) 
        }     
    });
}
function onGetOutlookView_outlook(jqXHR, placeAt, table){
    var doc = jqXHR.responseXML;
    jQuery('#'+placeAt).html( getXmlValue(doc,"content") );  
    eval(getXmlValue(doc,"scripts"));
    updateOutlookCounters(table);    
}
function sendCommunicationForm(id){
				if (id==null)
					id = "section";
				else {
					id = id.getAttribute('parentid');
				}
				var message = "";
				var name = "";
				var lastname = "";
				var email = "";
				var phone = "";
				var fullname = "";
				var company = "";
				var ins = jQuery("#"+id).find("input");

				for (var i=0;i<ins.length;i++){
					if (ins[i].value != "" && ins[i].getAttribute('type') == "text"){
						message += ins[i].value+":";
					}
					if (ins[i].hasAttribute('name') == true){
						if (ins[i].getAttribute('name') == "firstname"){
						name = ins[i].value;
						}
					}
					if (ins[i].hasAttribute('name') == true){
						if (ins[i].getAttribute('name') == "lastname"){
						lastname = ins[i].value;}
					}
					if (ins[i].hasAttribute('name') == true){
						if (ins[i].getAttribute('name') == "email"){
						email = ins[i].value;}
					}
					if (ins[i].hasAttribute('name') == true){
						if (ins[i].getAttribute('name') == "phone"){
						phone = ins[i].value;}
					}
					if (ins[i].hasAttribute('name') == true){
						if (ins[i].getAttribute('name') == "fullname"){
							fullname = ins[i].value;
						}
					}
					if (ins[i].hasAttribute('name') == true){
						if (ins[i].getAttribute('name') == "company"){
							company = ins[i].value;
						}
					}
				}/*for*/
				/*alert(_fullname);*/
				message = message.substr(0,message.length-1);
				
				ins = jQuery("#"+id).find("textarea");
				for (var i=0;i<ins.length;i++){
					if (ins[i].value != "")
						message += ":"+ins[i].value;
				}
				try{
					if (!receiver)
						receiver=100;
				}catch(err){receiver=100;}
				var xmlString = "<?xml version='1.0' encoding='UTF-8'?>"+
					"<elements>"+
					"<actor>"+document.getElementById('thisActorCode').value+"</actor>"+
					"<unit>"+document.getElementById('unit').value+"</unit>"+
					"<pageAction>addMessage</pageAction>"+
					"<action>addMessage</action>"+
					"<message>"+message+"</message>";
					if (name!="")
						xmlString+="<firstName>"+name+"</firstName>";
					if (lastname!="")
						xmlString+="<lastName>"+lastname+"</lastName>";
					if (fullname!="")
						xmlString+="<fullName>"+fullname+"</fullName>";
					if (company!="")
						xmlString+="<company>"+company+"</company>";
					
					xmlString +=				
					"<email>"+email+"</email>"+
					"<phone>"+phone+"</phone>"+
					"<receiver>"+receiver+"</receiver>"+
					"<articleCode>"+document.getElementById('articleCode').value+"</articleCode>"+
					"<wrapper>"+document.getElementById('wrapper').value+"</wrapper>"+
					"</elements>";
					xmlString = xmlString.replace(/&/g,'&amp;');
					//alert(xmlString);

					var loader1 = new net.sendThis("main",this.onGetCommunicationForm,null,this,null, "POST",xmlString,"text/xml");
}
//Sends an email originating from system@comidor.com
function sendSystemEmail(sendTo,type,subject,body,successCallback,errorCallback){
// sendTo        - A code that can be translated to an email from Client Parameters
// type          - Content type, i.e. plain/text
var xmlString = "<?xml version='1.0' encoding='UTF-8'?>"+
		"<elements>"+
		    "<action>sendSystemEmail</action>"+
		    "<message>"+body+"</message>"+
		    "<subject><![CDATA["+subject+"]]></subject>"+
		    "<sendTo>"+sendTo+"</sendTo>"+
		    "<type>"+type+"</type>"+
		    "<actor>"+document.getElementById('thisActorCode').value+"</actor>"+
		"</elements>";
xmlString = xmlString.replace(/&/g,'&amp;');
var loader1 = new net.send("main",successCallback,errorCallback, "POST",xmlString,"text/xml");
}
function checkDate(inp, mode){
	var inpId=inp.id;
	var value=inp.value;
	var actor=document.getElementById('thisActorCode').value;
	var unit=document.getElementById('unit').value;
	//var strParams="actor="+actor+"&unit="+unit+"&action=getDateTimeFixed&pageAction=s_checkDateTime&datetime="+value+"&inputId="+inpId+"&mode="+mode;
	//var check_loader = new  net.ContentLoader("main",onCheckDateTime,null,"POST",strParams);
	var xmlString="<elements>"+
					"<actor>"+actor+"</actor>"+
					"<unit>"+unit+"</unit>"+
					"<inputId>"+inpId+"</inputId>"+
					"<action>getDateTimeFixed</action>"+
					"<pageAction>s_checkDateTime</pageAction>"+
					"<datetime>"+value+"</datetime>"+
					"<mode>"+mode+"</mode>"+
				"</elements>";
	xmlString=xmlString.replace(/&/g,'&amp;');
	var check_loader = new  net.send("main",onCheckDateTime,null,"POST",xmlString,"text/xml");
}

function onCheckDateTime(){
	var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){
		var inputId = doc.getElementsByTagName("inputId")[0].firstChild.nodeValue;
		if(doc.getElementsByTagName("value")[0].firstChild!=null){
			document.getElementById(inputId).value=doc.getElementsByTagName("value")[0].firstChild.nodeValue;
		}else{
			document.getElementById(inputId).value="";
		}
	}else if(status[0].firstChild.nodeValue=='-1'){
		alert(message[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-4'){
}
}

//checks if a xml document contains a spesific tag
function hasXmlTag(doc, tag){
    if(doc != null)	return (doc.getElementsByTagName(tag).length>0 ? true : false);
    else return false;
}

//return the value of a tag as an array.
//Ean den iparxei to tag : kenos pinakas
//o pinakas tha exei tosa stoixeia osa tags tariazoun
function getXmlValue(doc, tagName){
	var tagValues=new Array();
	if(hasXmlTag(doc, tagName)){
		var tags=doc.getElementsByTagName(tagName);
		for(var i=0; i<tags.length; i++){
			tagValues.push(tags[i].firstChild ? tags[i].firstChild.nodeValue : "");
		}
	}
	if(tagValues.length==1){
		return tagValues[0];
	}
	return tagValues;
}

//returns the value of an attribute of a tag or many in an array
//opos kai pano an den iparxei to tag tote kenos pinakas
function getXmlAttribute(doc, tagName, attr){
	var tagAttributes=new Array();
	if(hasXmlTag(doc, tagName)){
		var tags=doc.getElementsByTagName(tagName);
		for(var i=0; i<tags.length; i++){
			if(tags[i].getAttribute(attr)){
				tagAttributes.push(tags[i].getAttribute(attr));
			}
		}
	}
	if(tagAttributes.length==1){
		return tagAttributes[0];
	}
	return tagAttributes;
}

//get a parameter from url if there is any or an empty string if there isn't
function getParameter(parameter){
	var loc=window.location.href;
	if(loc.indexOf(parameter+'=')!=-1){
		loc=loc.substring(loc.indexOf(parameter+'='), loc.length);
		loc=loc.substring(loc.indexOf('=')+1, loc.length);
		if(loc.indexOf('&')!=-1){
			loc=loc.substring(0, loc.indexOf('&'));
		}
		if(loc.indexOf('#')!=-1){
			loc=loc.substring(0, loc.indexOf('#'));
		}
		return loc;
	}else{
		return "";
	}
}

function resizeIframe(newHeight){
  //alert('aaaa');
  //alert(newHeight);
  //var f =document.getElementsByTagName('iframe')[0];
  //f.style.height = f.contentWindow.document.body.scrollHeight + 'px';
  //alert(f.style.height);
  //alert(.contentDocument.body.height);
  //document.getElementsByTagName('iframe')[0].style.height = parseInt(newHeight) + 10 + 'px';
  //alert(document.getElementsByTagName('iframe')[0].style.height);

  
  /*iframe=parent.document.frames[frameId];
  iframe.height = newHeight;*/
}

function processBlock(){

	/*var el = document.getElementById('loginDialog');
	//alert(el);
	$.blockUI({
		message: jQuery(el),
		centerY: 0,
		css: {
			width: '200px',
			top: '100px',
			left: '300px',
			right: '',
			border: 'none',
			padding: '5px',
			cursor: 'not-allowed',
			backgroundColor: '#fff',
			'-webkit-border-radius': '10px',
			'-moz-border-radius': '10px',
			//opacity: .6,
			color: '#fff'
		}
	});*/
}

function loginDash(){
	var username = document.getElementById('un_input').value;
	var pass = document.getElementById('pass_input').value;
	var act_code = document.getElementById('act_input').value;
	var strParams="action=Login&username="+username+"&password="+pass+"&actorCode="+act_code;
	//alert(strParams);
	var login_loader = new  net.ContentLoader("MainViewServlet",Dlogged,null, "POST",strParams);
}

function handleRoles(el){
	var val = el.getAttribute('value');
	var strParams="action=fetchRoles&value="+val;
	
	var login_loader = new  net.ContentLoader("main",changeTabs,null, "POST",strParams);
}

function changeTabs(){

	var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	var content = doc.getElementsByTagName("content");

	if(status[0].firstChild.nodeValue=='0'){
		document.getElementById('cssmenubopen').innerHTML=content[0].firstChild.nodeValue;
	}else if(status[0].firstChild.nodeValue=='-1'){
		document.getElementById('viewDiv').innerHTML="";
		alert(message[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-4'){
		document.getElementById('viewDiv').innerHTML="";
		parent.processBlock();
	}

}

function Dlogged(){
	var doc=this.req.responseXML;
	//alert(this.req.responseText);
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){
		$.unblockUI();
	/*for(var i=0; i<lastOpenedFrame.length; i++){
			var ifra=lastOpenedFrame.pop();
			ifra.reload(this, lastOpenedUrl.pop());
		}*/
	}else if(status[0].firstChild.nodeValue=='-1'){
		alert(message[0].firstChild.nodeValue);
	}
}

function al() {
	var div=document.getElementById("div4");
	div.style.cursor="pointer";
	div.style.position = "absolute";
	div.style.backgroundImage="url(codebase/neokopsimo/3-red.gif)";
	div.style.left = "755px";
	div.style.top = "146px";
	div.style.height = "62px";
	div.style.width = "269px";
	div.style.zIndex = "1000";
	div.onmouseout=function(evt){
		eval("al2()");
	}
}
 
function al2(){
	var div=document.getElementById("div4");
	div.style.cursor="pointer";
	div.style.position = "absolute";
	div.style.backgroundImage="url(codebase/neokopsimo/3.gif)";
	div.style.left = "755px";
	div.style.top = "146px";
	div.style.height = "62px";
	div.style.width = "269px";
	div.style.zIndex = "1000";
}

function al3() {
	var div=document.getElementById("div10");
	div.style.cursor="pointer";
	div.style.position = "absolute";
	div.style.backgroundImage="url(codebase/neokopsimo/5-anapoda.gif)";
	div.style.left = "755px";
	div.style.top = "302px";
	div.style.height = "68px";
	div.style.width = "269px";
	div.style.zIndex = "1000";
	div.onmouseout=function(evt){
		eval("al4()");
	}
}

function al4(){
	var div=document.getElementById("div10");
	div.style.cursor="pointer";
	div.style.position = "absolute";
	div.style.backgroundImage="url(codebase/neokopsimo/5.gif)";
	div.style.left = "755px";
	div.style.top = "302px";
	div.style.height = "68px";
	div.style.width = "269px";
	div.style.zIndex = "1000";
}

function loadMaps() {

	var el = document.createElement("a");
	el.setAttribute("href",'?unit=KT_Example');
	el.appendChild(document.createElement("br"));
	el.appendChild(document.createElement("br"));
	el.appendChild(document.createElement("br"));
	el.appendChild(document.createElement("br"));
	el.style.position = "absolute";
	el.style.cursor = "pointer";
	el.style.left = "780px";
	el.style.top = "290px";
	el.style.Height = "200px";
	el.style.width = "200px";
	el.href='?unit=KT_Example';
	//el.style.backgroundColor = "red";
	document.body.appendChild(el);


	addScrollers();

	if (GBrowserIsCompatible() && document.getElementById("map")!=null) {
		var la = document.getElementById("map").getAttribute("la");
		var lo = document.getElementById("map").getAttribute("lo");
     
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(la,lo), 15);
		map.addOverlay(new GMarker(new GLatLng(la, lo)));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());


	}
}

//Create an overlay
function loadingOverlay(show, html){
    //show      - true to show, false to hide, null to toggle
    //html      - html to show in the window. Its placed in a small window at the center of the page
    //decide what to do if we weren't told (toggle)
    if( show == null    ){
        if( jQuery('#overlay55').length > 0 )   show = false;
        else                                    show = true;    
    } 
    if( show == true  ){  
        jQuery('#overlay55').remove() ;
        var $overlay = jQuery("<div id='overlay55' " //55 is used just do it doesnt get mixed with other overlays
        +"style='"
           +"background-color:rgba(90,90,90,0.7);"
           +"position: absolute;"
           +"left: 0px;"
           +"top: 0px;"
           +"width:100%;"
           +"height:"+ jQuery('body').outerHeight(true)+"px;"
           +"text-align:center;"
           +"z-index: 100000;"
        +"'>"
        +"<div id='overlay_window' style='"
            +"width:300px;"
            +"margin: 15% auto 0;"
            +"background:rgba(255,255,255,0.9);"
            +"padding:25px;"
            +"text-align:center;"
         +"'>"+html+"</div></div>");
         
        jQuery('body').append( $overlay ) ;
    }
    else {
        jQuery('#overlay55').remove() ;
    }
            
}   
//simply get a text to use in the overlay, just so we dont repeat it allover the place
function getHtmlForOverlay(text){
    if(text=='uploading') return "<br/><span style='color:grey;font-size:14px;'>"+getMessage("Uploading")+"...</span><br/><img style='padding:5px;' src='/platonimages/images/loading.gif'/><br/>";
	    
}
function onButtonClick(itemId,itemValue){
	alert("Button "+itemId+" was pressed"+(itemValue?("\n select value : "+itemValue):""));
};

var first,second;
var active;

document.oncontextmenu = function() {
	return true;
}
	
function onDown(val) {
	first=val;
	active=val;
	val.oncontextmenu = function() {
		return false;
	}
		
}
	
function resizeRight(elem){
		
	var start = parseInt(elem.id);
	var identity = start+(1*elem.getAttribute('colspan'));
	//alert(elem.parentNode.innerHTML);
	//alert(elem.getAttribute('colspan'));
	var ni = (parseInt(elem.getAttribute('colspan'))+1);
	var total = parseInt(ni)+parseInt(elem.id)-1;
	var d;
	if (parseInt(elem.id)>0 && parseInt(elem.id)<=30)
		d = 30;
	if (parseInt(elem.id)>30 && parseInt(elem.id)<=60)
		d = 60;
	if (parseInt(elem.id)>60 && parseInt(elem.id)<=90)
		d = 90;
	if (parseInt(elem.id)>90 && parseInt(elem.id)<=120)
		d = 120;
		
	if (total>d)
		return;
	//alert(elem.innerHTML);
	//alert("BEFORE:"+elem.getAttribute('colspan'));
	elem.colSpan = ni;
	elem.width = (ni*3)+"%";
	//elem.colspan="2";
	//alert(elem.parentNode.innerHTML);
	//alert("AFTER:"+elem.getAttribute('colspan'));
	//alert(elem.colspan);
	for (var i=0;i<elem.getAttribute('rowspan');i++)
	{
		var nex = document.getElementById(identity);
		if (nex!=null)
			nex.parentNode.removeChild(nex);
		identity = identity + 30;
	}
		
//alert((elem.getAttribute('colspan')+1));
}
	
function resizeUp(elem){
		
	var start = parseInt(elem.id);
		
	var identity = start+(30*elem.getAttribute('rowspan'));
	var ni = (parseInt(elem.getAttribute('rowspan'))+1);
	elem.rowSpan = ni;
	for (var i=0;i<elem.getAttribute('colspan');i++)
	{
		//alert(i);
		  
		var nex = document.getElementById(identity);
		//alert(identity);
		if (nex!=null)
			nex.parentNode.removeChild(nex);
		identity = identity + 1;
	}
//alert((elem.getAttribute('colspan')+1));
}
	
function test(e,el){
	if(navigator.appName.toLowerCase().indexOf("netscape")!=-1){
		if (e.button == 0)
			resizeUp(el)
		if (e.button == 2)
			resizeRight(el)
	}

	if(navigator.appName.toLowerCase().indexOf("netscape")==-1){
		if (e.button == 1)
			resizeUp(el)
		if (e.button == 2)
			resizeRight(el)
	}
}

function onOver(el){
	el.parentNode.className="over";
	el.className="over";
}

function onOut(el){
	el.parentNode.className="out";
	el.className = "out";//setAttribute('style',"font-size:14;");
}

function getHtmlFragment(xmlUrl,id) {
	alert('1')
	//load the xml file
	var xmlSource = getResponseXml(xmlUrl,"POST").responseXML;
	var elem = document.getElementById(id);
	elem.innerHTML = getResponseXml(xmlUrl,"POST").responseText;
}

function kteolist(){
	var xmlUrl = "../PlatonServlet/PlatonServlet?user=kteo&pass=group&unit=kt_Example&datacomponent=g_KteoList&";
	alert('1');
	//"?action=fetch&dataComponent=articleMain&id=symmetry/philosophy.html";//"PlatonServlet/PlatonServlet?user=kteo&pass=group&unit=kt_Example&datacomponent=g_KteoList&";
	//load the xml file
	var xmlSource =  getResponseXml(xmlUrl,"GET");

	//alert(xmlSource.responseText);
	var text = xmlSource.responseText;
	try //Internet Explorer
	{
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(text);
	}
	catch(e)
	{
		try //Firefox, Mozilla, Opera, etc.
		{
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(text,"text/xml");
		}
		catch(e) {
			alert(e.message)
			}
	}
	var xmlRoot = xmlDoc.documentElement;
	var sel = document.getElementById('kteo');
	var str="";
	for(var i=0;i<xmlRoot.getElementsByTagName('kteo').length;i++){
		str+="<option value="+xmlRoot.getElementsByTagName('kteo')[i].childNodes[0].firstChild.nodeValue+">"+
		xmlRoot.getElementsByTagName('kteo')[i].childNodes[1].firstChild.nodeValue+"</option>";
	}
	alert('2');
	sel.innerHTML = str;
	sel.outerHTML = "<select id='kteo'>"+str+"</select>";
//alert(xmlRoot.getElementsByTagName('kteo')[0].getAttribute('id'));
//alert(xmlRoot.getElementsByTagName('kteo')[0].childNodes[0].firstChild.nodeValue);
//alert(xmlRoot.getElementsByTagName('kteo')[0].childNodes[1].firstChild.nodeValue);
}

function calendar(){
	/*document.body.style.cursor = "wait";
	//alert('1');
	var dd = document.getElementById('date1').value;
	var day = dd.substring(0,dd.indexOf("/"));
	var mm = dd.substring(dd.indexOf("/")+1,dd.lastIndexOf("/"));
	var yy = dd.substring(dd.lastIndexOf("/")+1,dd.length);
	if (day.length<2)
	  day = "0"+day;
	if (mm.length<2)
	  mm = "0"+mm;
	dd = yy+mm+day;
	//alert(yy+" "+mm+" "+day);
	var xmlUrl = "../PlatonServlet/PlatonServlet?&user=kteo&pass=group&unit=kt_Example&datacomponent=g_CalendarSet&date="+
	   +dd+"&kteo="+document.getElementById('select1').value+"&days=2";
//alert(xmlUrl);
	//"?action=fetch&dataComponent=articleMain&id=symmetry/philosophy.html";//"PlatonServlet/PlatonServlet?user=kteo&pass=group&unit=kt_Example&datacomponent=g_KteoList&";
//load the xml file
var xmlSource =  getResponseXml(xmlUrl,"GET");

//alert(xmlSource.responseText);
var text = xmlSource.responseText;
try //Internet Explorer
  {
  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.loadXML(text);
  }
catch(e)
  {
  try //Firefox, Mozilla, Opera, etc.
    {
    parser=new DOMParser();
    xmlDoc=parser.parseFromString(text,"text/xml");
    }
  catch(e) {alert(e.message)}
  }
  var xmlRoot = xmlDoc.documentElement;
  var sel = document.getElementById('select2');
  var str="";
  */
	document.getElementById('karelegx').removeAttribute('disabled');
	document.getElementById('liksikartas').removeAttribute('disabled');
	document.getElementById('eidoxim').removeAttribute('disabled');
	document.getElementById('eidelegx').removeAttribute('disabled');
	document.getElementById('arkyklof').removeAttribute('disabled');
  
	document.getElementById('name').removeAttribute('disabled');
	document.getElementById('address').removeAttribute('disabled');
	document.getElementById('tk').removeAttribute('disabled');
	document.getElementById('city').removeAttribute('disabled');
	document.getElementById('mobile').removeAttribute('disabled');
	document.getElementById('homephone').removeAttribute('disabled');
	document.getElementById('workphone').removeAttribute('disabled');
	document.getElementById('email').removeAttribute('disabled');
  
// document.getElementById('kartaelegxou').removeAttribute('disabled');
//alert('2');
/* if (xmlRoot!=null) {
    if (xmlRoot.getElementsByTagName('hour').length==0){
      alert('Αυτή την ημερομηνία είμαστε πλήρεις');
      document.body.style.cursor = "default";
      return;
    }
  //alert('3');
  if (xmlRoot.getElementsByTagName('hour'))
  for(var i=0;i<xmlRoot.getElementsByTagName('hour').length;i++){
  	str+="<option value="+xmlRoot.getElementsByTagName('kteo')[i].childNodes[0].firstChild.nodeValue+">"+
  	  xmlRoot.getElementsByTagName('kteo')[i].childNodes[1].firstChild.nodeValue+"</option>";
  }
//alert('4');
  sel.innerHTML = str;
  sel.outerHTML = "<select id='select1'>"+str+"</select>";
  }
  document.body.style.cursor = "default";

 
  //alert(xmlRoot.getElementsByTagName('kteo')[0].getAttribute('id'));
  //alert(xmlRoot.getElementsByTagName('kteo')[0].childNodes[0].firstChild.nodeValue);
  //alert(xmlRoot.getElementsByTagName('kteo')[0].childNodes[1].firstChild.nodeValue);*/
}

//calls a dataaction in PlatonAction.java and returns what to do next
function callScript(elem){
	var unit = document.getElementById('unit').value;
	var action = "callScript";
	var xmlUrl = "main";
	var strParams = "component=PlatonAction&action="+action+"&dataAction="+action+"&unit="+unit+"&script="+elem;
	var loader1 = new  net.ContentLoader(xmlUrl,setChanges,null, "POST",strParams);   
}

function senddata(elem){
	var unit = document.getElementById('unit').value;
	var action = elem.getAttribute("action");
	var dataAction = elem.getAttribute("dataAction");
	var dc="";
	if(elem.getAttribute("dataComponent") && elem.getAttribute("dataComponent")!=""){
		dc = elem.getAttribute("dataComponent");
	}else{
		dc = elem.getAttribute("formDataComponent");
	}
	var xmlUrl = "main";
	var strParams = "component=PlatonAction&action="+action+"&unit="+unit+"&dataComponent="+dc+"&dataAction="+dataAction+"&dataComp="+dc;
	var loader1 = new  net.ContentLoader(xmlUrl,setChanges,null, "POST",strParams);   
}

function aler(){
	var xmlUrl = "?&action=platonAction&dataAction=execute&unit=KT_Example&dataComponent=s_KteoList&";
	//var xmlSource =  getKteoList(xmlUrl,"POST");
	//alert(xmlSource.responseText);
	var xmlDoc = getKteoList(xmlUrl,"POST").responseXML;
	var xmlRoot = xmlDoc.documentElement;
	var kteos = xmlDoc.getElementsByTagName('kteo');
	var sel = document.getElementById('kteo');
	var str="";
	for(var i=0;i<xmlRoot.getElementsByTagName('kteo').length;i++){
		str+="<option value="+xmlRoot.getElementsByTagName('kteo')[i].childNodes[0].firstChild.nodeValue+">"+
		xmlRoot.getElementsByTagName('kteo')[i].childNodes[1].firstChild.nodeValue+"</option>";
	}
	//alert('2');
	sel.innerHTML = str;
	sel.outerHTML = "<select id='kteo'>"+str+"</select>";
  
	if (document.getElementById('karelegx'))
		document.getElementById('karelegx').setAttribute('disabled','disabled');
	if (document.getElementById('liksikartas'))
		document.getElementById('liksikartas').setAttribute('disabled','disabled');

	if (document.getElementById('eidoxim'))
		document.getElementById('eidoxim').setAttribute('disabled','disabled');
	if (document.getElementById('eidelegx'))
		document.getElementById('eidelegx').setAttribute('disabled','disabled');
	if (document.getElementById('arkyklof'))
		document.getElementById('arkyklof').setAttribute('disabled','disabled');
   
	if (document.getElementById('name'))
		document.getElementById('name').setAttribute('disabled','disabled');
	if (document.getElementById('address'))
		document.getElementById('address').setAttribute('disabled','disabled');
	if (document.getElementById('tk'))
		document.getElementById('tk').setAttribute('disabled','disabled');
	if (document.getElementById('city'))
		document.getElementById('city').setAttribute('disabled','disabled');
	if (document.getElementById('mobile'))
		document.getElementById('mobile').setAttribute('disabled','disabled');
	if (document.getElementById('workphone'))
		document.getElementById('workphone').setAttribute('disabled','disabled');
	if (document.getElementById('homephone'))
		document.getElementById('homephone').setAttribute('disabled','disabled');
	if (document.getElementById('email'))
		document.getElementById('email').setAttribute('disabled','disabled');
}

function getKteoList(xmlUrl,meth) {
	
	var xmlHttp;


	if(navigator.appName.toLowerCase().indexOf("explorer")!=-1){
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else{

		xmlHttp = new XMLHttpRequest();

	}

	xmlHttp.open(meth, xmlUrl, false);
	xmlHttp.send(null);

	return xmlHttp;
}

function getArticles(sourceNodeId,categoryName,code,unit){
	
	var elem = document.getElementById(sourceNodeId);
	//alert("adsfdf"+sourceNodeId+" "+elem);
	if (elem==null){
		window.location = "?unit="+unit+"&code="+code+"&component="+sourceNodeId;
		return;
	}else{
		//alert("IN POST");
		var xy = sourceNodeId+'.getArticles(sourceNodeId,categoryName,code,unit)';
		eval(xy);
	//loadMaps();
	}
}

function changePic(elem){
	var image = document.getElementById("imbig");
	var elemstr = elem.id;
 
	var srcold = image.src;
	/*if ((elem.id).indexOf("renti")!=-1)
	   document.getElementById("imbig").setAttribute("src","../../../platonimages/images/mrkteo/renti/"+elem.id+".jpg");	
	if ((elem.id).indexOf("XAID")!=-1)
		document.getElementById("imbig").setAttribute("src","../../../platonimages/images/mrkteo/XAIDARI/"+elem.id+".jpg");
	if ((elem.id).indexOf("ANAR")!=-1)
		document.getElementById("imbig").setAttribute("src","../../../platonimages/images/mrkteo/ANARGIROI/"+elem.id+".jpg");
	if ((elem.id).indexOf("ANAR")!=-1)
		document.getElementById("imbig").setAttribute("src","../../../platonimages/images/mrkteo/ANARGIROI/"+elem.id+".jpg");*/
	image.src=elem.src;
	elem.src = srcold;
	setOpacity(image, 0);
	image.style.visibility = 'visible';
	fadeIn("imbig",0);
}

function setOpacity(obj, opacity) {
	opacity = (opacity == 100)?99.999:opacity;
  
	// IE/Win
	obj.style.filter = "alpha(opacity:"+opacity+")";
  
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = opacity/100;
  
	// Older Mozilla and Firefox
	obj.style.MozOpacity = opacity/100;
  
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity = opacity/100;
}

function fadeIn(objId,opacity) {
	if (document.getElementById) {
		obj = document.getElementById(objId);
		if (opacity <= 100) {
			setOpacity(obj, opacity);
			opacity += 10;
			window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);
		}
	}
}

function load() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(37.4419, -122.1419), 13);
	}
}

function isDisekto(tempyear){

	if(tempyear % 4 == 0 && tempyear % 100 != 0){
		
		return true;
	}
	else{
		if(tempyear % 400 == 0){
		
			return true;
		}
	
		return false;
	}
	
}

/*function potePernaoKteo(){
	window.addEvent('domready', function() {
		Sexy = new SexyAlertBox();
	});
	

	
	var year = document.getElementById("year").value;
	year = parseInt(year);
	//alert(year+4);
	
	var date = document.getElementById("date").value;
	date = parseInt(date );
	var month = document.getElementById("month").value;
	month = parseInt(month );
	var enddate,endmonth,endyear;
	if (document.getElementById("type").value=="2" || (document.getElementById("type").value=="1" && year>=2005)){
 
		//gia mines me 31 meres
		if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
			if (date>21){
				var tt="αρχικού";
				if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="2"){
			
					year=year+2;
					tt="περιοδικού"
				}
				else if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="1"){
					if (year>=2007)
						year=year+2;
					else
						year=year+3;
			 	
					tt="περιοδικού"
				}
				else
					year=year+4;
				endyear=year;
				endmonth=month;
		
				if (date>24){
					if (month==12){
						endmonth=1;endyear=endyear+1;
					}
					else{
						endmonth=endmonth+1;
					}
					enddate=31-date;
					enddate=7-enddate;
				
				}
				else
					enddate=date+7;
				date=date-21;
				var myDate=new Date();
				myDate.setFullYear(endyear,(endmonth-1),enddate);
      
				var today = new Date();

				if (myDate>today)
				{
					Sexy.info("Το ημερολογιακό διάστημα <br>εμπρόθεσμου "+tt+" τεχνικού ελέγχου <Br>για το όχημα σας είναι <br><b>Aπό:</b>"+date+"/"+month+"/"+year+" <Br><b>Mέχρι:</b>"+enddate+"/"+endmonth+"/"+endyear);
			
				}
				else
				{
					Sexy.alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
				}//alert("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:"+date+"/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
			}
			else{
				var tt="αρχικού"
				if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="2"){
					year=year+2;
		  
					tt="περιοδικού"
				}
				else if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="1"){
					if (year>=2007)
						year=year+2;
					else
						year=year+3;
			 	
					tt="περιοδικού"
				}
				else
					year=year+4;
			
				endyear=year;
				enddate=date+7;
				endmonth=month;
			
			
				date=21-date-1;
			
				if(isDisekto(year)==true && month==3){
					date=29-date-1;
				}
				else if(month==3)
					date=28-date-1;
				else if (month==8)
					date=31-date-1;
				else
					date=30-date-1;
				if (month>1)
					month=month-1;
				else{
					year=year-1;month=12;
				}
		
				var myDate=new Date();
				myDate.setFullYear(endyear,(endmonth-1),enddate);
      
				var today = new Date();

				if (myDate>today)
				{
					Sexy.info("Το ημερολογιακό διάστημα <br>εμπρόθεσμου "+tt+" τεχνικού ελέγχου <Br>για το όχημα σας είναι <br><b>Aπό:</b>"+date+"/"+month+"/"+year+" <Br><b>Mέχρι:</b>"+enddate+"/"+endmonth+"/"+endyear);
			
				}
				else
				{
					Sexy.alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
				}
			
			//alert("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:"+date+"/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
			}
		}
		//TELOS 31 meres
		else
		//gia mines me 30 meres
		if(month==4 || month==6 || month==9 || month==11){
			if (date>21){
				var tt="αρχικού"
				if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="2"){
					year=year+2;
					tt="περιοδικού"
				}
				else if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="1"){
					if (year>=2007)
						year=year+2;
					else
						year=year+3;
			 	
					tt="περιοδικού"
				}
				else
					year=year+4;
				endyear=year;
				endmonth=month;
		
				if (date>23){
					if (month==12){
						endmonth=1;endyear=endyear+1;
					}
					else{
						endmonth=endmonth+1;
					}
					enddate=31-date;
					enddate=7-enddate+1;
				
				}
				else
					enddate=date+7;
				date=date-21;
				var myDate=new Date();
				myDate.setFullYear(endyear,(endmonth-1),enddate);
      
				var today = new Date();

				if (myDate>today)
				{
					Sexy.info("Το ημερολογιακό διάστημα <br>εμπρόθεσμου "+tt+" τεχνικού ελέγχου <Br>για το όχημα σας είναι <br><b>Aπό:</b>"+date+"/"+month+"/"+year+" <Br><b>Mέχρι:</b>"+enddate+"/"+endmonth+"/"+endyear);
			
				}
				else
				{
					Sexy.alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
				}	//alert("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:"+date+"/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
			}
			else{
				var tt="αρχικού"
				if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="2"){
					year=year+2;
					tt="περιοδικού"
				}
				else if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="1"){
					if (year>=2007)
						year=year+2;
					else
						year=year+3;
			 	
					tt="περιοδικού"


				}
				else
					year=year+4;
				endyear=year;
				enddate=date+7;
				endmonth=month;
			
				if (month>1)
					month=month-1;
				else{
					year=year-1;month=12;
				}
		
				date=21-date-1;
				date=31-date-1;
		
				var myDate=new Date();
				myDate.setFullYear(endyear,(endmonth-1),enddate);
      
				var today = new Date();

				if (myDate>today)
				{
					Sexy.info("Το ημερολογιακό διάστημα <br>εμπρόθεσμου "+tt+" τεχνικού ελέγχου <Br>για το όχημα σας είναι <br><b>Aπό:</b>"+date+"/"+month+"/"+year+" <Br><b>Mέχρι:</b>"+enddate+"/"+endmonth+"/"+endyear);
			
				}
				else
				{
					Sexy.alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
				}///alert("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:"+date+"/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
			}
		}
		//TELOS 30 meres
		else
		//gia febrouario me 29 meres
		if(month==2 && isDisekto(year)==true){
			if (date>21){
				var tt="αρχικού"
				if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="2"){
					year=year+2;
					tt="περιοδικού"
				}
				else if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="1"){
					if (year>=2007)
						year=year+2;
					else
						year=year+3;
			 	
					tt="περιοδικού"
				}
				else
					year=year+4;
				endyear=year;
				endmonth=month;
		
				if (date>22){
					if (month==12){
						endmonth=1;endyear=endyear+1;
					}
					else{
						endmonth=endmonth+1;
					}
					enddate=29-date;
					enddate=7-enddate;
				
				}
				else
					enddate=date+7;
				date=date-21;
				var myDate=new Date();
				myDate.setFullYear(endyear,(endmonth-1),enddate);
      
				var today = new Date();

				if (myDate>today)
				{
					Sexy.info("Το ημερολογιακό διάστημα <br>εμπρόθεσμου "+tt+" τεχνικού ελέγχου <Br>για το όχημα σας είναι <br><b>Aπό:</b>"+date+"/"+month+"/"+year+" <Br><b>Mέχρι:</b>"+enddate+"/"+endmonth+"/"+endyear);
			
				}
				else
				{
					Sexy.alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
				}	//alert("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:"+date+"/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
			}
			else{
				var tt="αρχικού";
				if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="2"){
					year=year+2;
					tt="περιοδικού"
				}
				else if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="1"){
					if (year>=2007)
						year=year+2;
					else
						year=year+3;
			 	
					tt="περιοδικού"
				}
				else
					year=year+4;
				endyear=year;
				enddate=date+7;
				endmonth=month;
			
				if (month>1)
					month=month-1;
				else{
					year=year-1;month=12;
				}
		
				date=21-date-1;
				date=31-date-1;
		
				var myDate=new Date();
				myDate.setFullYear(endyear,(endmonth-1),enddate);
      
				var today = new Date();

				if (myDate>today)
				{
					Sexy.info("Το ημερολογιακό διάστημα <br>εμπρόθεσμου "+tt+" τεχνικού ελέγχου <Br>για το όχημα σας είναι <br><b>Aπό:</b>"+date+"/"+month+"/"+year+" <Br><b>Mέχρι:</b>"+enddate+"/"+endmonth+"/"+endyear);
			
				}
				else
				{
					Sexy.alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
				}//alert("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:"+date+"/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
			}
		}
		//TELOS febrouario me 29 meres
		
		//gia febrouario me 28 meres
		else
		if(month==2 && isDisekto(year)==false){

			if (date>21){

				var tt="αρχικού"
				if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="2"){
					year=year+2;
					tt="περιοδικού"
				}
				else if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="1"){
					if (year>=2007)
						year=year+2;
					else
						year=year+3;
			 	
					tt="περιοδικού"
				}
				else
					year=year+4;
				endyear=year;
				endmonth=month;
		
				if (month==12){
					endmonth=1;
					endyear=endyear+1;
				}
				else{
					endmonth=endmonth+1;
				}
			
				enddate=28-date;
			
				enddate=7-enddate;
				
			
		  
				//enddate=date+7;
				date=date-21;
				var myDate=new Date();
				myDate.setFullYear(endyear,(endmonth-1),enddate);
      
				var today = new Date();

				if (myDate>today)
				{
					Sexy.info("Το ημερολογιακό διάστημα <br>εμπρόθεσμου "+tt+" τεχνικού ελέγχου <Br>για το όχημα σας είναι <br><b>Aπό:</b>"+date+"/"+month+"/"+year+" <Br><b>Mέχρι:</b>"+enddate+"/"+endmonth+"/"+endyear);
			
				}
				else
				{
					Sexy.alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
				}	//alert("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:"+date+"/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
			}
			else{
				var tt="αρχικού"
				if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="2"){
					year=year+2;
					tt="περιοδικού"
				}
				else if (document.getElementById("eidos").value=="2" && document.getElementById("type").value=="1"){
					if (year>=2007)
						year=year+2;
					else
						year=year+3;
			 	
					tt="περιοδικού"
				}
				else
					year=year+4;
				endyear=year;
				enddate=date+7;
				endmonth=month;
	
				if (month>1)
					month=month-1;
				else{
					year=year-1;month=12;
				}
		
				date=21-date-1;
				date=31-date-1;
		
				var myDate=new Date();
				myDate.setFullYear(endyear,(endmonth-1),enddate);
      
				var today = new Date();

				if (myDate>today)
				{
					Sexy.info("Το ημερολογιακό διάστημα <br>εμπρόθεσμου "+tt+" τεχνικού ελέγχου <Br>για το όχημα σας είναι <br><b>Aπό:</b>"+date+"/"+month+"/"+year+" <Br><b>Mέχρι:</b>"+enddate+"/"+endmonth+"/"+endyear);
			
				}
				else
				{
					Sexy.alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
				}//alert("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:"+date+"/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
			}
		//TELOS febrouario me 28 meres
		}
	}
		
	else {
	
		if (year<2005){
			Sexy.alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
			//alert("Το όχημα σας είναι ήδη εκπρόθεσμο για αρχικό τεχνικό έλεγχο");
			return;
		}
		var d = new Date();
	
		var currentYear = d.getFullYear();
		year = currentYear;
		d = d.getMonth();
		d=d+1;
		if (d>month){
			year=year+1;
		}
		endmonth=month;
		endyear=year;
		if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)
			enddate=31;
		if(month==4 || month==6 || month==9 || month==11)
			enddate=30;
		if(month==2 && isDisekto(year)==true)
			enddate=29;
		if(month==2 && isDisekto(year)==false)
			enddate=28;
		Sexy.info("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:1/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
	//alert("Το ημερολογιακό διάστημα εμπρόθεσμου αρχικού τεχνικού ελέγχου \nγια το όχημα σας είναι από:"+date+"/"+month+"/"+year+" μέχρι:"+enddate+"/"+endmonth+"/"+endyear);
	
	}

//Else if (document.getElementById("eidos").value=="2"){
//	if (document.getElementById("type").value=="1"){
		
//		Sexy.info("Δεν ξέρω πότε θα περάσετε τεχνικό έλεγχο");

//	}
//	if (document.getElementById("type").value=="2"){
//		endyear=year+4;
//		endmonth=month;
//		enddate=date;
//		Sexy.info("Θα περάσετε εμπρόθεσμο τεχνικό έλεγχο \nστις:"+enddate+"/"+endmonth+"/"+endyear);
//	}
//}
}*/

function isElement(o){
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement : //DOM2
    typeof o === "object" && o.nodeType === 1 && typeof o.nodeName==="string"
);
}


function postAction(elem){
	var inp;
	if(isElement(elem)){
		inp=elem;
	}else{
		inp=document.getElementById(elem);
	}
	var dc="";
	var inpval=inp.value;
	var value="";
	if(inp.getAttribute('hasCode')=="true"){
		if(inpval!=""){
			value=inp.getAttribute('code');
		}else{
			value=inpval;
		}
	}else{
		if(inp.type=='checkbox'){
			if(inp.checked){
				value='1';
			}else{
				value='0';
			}
		}else{
			value=inpval;
		}
	}
	if (inp.getAttribute('dataVariable')!=null){
		dc=inp.getAttribute('dataVariable');
	}else if (inp.getAttribute('dataComponent')!=null && inp.getAttribute('dataComponent')!=""){
		dc=inp.getAttribute('dataComponent');
	}else{
		dc=inp.getAttribute('formDataComponent')+"."+inp.getAttribute('formField');
	}
	var extra="";
	if(jQuery(inp).hasClass('gridInput')){
		extra="&recordId="+inp.getAttribute('recId')+"&row="+inp.getAttribute('row');
	}
	var xmlUrl = "main"
	var unit = document.getElementById("unit").value;
	var strParams = "actorCode="+document.getElementById('thisActorCode').value+"&component=PlatonAction&action=set value&dataAction=WEB_SETVALUE&value="+value+"&unit="+unit+"&dataComponent="+dc+"&commit="+inp.getAttribute("commit")+extra;
	var loader1 = new  net.ContentLoaderThis(xmlUrl,setChanges,null, inp, null,"POST",strParams); 
}

function setChanges(){
	var xml;
	var pp=0;
	var inp;
	if(arguments[0]){
		xml = arguments[0];
	}else{
		xml = this.req.responseXML;
		inp=this.obj_reference;
	}
	mv.addMsg(xml);
	if (xml!=null && xml.getElementsByTagName("changed")[0]!=null){
		var inputs=document.getElementsByTagName("input");
		var txtareas=document.getElementsByTagName("textarea");
		var inputslen=inputs.length;
		var txtareaslen=txtareas.length;
		var changed=xml.getElementsByTagName("changed")[0].childNodes;
		for(var v=0; v < changed.length; v++){
			var chang=changed[v];
			var ch = chang.tagName;
			var type=chang.getAttribute('type');
			var editMode=chang.getAttribute('editMode');
			if (type=="variable"){
				for (var j=0;j<inputslen;j++){
					var inp = inputs[j];
					if(!inp || inp.getAttribute('doNo')=='true'){
						//if somehow exe figei to input apo to dom
						continue;
					}
					if (inp.getAttribute("dataComponent") == ch){//simple variable
						inp.value=chang.getAttribute("value");
						if (editMode!=null && editMode=="true"){
							inp.removeAttribute("disabled");
							jQuery(inp).next().removeClass('disabledList');
						}else if (editMode=="false"){
							inp.setAttribute("disabled","true");
							jQuery(inp).next().addClass('disabledList');
						}
						jQuery(inp).trigger("valueChangedEvent");
					}/*else if(inp.getAttribute("datavariable")==ch){
						//ti tha ginei an allaksei timi i variable pou sindeetai me mia lista?
					}*/
				}
			}else if (type=="list"){
				//de xreiazetai tpt efoson oi listes einai dinamikes
			}else if (type=="record"){
				var isActive=chang.getAttribute('isActive');
				var row=chang.getAttribute('row');
				var set=chang.getAttribute('set');
				//an i grammi den einai active tote bres to table me dataset=set kai kane ti row disabled
				if(isActive=="false" && set!="s_LinkSet"){
					var tr=jQuery('table[dataset='+set+'] tbody tr:eq('+row+')');
					if(tr.length>0){
						tr.addClass("deletedRow");
						tr.removeClass("selectedRow");
						tr.removeClass("isSelected");
						tr.trigger('rowDisabled'); //trigger the event to unbind the click in the row. currently used for grid
					}
				}else{
					//ilopoisi ean einai true. xreiazetai??
				}
				var chnodes=chang.childNodes;
				var len=chnodes.length;
				for(j=0; j<len; j++){
					var tname=chnodes[j].tagName;
					for (var i=0;i<inputslen;i++){
						var inp = inputs[i];
						if(!inp || inp.getAttribute('doNo')=='true'){
							//if somehow exe figei to input apo to dom i de theloume na kanei tpt
							continue;
						}
						if(inp.type=="file"){
							continue;
						}
						if (inp.getAttribute('dataComponent')==ch+"."+tname ){//&&  && !jQuery(inp).hasClass("gridInput")  pgrdInput
							var el=chnodes[j];
							var bal=chnodes[j].firstChild;
							if(bal){
								bal=chnodes[j].firstChild.nodeValue;
							}else{
								bal="";
							}
							if(inp.type=="checkbox"){
								if(bal=='1'){
									inp.checked=true;
								}else{
									inp.checked=false;
								}
							}else{
								inp.value=bal;
								if(el.getAttribute('code')){
									inp.setAttribute(code, el.getAttribute('code'));
								}
							}							
							if (editMode!=null && editMode=="true"){
								inp.removeAttribute("disabled");
								jQuery(inp).next().removeClass('disabledList');
							}else if (editMode=="false"){
								inp.setAttribute("disabled","true");
								jQuery(inp).next().addClass('disabledList');
							}
							jQuery(inp).trigger("valueChangedEvent");
						}
					}
					for (var i=0;i<txtareaslen;i++){
						var inp =txtareas[i];
						if(!inp || inp.getAttribute('doNo')=='true'){
							//if somehow exe figei to input apo to dom i de theloume na kanei tpt
							continue;
						}
						if (inp.getAttribute('dataComponent')==ch+"."+tname){
							var bal=chang.childNodes[j].firstChild;
							if(bal){
								bal=chang.childNodes[j].firstChild.nodeValue;
							}else{
								bal="";
							}
							inp.value=bal;
							if (editMode!=null && editMode=="true")
								inp.removeAttribute("disabled");
							else if (editMode=="false")
								inp.setAttribute("disabled","true");
							jQuery(inp).trigger("valueChangedEvent");
						}
					}
				}
			}else if (type=="dataset"){
				//alert('data set:'+pp);
				//if (pp>0 || xml.getElementsByTagName("g_questionRec")[0]==null)
				//	continue;
				//pp++;
				var tablesDataset = jQuery("table[dataset='"+ch+"']");
				var masterId=chang.getAttribute('masterId');
				if (tablesDataset.length>0){
					var idd = tablesDataset[0].id;
					idd=idd.replace(/_mainTable/,"");
					var obj=tables.getItem(document.getElementById('unit').value+idd);
					if(obj.masterId==masterId){
						tables.getItem(document.getElementById('unit').value+idd).refreshTable();
					}
				}
			}else if (ch=='platonmessage'){
				var message = chang.childNodes[0].nodeValue;
				alert(message);
			}else if (ch=='platonHtml'){
				var message = chang.childNodes[0].nodeValue;
				alert(message);
			}else if (ch=='platonJavascript'){
				var script = chang.childNodes[0].nodeValue;
				eval(script);
			}else{
				//alert('No type attribute specified in changed element');
			}
		}
	}
	if(inp){
		//checkDflt(inp, true); //not used pros to paron
	}
}

function hourList(){
	var xml = this.req.responseXML;
	//alert(this.req.responseText);
	var unit = window.location.href ;
	unit = unit.substring(unit.indexOf("unit=")+5,unit.length);
	
	if (unit.indexOf("&")!=-1)
		unit = unit.substring(0,unit.indexOf("&"));
  
	if (unit.indexOf("#")!=-1)
		unit = unit.substring(0,unit.indexOf("#"));

	if (xml!=null && xml.getElementsByTagName("message")[0]!=null && unit=="KT_Accounts"){
		alert(xml.getElementsByTagName("message")[0].childNodes[0].nodeValue);
	}
	/*if (xml!=null && xml.getElementsByTagName("message")[0]!=null)
{
	//alert(xml.getElementsByTagName("message")[0].childNodes[0].nodeValue);
	var a3 = document.getElementById("s_article3");
		 	 while ( a3.childNodes.length >= 1 )
    				{
        					a3.removeChild( a3.firstChild );       
    				} 
		 	val2= xml.getElementsByTagName("message")[0].childNodes[0].nodeValue;
		 	//alert(val2);
		 	//a3.appendChild(document.createElement("<br>"));
		 	a3.appendChild(document.createTextNode(val2));
		 	a3.appendChild(document.createElement("<br>"));
}	*/

	if (xml!=null && xml.getElementsByTagName("changed")[0]!=null)
	{
		//alert(xml.getElementsByTagName("result"));
		//alert(this.req.responseText);
		for(var v=0;v<xml.getElementsByTagName("changed")[0].childNodes.length;v++){
		
			var ch = xml.getElementsByTagName("changed")[0].childNodes[v].tagName;
			if (ch=="s_ReturnVar"){
				var a3 = document.getElementById("s_article3");
				//alert(a3.childNodes[1].childNodes[0].getAttribute("class"));
				var aa = a3.childNodes[0];
				if (aa.tagName!="DIV" && aa.tagName!="div")
					aa = a3.childNodes[1];
				var aa1 = aa.childNodes[0];
				//alert(a3.getAttribute("class"));
				//	a3.setAttribute("class","messageBodyIe");
		 	
				while ( aa1.childNodes.length >= 1 )
				{
					aa1.removeChild( aa1.firstChild );
				}
				val2= xml.getElementsByTagName("changed")[0].childNodes[v].getAttribute('value');
				//alert(val2);
				aa1.appendChild(document.createTextNode(val2));
			//alert(a3.getAttribute("class"));
			}
		
			var type=xml.getElementsByTagName("changed")[0].childNodes[v].getAttribute('type');

			var editMode=xml.getElementsByTagName("changed")[0].childNodes[v].getAttribute('editMode');
		 
			if (xml.getElementsByTagName("changed")[0].childNodes[v].getAttribute("value")!=null){
				for (var j=0;j<document.getElementsByTagName("input").length;j++){
					var inp = document.getElementsByTagName("input")[j];
					//my code //here
					if (inp.getAttribute("dataComponent") == ch || inp.getAttribute("formDataComponent") == ch){
						inp.value=xml.getElementsByTagName("changed")[0].childNodes[v].getAttribute("value");
						if (editMode!=null && editMode=="true")
							inp.removeAttribute("disabled");
						else if (editMode=="false")
							inp.setAttribute("disabled","true");
					}
				// to here
				}
			//alert(inp.id+" "+inp.getAttribute("dataComponent"));
			//if (inp.getAttribute("dataComponent") == ch)
			//alert("variablefield:"+inp.id);
			}
			else if (type==null && xml.getElementsByTagName("changed")[0].childNodes[v].childNodes.length==0){
				for (var i=0;i<document.getElementsByTagName("input").length;i++){
					var inp = document.getElementsByTagName("input")[i];
					if (inp.getAttribute("dataComponent") == ch || inp.getAttribute("formDataComponent")==ch){
						if (editMode!=null && editMode=="true")
							inp.removeAttribute("disabled");
						else if (editMode=="false")
							inp.setAttribute("disabled","true");
					}
				}
		 	  
				for (var i=0;i<document.getElementsByTagName("select").length;i++){
		 	  	
					var inp = document.getElementsByTagName("select")[i];
					if (inp.getAttribute("dataComponent") == ch || inp.getAttribute("formDataComponent")==ch){
						if (editMode!=null && editMode=="true")
							inp.removeAttribute("disabled");
						else if (editMode=="false")
							inp.setAttribute("disabled","true");
					}
				}
			}
			else{
				//my code //here
				var len=xml.getElementsByTagName("changed")[0].childNodes[v].childNodes.length;
				for(j=0; j<len; j++){
					var tname=xml.getElementsByTagName("changed")[0].childNodes[v].childNodes[j].tagName;
					for (var i=0;i<document.getElementsByTagName("input").length;i++){
						var inp = document.getElementsByTagName("input")[i];
						if (inp.id.endsWith(tname) && (inp.getAttribute('formDataComponent')==ch || inp.getAttribute("dataComponent") == ch)){
							inp.value=xml.getElementsByTagName("changed")[0].childNodes[v].childNodes[j].getAttribute('value');
							if (editMode!=null && editMode=="true")
								inp.removeAttribute("disabled");
							else if (editMode=="false")
								inp.setAttribute("disabled","true");
						}
					}
					for (var i=0;i<document.getElementsByTagName("textarea").length;i++){
						var inp = document.getElementsByTagName("textarea")[i];
						if (inp.id.endsWith(tname) && (inp.getAttribute('formDataComponent')==ch || inp.getAttribute("dataComponent") == ch)){
							inp.value=xml.getElementsByTagName("changed")[0].childNodes[v].childNodes[j].getAttribute('value');
							if (editMode!=null && editMode=="true")
								inp.removeAttribute("disabled");
							else if (editMode=="false")
								inp.setAttribute("disabled","true");
						}
					}
				}
				//to here
			
				for (var i=0;i<document.getElementsByTagName("select").length;i++){
					var inp = document.getElementsByTagName("select")[i];
					if (inp.getAttribute("dataComponent") == ch){
						var str="";
		 	  	
						while ( inp.childNodes.length >= 1 )
						{
							inp.removeChild( inp.firstChild );
						}

						for (var j=0;j<xml.getElementsByTagName("changed")[0].childNodes[v].childNodes.length;j++){
							var val = xml.getElementsByTagName("changed")[0].childNodes[v].childNodes[j].getAttribute('value');
							var val2 = xml.getElementsByTagName("changed")[0].childNodes[v].childNodes[j].firstChild.nodeValue;
							var oOption = document.createElement("OPTION");
							oOption.value=val;
		   					
							oOption.appendChild(document.createTextNode(val2));
							inp.appendChild(oOption);
   
						//str+="<option value=\""+val+"\">"+val2+"</option>";
						}
		 	  		
					}
				//alert("selectfield:"+inp.id);
				}
			}
		 
		 
		}
	//alert(xml.getElementsByTagName("changed")[0].childNodes[v].tagName);
	}



	if (xml!=null && xml.getElementsByTagName("action")[0]!=null && xml.getElementsByTagName("action")[0].childNodes[0].nodeValue=="clear")
	{
		var ch = xml.getElementsByTagName("action")[0].getAttribute('dataComponent');
		//alert(ch);
		for (var i=0;i<document.getElementsByTagName("input").length;i++){
		 	  	
			var inp = document.getElementsByTagName("input")[i];
			if (inp.getAttribute("dataComponent") == ch || inp.getAttribute("formDataComponent")==ch){
				inp.value="";
			}
		}
	
		for (var i=0;i<document.getElementsByTagName("select").length;i++){
		 	  	
			var inp = document.getElementsByTagName("select")[i];
			if (inp.getAttribute("dataComponent") == ch || inp.getAttribute("formDataComponent")==ch){
				inp.value="epilogi";
			}
		}
	
	}
}

function changePics() {

	var img1 = document.getElementById('imarr1');
  
 
	if (img1.src.indexOf('up')!=-1){
		img1.src = '../../../platonimages/images/down_arrow.gif';
  	
	}
	else {
		img1.src = '../../../platonimages/images/up_arrow.gif';
  	
	}
 
}

/*jQuery.jPrintArea=function(el)
{
var iframe=document.createElement('IFRAME');
var doc=null;
$(iframe).attr('style','position:absolute;width:0px;height:0px;left:-500px;top:-500px;');
document.body.appendChild(iframe);
doc=iframe.contentWindow.document;
var links=window.document.getElementsByTagName('link');
for(var i=0;i<links.length;i++)
if(links[i].rel.toLowerCase()=='stylesheet')
doc.write('<link type="text/css" rel="stylesheet" href="'+links[i].href+'"></link>');
doc.write('<div class="'+$(el).attr("class")+'">'+$(el).html()+'</div>');
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
alert('Printing...');
document.body.removeChild(iframe);
}*/

function printIt(elemdiv, scriptdiv, dcomp, comp) {
	var unit=document.getElementById("unit").value;
	var actor=document.getElementById("thisActorCode").value;
	var strParams="unit="+unit+"&actor="+actor+"&action=getPrintDialog&dataComponent="+dcomp+"&prScript="+scriptdiv+"&el="+elemdiv.id+"&pagecomp="+comp;
	var check_loader = new net.ContentLoader("main",onGotPrintDialog,null,"POST",strParams);
}

function onGotPrintDialog(){
	var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){
		var title=doc.getElementsByTagName("title")[0].firstChild.nodeValue;
		var content=doc.getElementsByTagName("content")[0].firstChild.nodeValue;
		var contentWin=new Window({id: "mainPrintDialog", className: 'windowStyle', title: title, hideEffect:Element.hide, showEffect:Element.show, minimizable:false,maximizable:false, resizable:false, wiredDrag: true, destroyOnClose: true, width:230, height:170, modal:true});
		contentWin.setHTMLContent(content);
		contentWin.showCenter();
	}else if(status[0].firstChild.nodeValue=='-1'){
		alert(message[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-4'){
		var uarl=doc.getElementsByTagName("url");
		window.location=uarl[0].firstChild.nodeValue;
	}
}

function choosePrint(obj, dComp, el, prscr){
	if(obj.selectedIndex==0){
		justPrint(document.getElementById(el), prscr);
	}else{
		var xmlString = "<?xml version='1.0' encoding='UTF-8'?>"+
		"<elements>"+
		"<actor>"+document.getElementById('thisActorCode').value+"</actor>"+
		"<unit>"+document.getElementById('unit').value+"</unit>"+
		"<pageAction>getReport</pageAction>"+
		"<action>getReport</action>"+
		"<dataComponent>"+dComp+"</dataComponent>"+
		"<report>"+obj.value+"</report>"+
		"<componentId>"+dComp+"</componentId>"+
		"</elements>";
		xmlString=xmlString.replace(/&/g,'&amp;');
		var loader1 = new  net.send("main", onGotReport,null, "POST",xmlString,"text/xml");
	}
	Windows.getWindow('mainPrintDialog').close();
}

function onGotReport(){
	var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	var content = doc.getElementsByTagName("content");
	var printStr = content[0].childNodes[0].nodeValue
	var str = "";
	var win = window.open();
	self.focus();
	win.document.open();
	win.document.write("<html><head>"+str+"</head><body>"+printStr+"</body></html>");
	win.document.close();
	win.print();
	if(status[0].firstChild.nodeValue=='0'){
		var url = doc.getElementsByTagName("url");
		window.open(url[0].firstChild.nodeValue, '_blank');
	}else if(status[0].firstChild.nodeValue=='1'){
		alert(doc.getElementsByTagName("message")[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-1'){
	}else if(status[0].firstChild.nodeValue=='-4'){
		var uarl=doc.getElementsByTagName("url");
		window.location=uarl[0].firstChild.nodeValue;
	}
}

function justPrint(elemdiv, scriptdiv){
	elemDiv = jQuery(elemdiv).parent().parent().parent().parent().parent().parent();
	var str = "";
	var links=window.document.getElementsByTagName('link');
	for(var i=0;i<links.length;i++)
		if(links[i].rel.toLowerCase()=='stylesheet')
			str+='<link type="text/css" rel="stylesheet" href="'+links[i].href+'"></link>';
	//doc.write('<div class="'+jQuery(el).attr("class")+'">'+jQuery(el).html()+'</div>');
	var sc=document.getElementById(scriptdiv);
	if(sc){
		var chart=sc.innerHTML.replace(/&gt;/g,">");
		str+='<script type="text/javascript" src="codebase/jquery/jquery-1.4.2.min.js"></script>'+
			'<script type="text/javascript" src="codebase/Highcharts-2.1.0/js/highcharts.js"></script>'+
			'<script type="text/javascript">jQuery(document).ready(function() { '+chart+' });</script>';
	}
	win = window.open();
	self.focus();
	win.document.open();
	win.document.write("<html><head>"+str+"<style>div{overflow:visible !important;}</style></head><body>"+elemDiv.html()+"</body></html>");
	win.document.close();
	win.print();
//win.close();
}

function encodeGreek(greekText){
	//alert(greekText);
	var clearString=greekText;
	clearString = escape(clearString);
	clearString = clearString.replace(/%u/g,"..u");
	clearString = clearString.replace(/%20/g," ");
	clearString = clearString.replace(/%2C/g,",");
	clearString = clearString.replace(/%/g,"");
	// alert(clearString);
	return clearString;
}

function getLogUsers(){
	var xmlUrl = "LogViewer";
	var strParams = "action=getLogUsers";
	var loader1 = new  net.ContentLoader(xmlUrl,getLogResponse,null, "POST",strParams);
}

function getLog(){
	var xmlUrl = "LogViewer";
	var fromd = document.getElementById('fromDate').value;
	var fromt = document.getElementById('fromTime').value;
	var tot = document.getElementById('toTime').value;
	var strParams = "fromDate="+fromd+"&fromTime="+fromt+"&toTime="+tot+"&tab="+selectedLogTab;
	var loader1 = new  net.ContentLoader(xmlUrl,getLogResponse,null, "POST",strParams);
}

function getLogResponse(){
	var doc =this.req.responseText;
	document.getElementById('logarea').innerHTML="<pre>"+doc+"</pre>";
}

function killServer( server ){
    var xmlUrl = "LogViewer";
	var strParams = "action=killServer&server="+server;
	var loader1 = new  net.ContentLoader(xmlUrl,alertResponse,null, "POST",strParams);    
}
function alertResponse(){	
	alert(this.req.responseText);
}
var selectedLogTab="ApacheTab";

function openLogTab(tab){
	document.getElementById("logarea").innerHTML="";

	if(tab=="actorsbox"){
		var sel = document.getElementById(tab);
		var choice=sel.options[sel.selectedIndex].value;
		var pos=sel.options[sel.selectedIndex].id;
		var paged=parseInt(pos)/5;
		paged=parseInt(paged);
		tab=choice+"Tab";
		window.location="LogViewer?page="+paged+"&requestedActor="+tab;;
	}
	else{
		var sel = document.getElementById("actorsbox");
		//sel.options[sel.selectedIndex].value;
		sel.selectedIndex="none";
	}
	//alert(tab);
	//alert(selectedLogTab);
    
	if(selectedLogTab!==""){
		if(document.getElementById(selectedLogTab)!=null)
			document.getElementById(selectedLogTab).className=" ";
	}
	if(document.getElementById(tab)!=null)
		document.getElementById(tab).className="selected";
	
	selectedLogTab=tab;
	
	//Once the tab is selected. Fetch the contents
	getLog();
}

function viewField(field, set, row){
	var unit=document.getElementById('unit').value;
	var actor=document.getElementById('thisActorCode').value;
	var strParams = "actor="+actor+"&unit="+unit+"&action=viewField&pageAction=viewField&field="+field+"&set="+set+"&row="+row;
	var loader1 = new  net.ContentLoader("main",onViewField,null, "POST",strParams);
}

function onViewField(){
	
}

function fetchArticle(obj, frmId, id, table){
	var unit=document.getElementById('unit').value;
	var actor=document.getElementById('thisActorCode');
	if(actor){
		actor=actor.value;
	}else{
		actor=obj.getAttribute('actor');
	}
	var fieldName=obj.getAttribute('fldName');
	if (fieldName!=null && fieldName.indexOf(".")>=0)
		fieldName = fieldName.substring(fieldName.indexOf(".")+1,fieldName.length);
	var file="", date="", time="";
	var isAll="false";
	if(obj.getAttribute('file')){
		file=obj.getAttribute('file');
		file=hexnorm(file);
	}
	if(obj.getAttribute('isAll')){
		isAll="true";
	}
	if(obj.getAttribute('date')){
		date=obj.getAttribute('date');
		time=obj.getAttribute('time');
	}
	var action="main?actor="+actor+"&action=fetchArticle&pageAction=fetchArticle&field="+fieldName+"&unit="+unit+"&id="+id+"&table="+table+"&component=PlatonAction&file="+file+"&date="+date+"&time="+time+"&isAll="+isAll;
	var frm=document.getElementById(frmId);
	frm.action=action;
	//alert(action);
	frm.submit();
}

function onFetchArticle(){
	var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){
		var url = doc.getElementsByTagName("url")[0].firstChild.nodeValue;
		if(url.endsWith(".pdf") || url.endsWith(".txt") || url.endsWith(".html")){
			var win=window.open(url, '_blank');
		}else{
			var ifra=document.getElementById('uploadTrickFrame');
			ifra.src=url;
		}
	}else if(status[0].firstChild.nodeValue=='1'){
		alert(doc.getElementsByTagName("message")[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-1'){
	}else if(status[0].firstChild.nodeValue=='-4'){
		if(document.getElementById('postType')){
			if(document.getElementById('postType').value=='unitsMenu'){
				parent.processBlock();
				return;
			}
		}
		var uarl=doc.getElementsByTagName("url");
		window.location=uarl[0].firstChild.nodeValue;
	}
}

function sbmtLogin(){
	document.getElementById('loginForm').submit();
	jQuery("#mainTable").remove();
	var dv=document.createElement("div");
	document.body.appendChild(dv);
	jQuery(dv).html("<table style='height:100%; width:100%'>"+
						"<tr>"+
							"<td align='center'>"+
								"<object width='300' height='32' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'>"+
									"<param value='../../../platonimages/servers/Bopen/images/loader.swf' name='movie'>"+
									"<param value='high' name='quality'>"+
									"<param value='transparent' name='wmode'>"+
									"<embed width='300' height='32' wmode='transparent' type='application/x-shockwave-flash' src='../../../platonimages/servers/Bopen/images/loader.swf' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer'>"+
								"</object>"+
							"</td>"+
						"</tr>"+
					"</table>");
}

function slideToggle(el, bShow){
	if(jQuery(el).is(':hidden')){
		jQuery(el).css('display','');
	}else{
		jQuery(el).css('display','none');
	}
	/*if (jQuery(el).css('display')=="none")
	  jQuery(el).css('display','');
	else
		jQuery(el).css('display','none');
		*/
	/*
  var $el = jQuery(el), height = jQuery(el).data("originalHeight"), visible = $el.is(":visible");
  alert('after');
  // if the bShow isn't present, get the current visibility and reverse it
  if( arguments.length == 1 ) bShow = !visible;
  
  // if the current visiblilty is the same as the requested state, cancel
  if( bShow == visible ) return false;
  
  // get the original height
  if( !height ){
    // get original height
    height = jQuery(el).show().height();
    // update the height
    $el.data("originalHeight", height);
    // if the element was hidden, hide it again
    if( !visible ) $el.hide().css({height: 0});
  }

  // expand the knowledge (instead of slideDown/Up, use custom animation which applies fix)
  if( bShow ){
    jQuery(el).show().animate({height: height}, {duration: 250});
	//$el.show("normal");
  } else {
    jQuery(el).animate({height: 0}, {duration: 250, complete:function (){
        jQuery(el).hide();
      }
    });
  }*/
}

function slideToggleEl(el){
	/*if (jQuery('#'+el).css('display')=="none")
	  jQuery('#'+el).css('display','');
	else
		jQuery('#'+el).css('display','none');*/
	if(jQuery('#'+el).is(':hidden')){
		jQuery('#'+el).removeClass('hidden').css('display','');
	}else{
		jQuery('#'+el).css('display','none');
	}
}

function selectItem(clas, obj){
	obj.className=clas;
}

function deselect(clas, obj){
	if(obj.getAttribute('selected')=='false'){
		obj.className=clas;
	}
}

function changeState(inpId, state){
	var inp=document.getElementById(inpId);
	document.getElementById(inpId+"_1").checked=false;
	document.getElementById(inpId+"_2").checked=false;
	//document.getElementById(inpId+"_3").checked=false;
	document.getElementById(inpId+"_"+state).checked=true;
	inp.setAttribute('state', state);
}

function stopEvents(e){
	if (!e)
		e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation)
		e.stopPropagation();
	if (e.preventDefault)
		e.preventDefault();
	//e.returnValue = false;
}

function editMenu(obj, ulId){
	var lis=jQuery('#'+ulId+" li");
	var ul=document.getElementById(ulId);
	var length=lis.length;
	if(ul.getAttribute('edit')=="on"){
		jQuery(obj).next().next().css('display', 'none');
		jQuery(obj).parent().parent().css('height', null);
		for(var i=1; i<length; i++){
			jQuery(lis[i]).removeClass('selectedLi');
			//lis[i].setAttribute("onclick", "");
			lis[i].onclick="";
			var ihtml=lis[i].innerHTML;
			ihtml=ihtml.replace(/_onclick/g,"onclick");
			ihtml=ihtml.replace(/_href/g,"href");
			lis[i].innerHTML=ihtml;
		}
		ul.setAttribute('edit', 'off');
		var ni=document.getElementById('newMenuItem');
		if(ni){
			ni.id="";
		}
	}else{
		jQuery(obj).next().next().css('display', '');
		jQuery(obj).parent().parent().css('height', 80);
		for(var i=1; i<length; i++){
			//lis[i].setAttribute("onclick", "selectMenu(this, '"+ulId+"')");
			lis[i].onclick=function(){
					selectMenu(this, ulId)
				};
			var ihtml=lis[i].innerHTML;
			ihtml=ihtml.replace(/onclick/g,"_onclick");
			ihtml=ihtml.replace(/href/g,"_href");
			lis[i].innerHTML=ihtml;
		}
		ul.setAttribute('edit', 'on');
	}
}

function selectMenu(obj, ulId){
	var sli=getSelectedLi(ulId);
	if(sli){
		jQuery(sli).removeClass('selectedLi');
	}
	if(sli==obj){
		jQuery(obj).removeClass('selectedLi');
	}else{
		jQuery(obj).addClass('selectedLi');
	}
}

function getSelectedLi(ulId){
	var lis=jQuery('#'+ulId+" li");
	var length=lis.length;
	for(var i=1; i<length; i++){
		if(jQuery(lis[i]).hasClass('selectedLi')){
			return lis[i]
		}
	}
	return null;
}

function newMenuItem(obj, ulId){
	var win=Windows.getWindow('newMenuDialog');
	if(win){
		return;
	}
	var li=getSelectedLi(ulId);
	var level="";
	if(li){
		if(jQuery(li).hasClass("level1")){
			level="level2";
		}else if(jQuery(li).hasClass("level2")){
			//level="level2";
			level="level2";
		}
	}
	if(!li){
		jQuery(obj).parent().parent().parent().after("<li class='level1' onclick=\"selectMenu(this, '"+ulId+"')\"><a id='newMenuItem' ><span></span></a></li>");
	}else{
		jQuery(li).after("<li class='"+level+"' onclick=\"selectMenu(this, '"+ulId+"')\"><a id='newMenuItem' ><span></span></a></li>");
	}
	var content = "<div><form><table width='100%'><tr><td width='10%'>"+getMessage(5)+"</td><td><input id='menuText' type='text' /></td></tr><tr><td width='10%'>"+getMessage(6)+"</td><td><input id='menuUrl' type='text' style='width:350px'/></td></tr>"+
				"<tr><td></td><td align='right'><input type='button' value='"+getMessage(4)+"' onclick='setItemProperties(); Windows.getWindow(\"newMenuDialog\").close();' class='stylishBut'/>&nbsp;<input type='button' value='"+getMessage(3)+"' onclick='cancelnewItem(); Windows.getWindow(\"newMenuDialog\").close();' class='stylishBut'/></td></tr></table></form></div>";
	var contentWin=new Window({id: "newMenuDialog", className: 'alphacube', title: getMessage(8), hideEffect:Element.hide, showEffect:Element.show, minimizable:false,maximizable:false, resizable:true, wiredDrag: true, destroyOnClose: true, width:450, height:100, modal:true});
	contentWin.setHTMLContent(content);
	contentWin.showCenter();
}

function setItemProperties(){
	var mitem=document.getElementById("newMenuItem");
	if(mitem){
		var a=mitem;
		a.innerHTML="<span>"+document.getElementById("menuText").value+"</span>";
		var uarl=document.getElementById("menuUrl").value;
		if(uarl==""){
			uarl="javascript:void(0);";
		}
		a.setAttribute('_href', uarl);
		mitem.id="";
	}
}

function cancelnewItem(){
	jQuery('#newMenuItem').parent().remove();
}

function deleteMenuItem(obj, ulId){
	var li=getSelectedLi(ulId);
	if(!li){
		return;
	}
	//var ok = confirm("Delete this menuItem?");
	var ok = confirm(getMessage(2));
	if (ok == false) {
		return;
	}
	jQuery(li).remove();
}

function moveItem(obj, ulId, orient){
	var li=getSelectedLi(ulId);
	if(!li){
		return;
	}
	if(orient=="up"){
		var prev=jQuery(li).prev();
		if(prev.attr('id')!="actionLi"){
			prev.before(li);
		}
	}else{
		var next=jQuery(li).next().after(li);
	}
}

function editMenuItem(obj, ulId){
	var li=getSelectedLi(ulId);
	if(!li){
		return;
	}
	var win=Windows.getWindow('newMenuDialog');
	if(win){
		return;
	}
	var a=li.childNodes[0];
	a.id="newMenuItem";
	var content = "<div><form><table width='100%'><tr><td width='10%'>"+getMessage(5)+"</td><td><input id='menuText' type='text' value='"+a.childNodes[0].innerHTML+"'/></td></tr><tr><td width='10%'>"+getMessage(6)+"</td><td><input id='menuUrl' type='text' style='width:350px' value='"+a.getAttribute('_href')+"'/></td></tr>"+
				"<tr><td></td><td align='right'><input type='button' value='"+getMessage(4)+"' onclick='setItemProperties(); Windows.getWindow(\"newMenuDialog\").close();' class='stylishBut'/>&nbsp;<input type='button' value='"+getMessage(3)+"' onclick='document.getElementById(\"newMenuItem\").id=\"\"; Windows.getWindow(\"newMenuDialog\").close();' class='stylishBut'/></td></tr></table></form></div>";
	var contentWin=new Window({id: "newMenuDialog", className: 'alphacube', title: getMessage(7), hideEffect:Element.hide, showEffect:Element.show, minimizable:false,maximizable:false, resizable:true, wiredDrag: true, destroyOnClose: true, width:450, height:100, modal:true});
	contentWin.setHTMLContent(content);
	contentWin.showCenter();
}

function saveMenu(obj, ulId, recId, s){
	var ul=document.getElementById(ulId);
	if(ul.getAttribute('edit')=="on"){
		editMenu(jQuery(obj).prev(), ulId);
	}
	var lis=jQuery('#'+ulId+" li");
	var length=lis.length;
	var menuData="";
	var start="true";
	var elements=new Array()
	var index=0;
	for(var i=1; i<length; i++){
		var iindex=0;
		if(jQuery(lis[i]).hasClass('level1')){
			var tmpArray=new Array();
			var a=lis[i].childNodes[0];
			var oncl=a.getAttribute('onclick');
			//var oncl=jQuery(a).attr('onclick');
			var m="";
			if(oncl){
				oncl=oncl+"";
				if(oncl.indexOf("function onclick()")!=-1){
					oncl=oncl.substring(oncl.indexOf("{")+1, oncl.lastIndexOf("}"));
				}
				m=a.childNodes[0].innerHTML+" click="+oncl;
			}else{
				var hr=a.href;
				m=a.childNodes[0].innerHTML+" link="+hr;
			}
			tmpArray[iindex]=m;
			iindex+=1;
			for(var j=i+1; j<length; j++){
				if(jQuery(lis[j]).hasClass('level1')){
					break;
				}
				var a=lis[j].childNodes[0];
				oncl=a.getAttribute('onclick');
				//oncl=jQuery(a).attr('onclick');
				var m="";
				if(oncl){
					oncl=oncl+"";
					if(oncl.indexOf("function onclick()")!=-1){
						oncl=oncl.substring(oncl.indexOf("{")+1, oncl.lastIndexOf("}"));
					}
					m=a.childNodes[0].innerHTML+" click="+oncl;
				}else{
					var hr=a.href;
					m=a.childNodes[0].innerHTML+" link="+hr;
				}
				tmpArray[iindex]=m;
				iindex+=1;
			}
			elements[index]=tmpArray;
			index+=1;
		}
	}
	for(var i=0; i<elements.length; i++){
		menuData+="{";
		for(var j=0; j<elements[i].length; j++){
			menuData+=elements[i][j];
			if(j!=elements[i].length-1){
				menuData+=",";
			}
		}
		menuData+="}";
	}
	//alert(menuData);
	quickSave(recId, menuData, s);
}

function fixForm(formId, index, width){
	var form=document.getElementById(formId);
	var jqform=jQuery('#'+formId);
	/*if(!form){
		return;
	}*/
	if(width==-1){
		var par=jqform.parent();
		do{
			par=par.parent();
		}while(par.get(0).tagName.toLowerCase()!="td" && (par.attr('id') && par.attr('id').indexOf('m')!=0));
		width=par.width();
	}else if(width==-2){
		width=EDIT_DIALOG_WIDTH;
	}
	var ftable;
	var number=parseInt(index);
	if(isNaN(number)){
		ftable=jQuery('#'+index+' .diaTable');
	}else{
		if(number==-1){
			ftable=jqform.find('.diaTable');
		}else{
			ftable=jqform.find('.diaTable:eq('+number+')');
		}
	}
	width=width-15;
	for(var i=0; i<ftable.length; i++){
		var trows=ftable[i].tBodies[0].rows;
		for(var r=0; r<trows.length; r++){
			var rwidth=0;
			var tcells=trows[r].cells;
			var widths=new Array();
			var inputs=new Array();
			var ind=0;
			for(var c=0; c<tcells.length; c++){
				var inp=jQuery(tcells[c]).find('input');
				var lab=jQuery(tcells[c]).find('label');
				var img=jQuery(tcells[c]).find('img');
				if(inp.length>0){
					if (jQuery(inp[0]).width()>=jQuery(tcells[c]).width()){
						widths[ind]=jQuery(inp[0]).width();
						inputs[ind]=inp[0];
						ind++;
						rwidth+=jQuery(inp[0]).width();
					}else{
						widths[ind]=jQuery(inp[0]).width();
						inputs[ind]=inp[0];
						ind++;
						rwidth+=jQuery(tcells[c]).width()
					}
				}
				if(lab.length>0){
					rwidth+=jQuery(tcells[c]).width();
				}
			}
			sortTables(widths,inputs);
			if(jqform.width()-20<rwidth){
				var substracted=0;var temp=0;
				for(var c=inputs.length-1; c>=0; c--){
					temp=0;
					var inp=inputs[c];
					if (inp.getAttribute('size')>50){
						temp = jQuery(inp).width();
						inp.setAttribute('size', "50");
						substracted+=parseInt(temp - jQuery(inp).width());
					}
					rwidthtemp = parseInt(rwidth - substracted);
					if(width-20	>=rwidthtemp)
						break;
				}
			}
		}
	}
	//form.setAttribute('fixed', 'true');???
}

function sortTables(table1,table2){
	
	for (var i = table1.length - 1; i >= 0;  i--) {
		for (var j = 0; j <= i; j++) {
			if (table1[j+1] < table1[j]) {
				var tempValue = table1[j];
				table1[j] = table1[j+1];
				table1[j+1] = tempValue;
				
				tempValue = table2[j];
				table2[j] = table2[j+1];
				table2[j+1] = tempValue;
			 }
		}
	}
}

var tgList="";
var exList="";

function closeLookupDivs(idd, type){
	//jQuery("div .dropDownList[class='dropDownList'][id!='"+idd+"']").remove();
	//jQuery("div .dropDownList[class~='static'][id!='"+idd+"']").css('display','none');
	var l1=document.getElementById(tgList);
	var l2=document.getElementById(exList);
	if(l1){
		jQuery(l1).remove();
	}
	if(l2){
		jQuery(l2).css('display', 'none');
	}
	//f_tcalHideAll();
	if(type==1){
		tgList=idd;
		exList="";
	}else if(type==2){
		exList=idd;
		tgList="";
	}
}

//tries to keep your session alive
function keepAlive(){
    //and while you are at it, you can just as well do something of use!
    updateUnreadMessages();
    //and if we are looking outlook, update it as well
   if( document.getElementById('unit').value == 'Outlook') updateOutlookCounters();
}

function errorState(){
	alert(getMessage(44));
}

//Get the outlook "new" counters, and place them where the user can see them!
function updateOutlookCounters(what) {
//what  -   which counters to get. Prices are events, cases, topics (for the new comments), totals (gets the new # of events, cases etc), all (brings back everything)
    
    if(!what) what = 'all';
    var actor=document.getElementById('thisActorCode').value;
	var strParams="actor="+actor+"&component=PlatonAction&unit=Main&action=updateCounters&what="+what;
	jQuery.ajax({  
        type:"POST",
		url:"?main",
        data: strParams,  
    	dataType: "xml",
        success: function(xml){ onUpdateOutlookCounters(xml) }     
    });    
}
//Update the screen, based on the counters you got as a response.
function onUpdateOutlookCounters(xml){
	$xml = jQuery(xml);
		
	//---Whatever has an ID must be a record---
    var content = jQuery('#outlook_link_casesComments_NA').html();   //get the old content    
	if( $xml.find("cases").length > 0 ){                             //if we have new information about it, update it. Else leave it to what it was.
	    content = "";
	    $xml.find("case").each(function(){
            var id = jQuery(this).attr('id');   
            var num = parseInt( jQuery(this).text() );
            jQuery('#'+id+'_unreadCounter_NA').html( num>0 ? '&nbsp;('+num+')': ""  ) ;  
            if(num>0 ) content = "*";
        });
    }
    jQuery('#outlook_link_casesComments_NA').html( content );     
    
    var content = jQuery('#outlook_link_eventsComments_NA').html();
	if( $xml.find("events").length > 0 ){
    	content = "";
	    $xml.find("event").each(function(){
            var id = jQuery(this).attr('id');   
            var num = parseInt( jQuery(this).text() );
            jQuery('#'+id+'_unreadCounter_NA').html( num>0 ? '&nbsp;('+num+')': ""  ) ;  
            if(num>0 ) content = "*";
        });
    }
    jQuery('#outlook_link_eventsComments_NA').html( content );     
    
    var content = jQuery('#outlook_link_topicsComments_NA').html();
    if( $xml.find("topics").length > 0 ){
        content = "";
        $xml.find("topic").each(function(){
            var id = jQuery(this).attr('id');   
            var num = parseInt( jQuery(this).text() );
            jQuery('#'+id+'_unreadCounter_NA').html( num>0 ? '&nbsp;('+num+')': ""  ) ;  
            if(num>0 ) content = "*";
        });
    }
    jQuery('#outlook_link_topicsComments_NA').html( content );     
    
    //----UPDATE TOTALS -----
    content = jQuery('#outlook_link_cases_NA').html();   //get the old content    
    if( $xml.find("newCases").length > 0 ){                 //and if we have new cases update, show that as well
        num = parseInt( $xml.find("newCases").text() );
        content = num>0 ? '&nbsp;('+num+') ': "" ;       
    }
    jQuery('#outlook_link_cases_NA').html( content );       
    
    content = jQuery('#outlook_link_events_NA').html();   
    if( $xml.find("newEvents").length > 0 ){                 
        num = parseInt( $xml.find("newEvents").text() );
        content = num>0 ? '&nbsp;('+num+') ': "" ;
    }
    jQuery('#outlook_link_events_NA').html( content );     
    
    content = jQuery('#outlook_link_topics_NA').html();   
    if( $xml.find("newTopics").length > 0 ){    
        num = parseInt( $xml.find("newTopics").text() );
        content = num>0 ? '&nbsp;('+num+') ': "" ;
    }
    jQuery('#outlook_link_topics_NA').html( content ); 
    
    content = jQuery('#outlook_link_messages_NA').html();   
    if( $xml.find("newMessages").length > 0 ){    
        num = parseInt( $xml.find("newMessages").text() );
        content = num>0 ? '&nbsp;('+num+') ': "" ;
    }
    jQuery('#outlook_link_messages_NA').html( content );     
       
}
//Get the number of unread messages, and show them by the main menu link
function updateUnreadMessages(){
    var actor=document.getElementById('thisActorCode').value;
	var unit=document.getElementById('unit').value;
	var strParams="actor="+actor+"&unit="+unit+"&action=countUnreadMessages";
	new  net.ContentLoader("main",onUpdateUnreadMessages,errorState,"POST",strParams);    
}
function onUpdateUnreadMessages(){
    var doc=this.req.responseXML;
    if(doc)	content = doc.getElementsByTagName("content");
    else    errorState();
    
	if(content.length > 0) unread = content[0].firstChild.nodeValue;
	else        return;	
    
    var prevCounter = mb.getCounter('Messenger');
    mb.updateCounter('Messenger',unread);      
    if (prevCounter < unread && winHasFocus == false ) document.title = t('New Emails');
}
/*function IESettingsWindow() {
	var contentWin = new Window({id: "IESettingsWindow", className: 'alphacube', title: getMessage(40), hideEffect:Element.hide, showEffect:Element.show, minimizable:false, maximizable:false, resizable:true, wiredDrag: true, destroyOnClose: true, width:400, height:300, modal:true});
	contentWin.setHTMLContent(getMessage(39));
	contentWin.showCenter();
}*/

			/******************************
					List functions
			*******************************/

function setListValue(inpId, val, code, remove){
	var inp=document.getElementById(inpId);
	inp.value=val;
	inp.setAttribute('value', norm(inp.value));
	inp.setAttribute('code', code);
	if(remove=="true"){
		jQuery('#'+jQid(inpId)+'_ddList').remove();
	}else{
		jQuery('#'+jQid(inpId)+'_ddList').css('display', 'none');
	}
	var validate=inp.getAttribute('validate');
	if(validate!=null && validate!=""){
		validateFieldId(inpId, validate);
	}else{
		//checkDflt(inp, true); //not used pros to paron
		jQuery(inp).trigger("valueChangedEvent");
	}
}

function removeList(inpId){
	if(document.getElementById(inpId).getAttribute('state')=='1'){
		jQuery('#'+jQid(inpId)+'_ddList').remove();
	}
}

function setUnread(){
	var jq = jQuery("#"+lastTable+" .isSelected");
	var rids="";
	for(var i=0;i<jq.length;i++){
		rids+=jQuery(jq[i]).attr('recordid')+",";
		if (!jQuery(jq[i]).hasClass('notread')){
			jQuery(jq[i]).addClass("notread");
		}
	}
	setActionMessage(rids, 'PlatonAction','UNREAD');
}
function setRead(){
	var jq = jQuery("#"+lastTable+" .isSelected");
	var rids="";
	for(var i=0;i<jq.length;i++){
		rids+=jQuery(jq[i]).attr('recordid')+",";
		if (jQuery(jq[i]).hasClass('notread')){
			jQuery(jq[i]).removeClass("notread");
		}
	}
	setActionMessage(rids	, 'PlatonAction','SETREADCOMPLETE');
}
function displayList(lastTable){
	var str='<div style="display:none" class="dropDownList static" id="message_more_list">'
	str+='<table width="100%"><tbody>'+
			 '<tr onmouseout="deselect(\'offspan\', this);" onmouseover="selectItem(\'onspan\', this);" selected="false" onclick="setRead()" class="offspan"><td value="0"><span>'+getMessage("Mark as Read")+'</span></td></tr>'+
			 '<tr onmouseout="deselect(\'offspan\', this);" onmouseover="selectItem(\'onspan\', this);" selected="false" onclick="setUnread()" class="offspan"><td value="1"><span>'+getMessage("Mark as Unread")+'</span></td></tr>'+
			 '<tr onmouseout="deselect(\'offspan\', this);" onmouseover="selectItem(\'onspan\', this);" selected="false" onclick="generalJunk(lastTable)" class="offspan"><td value="1"><span>'+getMessage("Move to Spam")+'</span></td></tr>'+
			 '<tr onmouseout="deselect(\'offspan\', this);" onmouseover="selectItem(\'onspan\', this);" selected="false" onclick="generalInbox(lastTable)" class="offspan"><td value="1"><span>'+getMessage("Move to Inbox")+'</span></td></tr>'+
			 '<tr onmouseout="deselect(\'offspan\', this);" onmouseover="selectItem(\'onspan\', this);" selected="false" onclick="archive(lastTable)" class="offspan"><td value="1"><span>'+getMessage("Archive")+'</span></td></tr>'+
			 '<tr onmouseout="deselect(\'offspan\', this);" onmouseover="selectItem(\'onspan\', this);" selected="false" onclick="restoreMessage(lastTable)" class="offspan"><td value="1"><span>'+getMessage("Restore")+'</span></td></tr>'+
			 '<tr onmouseout="deselect(\'offspan\', this);" onmouseover="selectItem(\'onspan\', this);" selected="false" onclick="delMessage(lastTable)" class="offspan"><td value="1"><span>'+getMessage("Delete")+'</span></td></tr>'+
			 '</table></div>'
	jQuery("#"+lastTable+'_MORE').append(str);
	toggleList(lastTable+'_MORE','message_more_list');
}
function toggleList(inpId, listId){
	var list=jQuery('#'+jQid(listId));
	if(list.css('display')!='none'){
	    closeList(listId,inpId);
		return;
	}
	closeLookupDivs(jQid(listId), 2);
	var jq=jQuery('#'+jQid(inpId));
	if(jq.prop('disabled')){
		return;
	}
	var offset = jq.offset();
	var pos = jq.position();
	var extratop=6; //for paddings etc...
	var topOffset=jq.offsetParent().scrollTop();
	if(browserName.search("Internet Explorer")!=-1){
		if(jq.hasClass('prdInput')){
			list.css('left', pos.left);
			jQuery(list).css('top', pos.top+jq.height()+extratop);
		}else if(list.hasClass('static')){
			list.css('left', pos.left);
			jQuery(list).css('top', pos.top+jq.height()+extratop);
		}else{
			list.css('left', pos.left);
			jQuery(list).css('top', pos.top+jq.height()+extratop+2);
		}
	}else{
		list.css('left', pos.left);
		list.css('top', topOffset+pos.top+jq.height()+extratop);
	}
	list.css('width', jq.width()+18);
	list.css('z-index','10');
	list.css('display','block');
	//bind a clickoutside event
	setTimeout('jQuery(\'#'+jQid(inpId)+'\').bind( \'clickoutside\', function(){ closeList(\''+listId+'\',\''+inpId+'\'); } );',250); 
	/*jq.focus();*/
}

var listTable;
var position=-1;
var overlist;
//prepei na iparxei to google jsapi
//empeine apo tin weblibrary. Tha mpei apo ta properties
//google.load('visualization', '1', {packages:['orgchart']});
    
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('string', 'Manager');
        data.addColumn('string', 'ToolTip');
        data.addRows([
        [{v:'Department', f:'Department<div style="color:red; font-style:italic">Finance</div>'}, '', 'Finance'],
          [{v:'Spyros Skolarikis', f:'Spyros Skolarikis<div style="color:red; font-style:italic">Department leader</div>'}, 'Department', 'Department leader'],
          [{v:'Christos Lazaridis', f:'Christos Lazaridis<div style="color:red; font-style:italic">Organiser</div>'}, 'Spyros Skolarikis', 'VP'],
          ['Christos Tsamsakizoglou', 'Christos Lazaridis', ''],
          ['Andreas Lianos', 'Christos Lazaridis', 'Andreas Lianos'],
          ['George Fylaktopoulos', 'Christos Lazaridis', 'George Fylaktopoulos'],

          [{v:'Department1', f:'Department<div style="color:red; font-style:italic">Development</div>'}, '', 'Development'],
           [{v:'Spyros Rigas', f:'Spyros Rigas<div style="color:red; font-style:italic">Department leader</div>'}, 'Department1', 'Department leader'],
          [{v:'Spyros Skolarikis1', f:'Spyros Skolarikis<div style="color:red; font-style:italic">Organiser</div>'}, 'Spyros Rigas', 'VP'],
          ['Christos Tsamsakizoglou', 'Christos Lazaridis', ''],
          ['Andreas Lianos', 'Christos Lazaridis', 'Andreas Lianos'],
          ['George Fylaktopoulos', 'Christos Lazaridis', 'George Fylaktopoulos'],
          
          [{v:'Department2', f:'Department<div style="color:red; font-style:italic">Marketing & Sales</div>'}, '', 'Marketing & Sales'],
          [{v:'Othon Michalas', f:'Othon Michalas<div style="color:red; font-style:italic">Department leader</div>'}, 'Department2', 'Department leader'],
          [{v:'Alexia Avronidaki', f:'Alexia Avronidaki<div style="color:red; font-style:italic">Organiser</div>'}, 'Othon Michalas', 'VP'],
          ['Christos Tsamsakizoglou', 'Alexia Avronidaki', 'CS'],
          ['Andreas Lianos', 'Christos Tsamsakizoglou', 'Andreas Lianos'],
          ['1', 'Andreas Lianos', '1'],
          ['2', 'Andreas Lianos', '2'],
          ['3', 'Andreas Lianos', '3'],
          ['4', '3', '4'],
          ['5', '3', '5']
        ]);
        var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
        data.setRowProperty(0, 'style', 'cursor:pointer;border: 1px solid green');
        data.setRowProperty(6, 'style', 'cursor:pointer;border: 1px solid green');
        data.setRowProperty(12, 'style', 'cursor:pointer;border: 1px solid green');
        
        chart.draw(data, {allowHtml:true,allowCollapse:true,size:'large'});
        
      }
function listFunctions(listId){
	listTable=null;
	overlist=null;
	position=-1;
	var ltables=jQuery('#'+listId+' table');
	if(ltables.length>0){
		listTable=ltables[0];
	}
	jQuery('#'+listId).unbind('mouseover').bind('mouseover', function(event){overlist=true});
	jQuery('#'+listId).unbind('mouseout').bind('mouseout', function(event){overlist=false});
	jQuery(document).unbind('keydown').bind('keydown', function(event){checkListKey(listId, event);});
	jQuery(document).unbind('mousedown').bind('mousedown', function(){if(!overlist){closeList(listId);}});
}

function checkListKey(list, e){
	if (!e) var e = window.event;
	var scrll=jQuery('#'+list);
	if(!scrll.hasClass('inlst')){
		scrll=jQuery(scrll.children()[0]);
	}
	if(e.keyCode==40){//down arrow
		if(position<listTable.rows.length-1){
			jQuery(listTable.rows[position+1]).mouseover();
			scrll.scrollTop(scrll.scrollTop()+jQuery(listTable.rows[position+1]).position().top);
			if(position>=0){
				jQuery(listTable.rows[position]).mouseout();
			}
			position++;
		}
		
		if (e.preventDefault){
			e.preventDefault();
		}else{
			e.returnValue = false;
		}
	}else if(e.keyCode==38){//up arrow
		if(position>=1){
			jQuery(listTable.rows[position-1]).mouseover();
			scrll.scrollTop(scrll.scrollTop()+jQuery(listTable.rows[position-1]).position().top);
			jQuery(listTable.rows[position]).mouseout();
			position--;
		}
		if (e.preventDefault){
			e.preventDefault();
		}else{
			e.returnValue = false;
		}
	}else if(e.keyCode==13){//enter key
		if(position>=0){
			jQuery(document).unbind('keydown').unbind('mousedown');
			jQuery(listTable.rows[position]).mouseout();
			jQuery(listTable.rows[position]).click();
			stopEvents(e);
			jQuery('#'+list.replace(/_ddList/,'')).focus();
			closeList(list);
		}
	}else if(e.keyCode==37){//left arrow
		if(position>=0 && position<listTable.rows.length){
			var jq=jQuery(listTable.rows[position]);
			var parent=jQuery('#'+jq.attr('parentId'));
			if(parent.attr('hasSub')=='true'){
				if(jq.attr('level')!=0){
					position=parent.get(0).sectionRowIndex;
					jQuery(listTable.rows[position]).mouseover();
					scrll.scrollTop(scrll.scrollTop()+jQuery(listTable.rows[position]).position().top);
				}
				var tc=parent.find('img')[0];
				jQuery(tc).click();
				stopEvents(e);
			}
		}
	}else if(e.keyCode== 39){//right arrow
		if(position>=0 && position<listTable.rows.length){
			var jq=jQuery(listTable.rows[position]);
			if(jq.attr('hasSub')=='true'){
				var tc=jq.find('img')[0];
				jQuery(tc).click();
				stopEvents(e);
			}
		}
	}else if(e.keyCode==27){//escape
		 closeList(list);
		 jQuery('#'+list.replace(/_ddList/,'')).focus();
	}
}

function closeList(list,inpId){
	//if (!e) var e = window.event;
	var lilist=document.getElementById(list);
	if(lilist){
		var jq=jQuery(lilist);
		jq.unbind('mouseover').unbind('mouseout');
		if(inpId) jQuery('#'+jQid(inpId) ).unbind( 'clickoutside');
		if(jq.hasClass('static')){
			jq.css('display','none');
		}else{
			jq.remove();
		}
	}
	jQuery(document).unbind('keydown').unbind('mousedown');
	listTable=null;
	overlist=null;
	position=-1;
}

function swapImage(img_id , img_src){

	jQuery('#'+img_id).attr("src" , img_src);

}

function freeSpace(id){
// THIS FUNCTION HAS UNSOLVED ISSUES. The parent is not found correctly and the calculation of
//the height of the children is wrong (because children can be side-by-side and not on top of eachther)
//Paddings margins etc for children is not taken into concideration either. Generally the whole idea should change
//So I suggest if for a reason you are here, take the time to change things, rather than trying to fix them. 
	var element;
	if(typeof id == "string"){
		element=jQuery('#'+id);
	}else{
		element=id;//jQuery object
	}
	var visible=false;
	if(element.is(':visible')){
		element.css('display', 'none');
		visible=true;
	}
	//find the first parent, that has height defined
	var parent=element.parent();
	var hasHeight=false;
	var i = 0; //make sure we wont get stuck here
    do {
        if( parent.height()>0 || parent.css('height')!='0px' || parent.attr('height') ){
             hasHeight = true;
        }else{
            parent=parent.parent();
		}
        i++;
    } while (!hasHeight && i <= 20)
	if(i > 20 ) return [element.height(),element.width()]; //if you found nothing 20 parents up, give up resizing.
	var height=parent.height();
	if(height < 50) height = 50;
	var innerHeight=0;
	parent.children().each(function(){
		var thisel=jQuery(this);
		if(this!=element.get(0) && thisel.is(':visible')){
			innerHeight+=thisel.outerHeight();
		}
	});
	var ppadtop=parseInt(parent.css('padding-top').replace("px", ""));
	var ppadbot=parseInt(parent.css('padding-bottom').replace("px", ""));
	var elppadtop=parseInt(element.css('padding-top').replace("px", ""));

	var elpadbot=parseInt(element.css('padding-bottom').replace("px", ""));
	var bordtop=parseInt(element.css('borderTopWidth').replace("px", ""));
	if(isNaN(bordtop)){
		bordtop=0;
	}
	var bordbot=parseInt(element.css('borderBottomWidth').replace("px", ""));
	if(isNaN(bordbot)){
		bordbot=0;
	}
	var margtop=parseInt(element.css('marginTop').replace("px", ""));
	if(isNaN(margtop)){
		margtop=0;
	}
	var margbot=parseInt(element.css('marginBottom').replace("px", ""));
	if(isNaN(margbot)){
		margbot=0;
	}
	var heiLeft=height-innerHeight-ppadtop-ppadbot-elppadtop-elpadbot-bordtop-bordbot-margtop-margbot;
	if(visible){
		element.css('display', '');
	}
	//and here is a min height
	if(heiLeft < 80) heiLeft = 80;

	return [heiLeft, parent.width()];
}

//use this function as a template for the inner html of a window
//you can use tabs, main content, and a button area
function windowFormat(tabs, content, buttons, height){
	var str="";
	if(tabs!=""){
		str+="<div class='tabmenu'>"+tabs+"</div><div style='clear:both;'></div>";
	}
	if(content!=""){
		str+="<div class='fwrpNoscrl'";//fwrp
		if(height!=""){
			str+=" style='height: "+height+"' ";
		}
		str+=">"+content+"</div>";
	}
	if(buttons!=""){
		str+="<div class='buttonsArea' style='text-align:right;'>"+buttons+"</div>";
	}
	return str;
}

//allazei to ikonidio view sta tables. apo open close kai antistrofa
function toggleView(obj){
	var img=obj;
	if(obj.nodeName!="IMG"){
		img=jQuery(obj).find('img:first').get(0);
	}
	if(img.getAttribute('openItem')=='false'){
		img.src="DataServlet?unit=Main&image=CLOSEITEM";
		img.setAttribute('openItem', 'true');
	}else{
		img.src="DataServlet?unit=Main&image=OPENITEM";
		img.setAttribute('openItem', 'false');
	}
}




//request the recent actions from the server
function updateRecentActions(){
    var unit = document.getElementById('unit').value;
    var actor = document.getElementById('thisActorCode').value;
    var strParams="actor="+actor+"&component=PlatonAction&unit="+unit+"&action=getRecentActions";
	jQuery.ajax({  
		url:"?main",
        type:"POST",
        data: strParams,  
    	dataType: "xml",
        success: function(xml){ onUpdateRecentActions(xml) }     
    });    
}
//Update the recent actions div with the new actions.
function onUpdateRecentActions(xml){
	$xml = jQuery(xml);
    jQuery('#recentInner').html($xml.find("content").text() );
}





/*****************************READY.JS*********************/
jQuery(document).ready(function(){
    
    //create the global messageviewer object
    mv = new messageViewer();	   
    
	if(document.getElementById("linksContent") != null){
		clearAll();
	}
	if(document.getElementById('unit')){
		window.name=document.getElementById('unit').value;
	}
	if(document.getElementById("device") && document.getElementById("device").value=="pc"){
		device="pc";
	}else if(document.getElementById("device") && document.getElementById("device").value=="mobile"){
		device="mobile";
	}
	if ((screen.width==1024) && (screen.height==768)){
		DEFAULT_WIDTH = 650;
		DEFAULT_HEIGHT = 450;
		var style="<style type='text/css'>"+
					"table tr td {font: normal 11px Tahoma;}"+
					".actionLink{font-size:11px;}"+
					"</style>";
		jQuery('head').append(style);
	}else if ((screen.width==800) && (screen.height==600)){
		DEFAULT_WIDTH = 550;
		DEFAULT_HEIGHT = 350;
		var style="<style type='text/css'>"+
					"table tr td {font: normal 10px Tahoma;}"+
					".actionLink{font-size:10px;}"+
					"</style>";
		jQuery('head').append(style);
	}else if ((screen.width<800) || (screen.height<600)){
		var style="<style type='text/css'>"+
					"table tr td {font: normal 10px Tahoma;}"+
					".actionLink{font-size:9px;}"+
					".unitsMenu li {padding:5px 3px;}"+
					"</style>";
		jQuery('head').append(style);
		DEFAULT_WIDTH = 550;
		DEFAULT_HEIGHT = 350;
	}
	if (document.getElementById("units")){
		//fixMenu('units');
		var as = jQuery("#scrollMenu").find("a");
		for (var i=0;i<as.length;i++){
			var jq=jQuery(as[i]);
			jq.css('width', jq.innerWidth());
		}
		if(device=="pc"){
			jQuery("#scrollMenu").smoothDivScroll({startAtElementId: "selectedMenuItem", scrollStep: 1, scrollInterval: 5, visibleHotSpots: "always"});
		}else if(device=="mobile"){
			jQuery("#scrollMenu").smoothDivScroll({startAtElementId: "selectedMenuItem", scrollStep: 20, scrollInterval: 5, visibleHotSpots: "always"});
		}
	}
	//if defined, open default unit from left menu
	if(window.openDefaultUnit){
		openDefaultUnit();//mainslider.js
	}
	if(document.getElementById('user') && document.getElementById('user').value!="anonymous"){
		setInterval("keepAlive()", 120000);
	}
	var imgs = jQuery("#m103").find("img[alttext='image']");
	if (document.getElementById('m103')==null)
		return;
	var parw = document.getElementById("m103").scrollWidth;//jQuery("#m103").css('width');
	for (var i=0;i<imgs.length;i++){
		var tw = jQuery(imgs[i]).css('width');
		//if (parseInt(tw) >= (parseInt(parw)-2)){
			jQuery(imgs[i]).css('width',(parseInt(parw)-3))
			//alert('inside');
		// }
	}
});
/****************************************/


/******************WINFUNCT.JS*********************/
var EDIT_DIALOG_WIDTH = 600;
var EDIT_DIALOG_HEIGHT = 500;
var DEFAULT_WIDTH = 720;
var DEFAULT_HEIGHT = 560;

if(typeof(Windows) !== 'undefined') {
	Object.extend(Windows, {
	  // Overide minimize function
	  close: function(id, event) {
		var win = this.getWindow(id)
		if (win && win.visible) {
			if(window.f_tcalHideAll){
				f_tcalHideAll();
			}
			if(id=="main_message_div_Window"){
				if(isNull_Message()){ //apo sendSMSServlet
					//des kai tin openMessWindow exei ekei win.destroy
					destroyEditor();
					win.destroy();
				}else{
					confirmClose(id);
				}
			}else{
				win.hide();
			}
		}
	  }
	});
}

function addWindow(id, wintitle){
	var contentWin=Windows.getWindow(id+"_Window");
	if (contentWin) {
		//contentWin.show();
		return;
	} else {
		//contentWin = new Window({maximizable: false, resizable: false, hideEffect:Element.hide, showEffect:Element.show, minWidth: 10, destroyOnClose: true});
		//contentWin=new Window({id: id+"_Window", className: 'alphacube', title: wintitle, hideEffect:Element.hide, minimizable:false,maximizable:false,showEffect:Element.show, wiredDrag: true, top:50, left:150, width:850, height:620, minWidth:850});
		contentWin=new Window({id: id+"_Window", className: 'windowStyle', title: wintitle, hideEffect:Element.hide, minimizable:false,maximizable:false,showEffect:Element.show, wiredDrag: true, recenterAuto:false, top:50, left:150, width:DEFAULT_WIDTH, height:DEFAULT_HEIGHT, minWidth:250});
		contentWin.setContent(id, false, false);
		/*myObserver = {
			onClose: function(eventName, win) {
				if (win == contentWin) {
					//contentWin = null;
					Windows.removeObserver(this);
				}
			}
			onDestroy: function(eventName, win) {
				if (win == contentWin) {
					//$(id+'_container').appendChild($(id));
					contentWin = null;
					Windows.removeObserver(this);
				}
				//debug(eventName + " on " + win.getId()) 
			}
		}*/
		//Windows.addObserver(myObserver);
	}
}

function confirmClose(aid){
	var win=Windows.getWindow("messageConfirm");
	if(win){
		return;
	}
	var confwin=new Window({id: "messageConfirm",className: 'windowStyle',title:getMessage(16),minimizable:false,maximizable:false,closable:false, resizable:false, recenterAuto:false, destroyOnClose: true,width:380,height:80});
	var contents="<div><br/><div style='text-align:center;'>"+getMessage(17)+"</div>"+
		"<div class='winBLink'>"+
		"<table width='100%'><tr><td align='center'>"+
		" <input type='button' value='"+getMessage(18)+"' class='stylishBut' onclick=\"if(!validateForSave()){Windows.getWindow('messageConfirm').destroy(); return false;} sbmtFRMSave('smsForm'); Windows.getWindow('messageConfirm').destroy(); destroyEditor(); Windows.getWindow('"+aid+"').destroy();\" />"+
		" <input type='button' value='"+getMessage(19)+"' class='stylishBut' onclick=\"Windows.getWindow('messageConfirm').destroy(); destroyEditor(); Windows.getWindow('"+aid+"').destroy();\" />"+
		" <input type='button' value='"+getMessage(3)+"' class='stylishBut' onclick=\"Windows.getWindow('messageConfirm').destroy();\" />"+
		"</td></tr></table></div></div>";
	confwin.setHTMLContent(contents);
	confwin.showCenter();
}

function addWindowWithProperties(id, wintitle,width,height,minim,maxim){
	var contentWin=Windows.getWindow(id+"_Window");
	if (contentWin) {
		//contentWin.show();
		return null;
	} else { 
		//contentWin = new Window({maximizable: false, resizable: false, hideEffect:Element.hide, showEffect:Element.show, minWidth: 10, destroyOnClose: true});
		contentWin=new Window({id: id+"_Window", className: 'windowStyle', title: wintitle, hideEffect:Element.hide, minimizable:minim,maximizable:maxim,showEffect:Element.show, recenterAuto:false, resizable:false, wiredDrag: true, destroyOnClose: true, top:50, left:150, width:width, height:height, modal:true});
		contentWin.setContent(id, false, false)
		/*myObserver = {
			onDestroy: function(eventName, win) {
				if (win == contentWin) {
					//$(id+'_container').appendChild($(id));
					contentWin = null;
					Windows.removeObserver(this);
				}
			}
		}
		Windows.addObserver(myObserver);*/
	}
	return contentWin;
}

function addWindowWithContent(id, content, wintitle,width,height,minim,maxim){
	var contentWin=Windows.getWindow(id+"_Window");
	if (contentWin) {
		return null;
	} else { 
		contentWin=new Window({id: id+"_Window", className: 'windowStyle', title: wintitle, hideEffect:Element.hide, minimizable:minim,maximizable:maxim,showEffect:Element.show, recenterAuto:false, resizable:false, wiredDrag: true, destroyOnClose: true, top:50, left:150, width:width, height:height, modal:true});
		contentWin.setHTMLContent(content);
	}
	return contentWin;
}

/******************************************/

/*******/
//gia hover. irthe apo to webcalendar.js
function hoveron(obj){
		var jq=jQuery(obj);
		if ( !jq.hasClass('calendarTdOver') && (jq.hasClass('calendarTd')) ){
			jq.addClass('calendarTdOver');
		}
		else if (jq.hasClass('workCalendarTd')){
			jq.addClass('workCalendarTdOver');
			jq.removeClass('workCalendarTd');
		}
		else if (jq.hasClass('tday')){
			jq.addClass('tdayOver');
			jq.removeClass('tday');
		}
		else if (jq.hasClass('RecWidgetClass')){
			jq.addClass('RecWidgetClassOver');
			jq.removeClass('RecWidgetClass');
		}
	}
	
function hoveroff(obj){
	var jq=jQuery(obj);
	if (jq.hasClass('calendarTdOver')){
		jq.removeClass('calendarTdOver');
	}
	else if (jq.hasClass('workCalendarTdOver')){
		jq.removeClass('workCalendarTdOver');
		jq.addClass('workCalendarTd');
	}
	else if (jq.hasClass('tdayOver')){
		jq.removeClass('tdayOver');
		jq.addClass('tday');
	}
	else if (jq.hasClass('RecWidgetClassOver')){
		jq.removeClass('RecWidgetClassOver');
		jq.addClass('RecWidgetClass');
	}
}

function hoverdown(obj){
	var jq=jQuery(obj);
		if (jq.hasClass('RecWidgetClassSelect')){
			jq.removeClass('RecWidgetClassSelect');
			jq.addClass('RecWidgetClassOver');
			jQuery('#b'+(obj.id).substring(1)).css('display','none');
		}
		else if (jq.hasClass('RecWidgetClassOver')){
			jq.removeClass('RecWidgetClassOver');
			jq.addClass('RecWidgetClassSelect');
			jQuery('#b'+(obj.id).substring(1)).css('display','inline');
		}
		else
			if(jq.hasClass('workCalendarTdSelect')){
				jq.removeClass('workCalendarTdSelect');
			}
		else
			jq.addClass('workCalendarTdSelect');
}
function getMiniCalMonth(year,month){
    var unit = document.getElementById('unit').value;
    var actor = document.getElementById('thisActorCode').value;
    var strParams="actor="+actor+"&component=PlatonAction&unit="+unit+"&action=getMiniCalMonth&month="+month+"&year="+year;
	jQuery.ajax({  
        type:"POST",
		url:"?main",
        data: strParams,  
    	dataType: "xml",
        success: function(xml){ ongetMiniCalMonth(xml) }     
    });    
}

//Update the screen, based on the counters you got as a response.
function ongetMiniCalMonth(xml){
	$xml = jQuery(xml);
    jQuery('#calendarInner').html($xml.find("content").text() );
    jQuery('#miniCalButton').html($xml.find("header").text() );
}
function fillInfoDialog(id, title/*, showhelp*/){
	jQuery(document).ready(function(){
		var content=document.getElementById(id+"_wrapper");
		var contentWin=new Window({id: id+'_dialog_Window', className: 'windowStyle', title: title, hideEffect:Element.hide, showEffect:Element.show, minimizable:false,maximizable:false, resizable:false, recenterAuto:false, closable:false, wiredDrag: false, width:560, height:380, modal:true, top:50, left:150});
		contentWin.setHTMLContent(content.innerHTML);
		document.getElementById(id+'_form').reset();
		var myObserver = {
			onClose : function(eventName, win1) {
				if (win1 == contentWin) {
					contentWin.destroy();
					Windows.removeObserver(this);
					/*if(showhelp!="false"){
						openHelp();
					}*/
				}
			}
		}
		Windows.addObserver(myObserver);
		contentWin.showCenter(true);
		jQuery(content).remove();
	});
}
function showfinance(){
	var str = "<table cellpadding=1 cellspacing=4 >"
	str+="<tr><td bgcolor=white>"+getMessage("Συνολο χρέωσης πελατών")+"</td><td bgcolor=white>100&euro;</td></tr>"
	str+="<tr><td bgcolor=white>"+getMessage("Σύνολο πίστωσης πελατών")+"</td><td bgcolor=white>88&euro;</td></tr>"
	str+="<tr><td bgcolor=white>"+getMessage("Συνολο δικαιωμάτων συνεργάτη")+"</td><td bgcolor=white>200&euro;</td></tr>"
	str+="<tr><td bgcolor=white>"+getMessage("Εκτελεσμένη πληρωμή σε συνεργάτη")+"</td><td bgcolor=white>43&euro;</td></tr>"
	str+="<tr><td bgcolor=white>"+getMessage("Υπόλοιπο προς πληρωμή")+"</td><td bgcolor=white>20&euro;</td></tr>"
	str += "</table>"
	alert(str)
}
//Enables and disables input fields based on a checkbox
function toggleFields(checkbox, fieldsContainerClass, rev){
//checkbox          -   expects DOM element i.e. this
//fieldsContainerClass -   The class of something containing all the fields, a span should do. 
//rev               -   Do the reverse thing, enable them when the box is checked . Boolean
    
    $inputs = jQuery("."+fieldsContainerClass+" :input");
    if ( jQuery(checkbox).is(':checked')) {
        if(rev)            $inputs.removeAttr('disabled'); 
        else               $inputs.attr('disabled', true); 
    }
    else { 
        if(rev)            $inputs.attr('disabled', true); 
        else               $inputs.removeAttr('disabled');
    }
}
function saveSettingsMin(){
var xmlString = "<?xml version='1.0' encoding='UTF-8'?>"+
				"<elements>"+
				"<actor>"+document.getElementById('thisActorCode').value+"</actor>"+
				"<unit>"+document.getElementById('unit').value+"</unit>"+
				"<pageAction>changeSettings</pageAction>"+
				"<action>changeSettings</action>"+
				"<ispartner>true</ispartner>"+
				"</elements>";
				xmlString=xmlString.replace(/&/g,'&amp;');
				var loader1 = new  net.send("main", onSaveSettingsMin,null, "POST",xmlString,"text/xml");
}
function onSaveSettingsMin(){
	var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){
		alert(getMessage("You have successfully become a pertner of Bopen. You can manage your clients from WebOffice left menu, from the 'Partner' selection"));
		//Windows.getWindow('mainChangePasswordDialog').close();
	}else if(status[0].firstChild.nodeValue=='-1'){
		alert(message[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-4'){
		var uarl=doc.getElementsByTagName("url");
		window.location=uarl[0].firstChild.nodeValue;
	}
}

function checkMandatory(field,NA,fieldName){
    $NA = jQuery('#'+NA);    
    field = getRealValue(field);
    if(field.length < 1 ){ $NA.html("<span style='color:red;'>"+fieldName+" "+getMessage("is mandatory")+"</span>");   return false;}
    else                { $NA.html("<span style='color:green;'></span>");  return true;  }
}
//sees that you have provided an oldPass
function checkOldPass(oldPass,NA){
    $oldPass = jQuery('#'+oldPass);
    $NA = jQuery('#'+NA);    
    pass = $oldPass.val();
    if(pass.length < 1 ){ $NA.html("<span style='color:red;'>"+getMessage("You must provide your old password")+"</span>");   return false;}
    else                { $NA.html("<span style='color:green;'></span>");  return true;  }
}
//Does some basic validation on the password!
function checkPass(newPass,NA){
    $newPass = jQuery('#'+newPass);
    $NA = jQuery('#'+NA);    
    pass = $newPass.val();
    if(pass.length < 6 ){ $NA.html("<span style='color:red;'>"+getMessage("Your password is too short")+"</span>");   return false;}
    else                { $NA.html("<span style='color:green;'></span>");  return true;  }
}
//gets the id of the confirmationPass input, the newPassword input, and a Notification Area, and prints an error message if the passwords dont match
function checkConfirmPass(confirmPass,newPass,NA){
    $confirmPass = jQuery('#'+confirmPass);
    $newPass = jQuery('#'+newPass);
    $NA = jQuery('#'+NA);
    if($confirmPass.val() != $newPass.val() ){   $NA.html("<span style='color:red;'>"+getMessage("Your password and password confirmation are different")+"</span>"); return false; }
    else                                     {   $NA.html("<span style='color:green;'></span>"); return true; }
}
//Sees if the thing is a valid email
function checkMail(email,NA){
    var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    $email = jQuery('#'+email);
    $NA = jQuery('#'+NA);      
    if( !emailReg.test($email.val()) ){ $NA.html("<span style='color:red;'>"+getMessage("Please provide with a valid email")+"</span>");   return false;}
    else                          { $NA.html("<span style='color:green;'></span>");  return true;  }
}


/* ===== TOGGLING ===== */
//shows whatever has "classToShow", and hides everything else that has class "classGroup"
function aggressiveShow(classToShow,classGroup){
    jQuery('.'+classGroup).hide();
    jQuery('.'+classToShow).show();
}
//Adds "selected" class to the given link, and removes it from all other links inside the classGroup
function markSelected(item,classGroup){
    jQuery('.'+classGroup).find('a').removeClass('selected');
    jQuery(item).addClass('selected');
}
/***editor functions***/
//open a window with an editor
//area is the id ot the textarea from where it reads the data
function openEditor(area, title){
	var textArea=jQuery('#'+area);
	if(textArea.prop('disabled')){
		return;
	}
	var contentWin=new Window({id: area+'_richTextEditor_Window', className: 'windowStyle', title: title, hideEffect:Element.hide, showEffect:Element.show, minimizable:false,maximizable:false, resizable:false, recenterAuto:false, wiredDrag: true, destroyOnClose: true, width:600, height:500,zIndex:100, modal:true});
	var button="<input type='button' class='stylishBut' value='"+getMessage("Ok")+"' onclick=\"setEditorValue('"+area+"'); Windows.getWindow('"+area+"_richTextEditor_Window').close();\">";
	contentWin.setHTMLContent(windowFormat('', "<div id='"+area+"_editorDiv'></div>", button, '92%'));
	var myObserver = {
		onShow: function(eventName, win) {
			if (win.getId() == area+'_richTextEditor_Window') {
				var offsets=freeSpace(area+'_editorDiv');
				var editor=jQuery('#'+area+'_editorDiv').ckeditor( function() {
					var text=textArea.val();
					if(textArea.attr("textType")=="html"){
						this.setData(text);
					}else{
						this.insertText(text);
					}
				}, {height:offsets[0]-185, width:'100%'});// 185 analoga me ton editor. iparxei mpara i oxi? an nai poses seires koumpion?
			}
		},
		onDestroy : function(eventName, win) {
			if (win.getId() == area+'_richTextEditor_Window') {
				var editor = jQuery('#'+area+"_editorDiv").ckeditorGet();
				editor.destroy();
				Windows.removeObserver(this);
			}
		}
	}
	Windows.addObserver(myObserver);
	contentWin.showCenter(true);
}

function setEditorValue(area){
	var editor = jQuery('#'+area+"_editorDiv").ckeditorGet();
	var data=editor.getData();
	jQuery('#'+area).val(data);
	disableArea(area);
	jQuery('#'+area).attr("textType", "html");
}

function enableArea(id){
	var area=jQuery('#'+id);
	var layer=area.next();
	if(layer && layer.hasClass('areaLayer')){
		layer.next().remove();
		layer.remove();
		area.css('color', '');
	}
}

function disableArea(id){
	var area=jQuery('#'+id);
	area.parent().css('height', area.height()).css('width', '100%').css('overflow', 'hidden');
	var layer=area.next();
	if(layer && layer.hasClass('areaLayer')){ //if it existed, reset and redo
    	layer.next().remove();
		layer.remove();
		area.css('color', '');	
	}
	layer=jQuery("<div class='areaLayer'></div>");
	layer.css('width', '100%').css('height', area.height()).css('opacity', '0.2').css('background-color', 'grey');
	layer.css('position', 'relative').css('top', -1-area.height());//-1 gia to bottom border tou textarea
	//This text is html formatted. You can edit it from the editor
	var buttonlayer=jQuery("<div class='areaLayer'><span style='position:relative; top:40%; text-align:center; display:block;'><div class='stylishBut' style='height:40px;' onclick=\"openEditor('"+id+"', '')\">"+getMessage(112)+"</div></span></div>");
	buttonlayer.css('width', '70%').css('min-width', '290px').css('margin', '0 auto').css('height', area.height()).css('position', 'relative').css('top', -1-(area.height()*2));
	area.css('color', 'grey');
	area.after(buttonlayer).after(layer);
}

//get the value of a textarea with some modifications
//area may be a textarea element or an id
//the result is always in the following form
//<text>memoTetx or <html>memoTetx
function getMemo(area){
	var text="";
	var type="";
	if(typeof area == "string"){
		text=document.getElementById(area).value;
		type=document.getElementById(area).getAttribute("textType");
	}else{
		text=area.value;
		type=area.getAttribute("textType");
	}
	text=text.replace(/\n/g,'@br@');
	if(type=="text"){
		return "[text]"+text;
	}else if(type=="html"){
		return "[html]"+text;
	}
	return text;
}


function convToText(id){
	Dialog.confirm("<div style='padding-top:10px'>"+getMessage(110)+"</div>", {title: getMessage(111), width:300, className: 'windowStyle', okLabel: getMessage(72), cancelLabel:getMessage(73), buttonClass: "stylishBut ", id: "confirmRepeat", cancel:function(win) {
			return true;
		}, ok:function(win) {
			var area=jQuery('#'+id);
			var tmp=jQuery("<div></div>");
			tmp.html(area.val());
			area.val(tmp.text());
			area.attr("textType", "text");
			enableArea(id);
			return true;
		} }); 
}

/***********/
//  search functions  //
var oldVal="";
function getSearchResults(inpId, links, share){
	var val="";
	var unit=document.getElementById('unit').value;
	var actor= document.getElementById('thisActorCode').value;
	var id="search_Window";
	if(links){
		id="link_Window";
	}
	var win=Windows.getWindow(id);
	if(!links){
		var inp=jQuery('#'+inpId);
		val=inp.val();
		if(val==inp.attr('dfltTxt')){
			val="";
		}
		if(oldVal==val){
			if(win){
				if(jQuery('#'+id).is(':hidden')){
					if(win.isMinimized()){
						win.minimize();
					}
					win.showCenter();
				}
				return;
			}
		}
		oldVal=val;
	}else{
		val=jQuery('#'+id+' #'+inpId);
		if(val.length>0){
			val=val.val();
		}else{
			val="";
		}
	}
	var memos=jQuery('#'+id+' #advMemos').prop('checked');
	var files=jQuery('#'+id+' #advFiles').prop('checked');
	val=val.replace(/%/g,'%25');
	var strParams="actor="+actor+"&unit="+unit+"&component=PlatonAction&value="+val+"&share="+share+"&links="+links+"&memos="+memos+"&files="+files;
	if(win){
		strParams+="&action=getResults";
	}else{
		strParams+="&action=searchDialog";
	}
	new net.ContentLoaderThis("main",onGotSearchDialog,null, id, [links, share], "POST",strParams);
}

function onGotSearchDialog(){
	var doc=this.req.responseXML;
	var id=this.obj_reference;
	var links=this.obj_reference2[0];
	var share=this.obj_reference2[1];
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){
		var content=getXmlValue(doc, "content");
		var win=Windows.getWindow(id);
		if(win){
			jQuery('#'+id+' #searchResults').html(content);
			if(jQuery('#'+id).is(':hidden')){
				if(win.isMinimized()){
					win.minimize();
				}
				win.showCenter();
				if(!links){
					jQuery('#dSearchInput').attr('value', jQuery('#gSearchInput').val());
				}
			}else{
				if(!links){
					jQuery('#gSearchInput').attr('value', jQuery('#dSearchInput').val());
					checkDflt(jQuery('#gSearchInput').get(0), true);
				}
				jQuery('#'+id+' #srch_results').colResize({noResize:true});
				jQuery('#'+id+' #srch_results tr:eq(1)').click();
			}
		}else{
			var destroy=false;
			var title=getMessage("Search");
			if(links){
				title=getMessage("Link with");
				destroy=true;
			}
			if(share){
				title=getMessage("Share");
				destroy=true;
			}
			win=new Window({id: id, className: 'windowStyle', title: title, hideEffect:Element.hide, showEffect:Element.show, minimizable:true,maximizable:false, resizable:false, recenterAuto:false, wiredDrag: true, destroyOnClose: destroy, width:DEFAULT_WIDTH+150, height:DEFAULT_HEIGHT,zIndex:100});
			win.setHTMLContent(content);
			var myObserver = {
				onDestroy: function(eventName, win) {
					if (win.getId() == id) {
						Windows.removeObserver(this);				
					}
				},
				onShow: function(eventName, win) {
						if (win.getId() == id) {
							jQuery('#'+id+' #srch_results').colResize({noResize:true});
							jQuery('#'+id+' #srch_results tr:eq(1)').click();
							if(links){
								addLinkedRecs();
							}
					}
				}
			}
			Windows.addObserver(myObserver);
			if(win.isMinimized()){
				win.minimize();
			}
			win.showCenter();
		}
	}else if(status[0].firstChild.nodeValue=='-1'){
		alert(message[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-4'){
		var uarl=doc.getElementsByTagName("url");
		window.location=uarl[0].firstChild.nodeValue;
	}
}

function selectLink(obj, table, id){
	var res2=jQuery('#srchlinks span[recId="'+id+'"][table="'+table+'"]');
	if(res2.length<=0){
		var value=jQuery(obj).parent().parent().find('.srchres').html();
		jQuery('#srchlinks').append("<div class='grpBut stylishBut'><span class='grpMinus link' recId='"+id+"' table='"+table+"' >"+value+"</span><span> <img alt='"+getMessage("Remove")+"' style='vertical-align:top;' src='DataServlet?unit=Main&image=UNLINK' onclick='jQuery(this).parent().parent().remove();'/></span></div>");
	}
}

function addLinkedRecs(){
	for(var i=0; i<mLinkArray.length; i++){
		jQuery('#linkedRecs').append("<div class='grpBut stylishBut'><span class='grpMinus link' recId='"+mLinkArray[i][0]+"' table='"+mLinkArray[i][1]+"' >"+mLinkArray[i][2]+"</span><span></span></div>");
	}
}

var mLinkArray=new Array();
function linkRecord(share){
	var linkXml="", mXml="";
	jQuery('#srchlinks .link').each(function(){
		linkXml+="<link table='"+this.getAttribute('table')+"'>"+this.getAttribute('recId')+"</link>";
	});
	for(var i=0; i<mLinkArray.length; i++){
		mXml+="<link table='"+mLinkArray[i][1]+"'>"+mLinkArray[i][0]+"</link>";
	}
	var xmlString = "<?xml version='1.0' encoding='UTF-8'?>"+
					"<elements>"+
						"<actor>"+document.getElementById('thisActorCode').value+"</actor>"+
						"<unit>"+document.getElementById('unit').value+"</unit>"+
						"<component>PlatonAction</component>"+
						"<action>createLinks</action>"+
						"<dtable>"+linkXml+"</dtable>"+
						"<mtable>"+mXml+"</mtable>"+
						"<share>"+share+"</share>"+
					"</elements>";
	new net.send("main",onlinkRecord,null, "POST",xmlString,"text/xml");
}

function onlinkRecord(){
	var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status")[0].firstChild.nodeValue;
	if(status!="0"){
		var message = doc.getElementsByTagName("message")[0].firstChild.nodeValue;
		alert(message);
	}
}

//closes search window
function minimizeScrh(){
	Windows.getWindow('search_Window').close();
}

function minimizeLnk(){
	Windows.getWindow('link_Window').close();
}

function openSrchCat(obj, categ){
	jQuery('.srchCat').removeClass('categoryColSelected');
	jQuery(obj).addClass('categoryColSelected');
	jQuery('.srchTable').css('display', 'none');
	jQuery('#'+categ+'_results').css('display', '').colResize({noResize:true});
}

//state : update delete insert ....
function getInformDialog(recId, state, rec){
	var unit=document.getElementById('unit').value;
	var actor= document.getElementById('thisActorCode').value;
	var strParams="actor="+actor+"&action=informDialog&unit="+unit+"&component=PlatonAction&recId="+recId+"&state="+state+"&dataComponent="+rec;
	new  net.ContentLoaderThis("main",onGotInformDialog,null,recId, null, "POST",strParams);
}

function onGotInformDialog(){
	var doc=this.req.responseXML;
	var recId=this.obj_reference;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){
		var content=getXmlValue(doc, "content");
		var contentWin=new Window({id: 'inform_Window', className: 'windowStyle', title: getMessage("Inform"), hideEffect:Element.hide, showEffect:Element.show, minimizable:false,maximizable:false, resizable:false, recenterAuto:false, wiredDrag: true, destroyOnClose: true, width:600, height:350,zIndex:100, modal:true});
		contentWin.setHTMLContent(content);
		contentWin.showCenter(true);
	}else if(status[0].firstChild.nodeValue=='-1'){
		alert(message[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-4'){
		var uarl=doc.getElementsByTagName("url");
		window.location=uarl[0].firstChild.nodeValue;
	}
}

function informUsers(recId, table, state){
	var actor=document.getElementById('thisActorCode').value;
	var unit=document.getElementById('unit').value;
	var xmlString="<elements>"+
				"<actor>"+actor+"</actor>"+
				"<unit>"+unit+"</unit>"+
				"<component>PlatonAction</component>"+
				"<action>informUsers</action>"+
				"<state>"+state+"</state>"+
				"<table>"+table+"</table>"+
				"<recId>"+recId+"</recId>"+
				"<mode>"+jQuery('#'+recId+'inform_mode').attr('code')+"</mode>"+
				"<description>"+document.getElementById('informDesc').value+"</description>";
	xmlString+=saveRightsSimple(recId, "inform");
	xmlString+="</elements>";
	new net.send("main",onInform,null,"POST",xmlString,"text/xml");
}

function onInform(){
	var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){
		Windows.getWindow('inform_Window').close();
	}else if(status[0].firstChild.nodeValue=='-1'){
		alert(message[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-4'){
		var uarl=doc.getElementsByTagName("url");
		window.location=uarl[0].firstChild.nodeValue;
	}
}

/****************/
//rights functions & inform
function addGroup(id, mode){
	if(mode){
		var groupList=jQuery('#'+id+'_groupsAllow');
		var code=groupList.attr('code');
		var value=groupList.val();
		var res1=jQuery('#'+id+'_grpListAl .plusList span:contains("'+value+'")');
		var res2=jQuery('#'+id+'_grpListRes .minusList span:contains("'+value+'")');
		if(res2.length<=0){
			if(res1.length<=0){
				jQuery('#'+id+'_grpListAl .plusList').append('<div class="grpBut stylishBut"><span class="grpPlus">'+value+'</span><span> <img alt="'+getMessage("Remove")+'" src="DataServlet?unit=Main&image=REMOVE" width="f14px" onclick="jQuery(this).parent().parent().remove();"/></span></div>');
			}
		}else{
			//iparxei sto -
		}
	}else{
		var groupList=jQuery('#'+id+'_groupsRestrict');
		var code=groupList.attr('code');
		var value=groupList.val();
		var res1=jQuery('#'+id+'_grpListAl .plusList span:contains("'+value+'")');
		var res2=jQuery('#'+id+'_grpListRes .minusList span:contains("'+value+'")');
		if(res1.length<=0){
			if(res2.length<=0){
				jQuery('#'+id+'_grpListRes .minusList').append('<div class="grpBut stylishBut"><span class="grpMinus">'+value+'</span><span> <img alt="'+getMessage("Remove")+'" src="DataServlet?unit=Main&image=REMOVE" width="14px" onclick="jQuery(this).parent().parent().remove();"/></span></div>');
			}
		}else{
			//iparxei sto +
		}
	}
}

function addUser(id, mode){
	if(mode){
		var groupList=jQuery('#'+id+'_usersAllow');
		var code=groupList.attr('code');
		var value=groupList.val();
		var res1=jQuery('#'+id+'_usListAl .plusList span:contains("'+value+'")');
		var res2=jQuery('#'+id+'_usListRes .minusList span:contains("'+value+'")');
		if(res2.length<=0){
			if(res1.length<=0){
				jQuery('#'+id+'_usListAl .plusList').append('<div class="usBut stylishBut"><span class="usPlus" code="'+code+'">'+value+'</span><span> <img alt="'+getMessage("Remove")+'" src="DataServlet?unit=Main&image=REMOVE" width="14px" onclick="jQuery(this).parent().parent().remove();"/></span></div>');
			}
		}else{
			//iparxei sto -
		}
	}else{
		var groupList=jQuery('#'+id+'_usersRestrict');
		var code=groupList.attr('code');
		var value=groupList.val();
		var res1=jQuery('#'+id+'_usListAl .plusList span:contains("'+value+'")');
		var res2=jQuery('#'+id+'_usListRes .minusList span:contains("'+value+'")');
		if(res1.length<=0){
			if(res2.length<=0){
				jQuery('#'+id+'_usListRes .minusList').append('<div class="usBut stylishBut"><span class="usMinus" code="'+code+'">'+value+'</span><span> <img alt="'+getMessage("Remove")+'" src="DataServlet?unit=Main&image=REMOVE" width="14px" onclick="jQuery(this).parent().parent().remove();"/></span></div>');
			}
		}else{
			////iparxei sto +
		}
	}
}

function changeSettingsContact(){
    var doc=this.req.responseXML;
	var status = doc.getElementsByTagName("status");
	var message = doc.getElementsByTagName("message");
	if(status[0].firstChild.nodeValue=='0'){		
		var content=doc.getElementsByTagName("content")[0].firstChild.nodeValue;
		var script=getXmlValue(doc,"script");
		jQuery('#settingsContactForm').html(content);
        eval(script);
		//me to ftiaksimo tou framework tha ftiaxtei kai auto
		jQuery('#settingsContactForm .buttonsArea input:first').remove();
		jQuery('#settingsContactForm .buttonsArea').prepend("<input type='button' class='stylishBut' value='Cancel' onclick='getSettingsContactCardCallback();' />");
	}else if(status[0].firstChild.nodeValue=='-1'){
		alert(message[0].firstChild.nodeValue);
	}else if(status[0].firstChild.nodeValue=='-4'){
		var uarl=doc.getElementsByTagName("url");
		window.location=uarl[0].firstChild.nodeValue;
	}
}
function saveRights(recId, table, dataComp, s, callBack, prefix){
	if(!callBack || callBack==""){
		callBack="onSaveRights";
	}
	var actor=document.getElementById('thisActorCode').value;
	var unit=document.getElementById('unit').value;
	var xmlString="<elements>"+
				"<actor>"+actor+"</actor>"+
				"<unit>"+unit+"</unit>"+
				"<component>"+s+"</component>"+
				"<action>saveRights</action>"+
				"<dataComponent>"+dataComp+"</dataComponent>"+
				"<table>"+table+"</table>"+
				"<recId>"+recId+"</recId>"+
				"<compId>"+s+"</compId>";
	xmlString+=saveRightsSimple(prefix, "access");
	xmlString+=saveRightsSimple(prefix, "change");
	xmlString+="</elements>";
	new net.send("main",window[callBack],null,"POST",xmlString,"text/xml");
}

function onSaveRights(){
	var doc=this.req.responseXML;
	var status = getXmlValue(doc, "status");
	var message = getXmlValue(doc, "message");
	var script = getXmlValue(doc, "script");
	var replaceId = getXmlValue(doc, "replaceId");
	jQuery('#'+replaceId+"_accessRightsdiv").replaceWith(getXmlValue(doc, "access"));
	eval(script);
	if(status!='0'){
		alert(message);
	}else{
		Windows.getWindow("main_accessrights_div_Window").close();
	}
}

function saveRightsSimple(id, mode){
	var groupPlus="";
	var groupMinus="";
	var userPlus="";
	var userMinus="";
	jQuery('#'+id+mode+"_grpPlus .grpPlus").each(function(){
		groupPlus+=this.innerHTML+",";
	});
	jQuery('#'+id+mode+"_grpMinus .grpMinus").each(function(){
		groupMinus+=this.innerHTML+",";
	});
	jQuery('#'+id+mode+"_usPlus .usPlus").each(function(){
		userPlus+=this.getAttribute('code')+",";
	});
	jQuery('#'+id+mode+"_usMinus .usMinus").each(function(){
		userMinus+=this.getAttribute('code')+",";
	});
	var xmlString="<"+mode+">"+
					"<defaultRight><![CDATA["+jQuery('#'+id+mode+'_def').attr('code')+"]]></defaultRight>"+
					"<groupm><![CDATA["+groupMinus+"]]></groupm>"+
					"<groupp><![CDATA["+groupPlus+"]]></groupp>"+
					"<userm><![CDATA["+userMinus+"]]></userm>"+
					"<userp><![CDATA["+userPlus+"]]></userp>"+
				"</"+mode+">";
	return xmlString;
}

//adds to last action menu
function addLastAction(unit, mode, recid, table, recIden){
	var elem="<div class='laction' style='padding:2px 0;'>";
	if(mode=="insert"){
		elem+="<img alt='"+getMessage("New")+"' src='DataServlet?unit=Main&amp;image=NEW16' style='vertical-align: bottom;'/>"
	}else if(mode=="update"){
		elem+="<img alt='"+getMessage("Updated")+"' src='DataServlet?unit=Main&amp;image=EDIT16' style='vertical-align: bottom;'/>"
	}
	elem+=" <a onclick=\"openIdUnit('"+unit+"', '"+recid+"', '"+table+"');\" class='stylishButForm' href='javascript:void(0);'>"+jQuery.trim(recIden)+"</a></div>";
	jQuery('#lastsp .laction:eq(9)').remove();
	jQuery('#lastsp').prepend(elem);
	
}

//anoigei to menu me ta programmata tou comidor
function openFlyout(event, obj, id){
	var $obj=jQuery(obj);
	var $wrapper=jQuery('#'+id);
	if($wrapper.is(':visible')){
		$wrapper.hide('slow');
		$wrapper.unbind('clickoutside');
		return;
	}
	var pos=$obj.offset();
	$wrapper.css('left', pos.left).css('top', pos.top+$obj.height()).show('slow');
	$wrapper.unbind('clickoutside').bind('clickoutside', function(){
			$wrapper.hide('slow');
		});
	stopEvents(event);	
}

function fixMainMenu(id){
	var menu=jQuery('#'+id);
	var width=menu.outerWidth(true);
	var children=menu.children();
	var unitWidth=0;
	var html=jQuery("<div id='overflowUnits' style='display:none'></div>");
	var len=children.length;
	var flooded=false;
	for(var i=0; i<len;){
		var menuItem=jQuery(children.get(i));
		unitWidth+=menuItem.outerWidth(true);
		if(unitWidth>=width-50){
			html.append(jQuery(children.get(--len)).remove());
			flooded=true;
		}else{
			i++;
		}
	}
	if(flooded){
		menu.append("<img src='DataServlet?unit=main&amp;image=DOWN' style='vertical-align:middle' onclick=\"openFlyout('overflowUnits')\"/>");
	}
	menu.after(html);
}


/* ===== GROWL ====== */
var isGrowlRunning = false;
        
function registerGrowl(){
	
	var application = new Growl.Application();
	application.name = "Javascript Example App";
	application.icon = "http://www.growlforwindows.com/gfw/examples/js/growl.png";
	
	var notificationTypes = new Array();
	var nt1 = new Growl.NotificationType();
	nt1.name = "NT1";
	nt1.displayName = "Example Notification One";
	nt1.enabled = true;
	notificationTypes.push(nt1);
	
	Growl.register(application, notificationTypes);
}

function notify(title, text){
	var notification = new Growl.Notification();
	notification.name = "NT1";
	notification.title = title;
	notification.text = text;
	notification.icon = "http://www.growlforwindows.com/gfw/examples/js/growl.png";
	notification.priority = "normal";
	
	Growl.notify("Javascript Example App", notification);
}

/*
Growl.onconnect = function(){alert("onconnect")};
Growl.ondisconnect = function(){alert("ondisconnect")};
Growl.ondata = function(){alert("ondata")};
Growl.onioerror = function(){alert("onioerror")};
Growl.onsecurityerror = function(){alert("onsecurityerror")};
Growl.onprogressevent = function(){alert("onprogressevent")};
Growl.onok = function(){alert("onok")};
Growl.oncallback = function(){alert("oncallback")};
Growl.onerror = function(){alert("onerror")};
*/
        

scriptLoaded();

