

var site = {
    original_title: '',
    module_title: '',
    toolbar_help_caption: '',
    iframe_document: null, 
	user : {},
    session : {},
    module_options: '', /* Some options thats passed along to the module */
	url_base : '',
    help_document: '',
    onresize_active: false,
    previous_tab_x_id: null,
    
    
    /* Make sure we have a current session, and that the user isnt inactive to long.  */
    update_session: function () { /* Triggered from EasyV4Gui */
        var d = new Date();
        site.session.last_update = (d.getTime()/1000);
    },
    
    /* Triggered for each xml request from xdbc. */
    update_session_status: function (xml_resp) { /* Check session status for each rpc */
        if( xml_resp ) {
            var sessionStatus = xml_resp.selectSingleNode('//Session_status');
            if( sessionStatus ) {
                if( sessionStatus.getAttribute('user_id') ) {
                    var lastupdate = sessionStatus.getAttribute('session_lastupdate');
                    site.session.last_update = lastupdate;
                }
            }
        }
    },
    
    /* Runs continuously every 10th second. */
    check_session_status: function () {
        if( site.session.last_update && site.session.last_update>0 ) {
            if( site.user.sessiontimeout && site.user.sessiontimeout>0 ) {
                var d = new Date();
                
                /* Finally, kill the session! */
                if( ((d.getTime()/1000)-site.session.last_update)>(site.user.sessiontimeout-60) ) {
                    document.location = '/index.php?get=login&action=logout&autologout=1';
                    return;
                /* First show a warning when approaching the timeout. */
                }else if( ((d.getTime()/1000)-site.session.last_update)>(site.user.sessiontimeout-300) ) {
                    $('logout_warning').style.display = 'block';
                }
            }
        }
        setTimeout(site.check_session_status, 10000);
    },
    
	popup : function(pName, pUrl, pW, pH, pScroll) {
		if( typeof v5_gui_toggle != "undefined" && v5_gui_toggle == true){
		    return site.layer_popup(pName, pUrl, pW, pH, pScroll);
		} else if( typeof parent.v5_gui_toggle != "undefined" && parent.v5_gui_toggle == true){
		    return site.layer_popup(pName, pUrl, pW, pH, pScroll);
		}
		
		/** Ok following is due to the ending support for resizeTo in mozilla
		 *  A default size of 10x10 is just stupid, change it to a more normal size.
		 *  If the resizeTo function doesnt work in the popup it doesnt matter too much with this fix
		 */
		if(pW == "10" && pH == "10"){
		    pW = "645"; pH = "470";
		}
		
		window.open(pUrl, pName, 'resizable=yes, scrollbars='+ pScroll +', toolbar=no, location=no, directories=no, status=no, menubar=no, width='+ pW +', height='+ pH +', top=50, left=50');
	},
    /**
	 * New open up pop-up function 
	 * jQuery compliant.. no xdbc-shit
	 */
    layer_popup: function(pName, pUrl, pW, pH, pScroll) {
        var action_type = pName;

        var top_offset = window.pageYOffset;

        if(action_type == "edit_item" || action_type == "edit_pages"){
            var popup = '';
        
            popup += '<div id="tmp_popup" class="v5_gui_popup"><div class="v5_close"><a href="#" onclick="$j(\'#tmp_popup\').remove(); return false;"><img src="/include/images/close.png" border="0"></a></div>';
            popup += ' <div class="v5_inner">';
            popup += '  <iframe border="0" frameborder="0" style="width:620px; height:440px;" src="'+pUrl+'"></iframe>';
            popup += ' </div>';
            popup += ' <div style="clear:both;"></div><img src="/include/images/eb_logo.png" class="eblogo"></div>';
            popup += '</div>';
        } else {
            
            // Fall back to normal.. do note: copy of popup-function
            window.open(pUrl, pName, 'resizable=yes, scrollbars='+ pScroll +', toolbar=no, location=no, directories=no, status=no, menubar=no, width='+ pW +', height='+ pH +', top=50, left=50');
            return false;
        }

        if( $j('#iSrc').contents() ){
            $j('#iSrc').contents().find('body').append( popup );
        } else {
            $j('body').append( popup );
        }
        
		return false;
	},
	load : function(redirect_to) {
		window.onresize = site.onresize_layout; //site.reset_layout;
		site.redirect_to = redirect_to;
		
		xdbc.path = '/index.php?get=xmlapi';
		xdbc.load('/?get=gui&action=ledger', site.init);
		//xdbc.load('/include/xml/ledger.xml', site.init);
	},
    logout: function () {

         try {
             eDesktop.widget.save_settings();
         } catch(e) {
         }

         xdbc.exec();
         window.location = '/?get=login&action=logout';
         return false;
    },
	init : function(resp) {
		if (!resp) return;
		xdbc.debug = false;
		xdbc.ledger = resp;
		
		var progress = '<div id="iProgress"><img src="/include/images/spinner.gif" align="absmiddle"/> Laddar...</div>';
		var span = document.createElement('SPAN');
		span.innerHTML = progress;
		document.body.appendChild(span.firstChild);

        var str = '';		
		var user = xdbc.ledger.selectSingleNode('//userdata');
		if (user.getAttribute('id') != '') {
			site.user.id = user.getAttribute('id');
			site.user.name = user.getAttribute('username');
            if( user.getAttribute('role') )
                site.user.role = user.getAttribute('role');
            if( user.getAttribute('sessiontimeout') )
                site.user.sessiontimeout = user.getAttribute('sessiontimeout');
            
            
            if( $('login_as') ) {
                if( !$('login_as').getAttribute('hold') ) {
        			$('login_as').innerHTML = '<img src="/include/images/tab_arrow.gif" align="absmiddle" onclick="site.tab_menu();">&nbsp;&nbsp; Inloggad som <a href="#" onclick="site.open_url(\'/index.php?get=profile&amp;action=edit\', true);">'+
        					site.user.name +'</a> | <a href="mailto:support@easybusiness.se" onclick="return site.supportEmail();"> <img src="/include/images/16/email.png" align="absmiddle" style="border: 0px;" border="0" /> Support</a> | <a href="#" onclick="return site.logout();">Logga ut</a>';
                }
            }
		} else {
			document.location.href = '/';
			return;
		}
        
        // Start building up the HTML for the tabs, icons, using the defined
        // modules from the ledger
        str+= '<div class="flap_holder">';
		var modules = xdbc.ledger.selectNodes('//modules/module');
		site.url_base = modules[0].parentNode.getAttribute('url_base');
		if (site.url_base == '/') {
			var dmn = '';
			var url = document.location.href.split('/');
			for (var i=0; i<3; i++) dmn+= url[i] +'/';
			site.url_base = dmn.slice(0,-1);
		}
		
		for (var m=0; m<modules.length; m++) {
			var iid = m+1;
			modules[m].setAttribute('iid', iid);
			var x_id = modules[m].getAttribute('id');
			var title = modules[m].getAttribute('title');
            var str_template = $('flap_template').innerHTML;
            str_template = str_template.replace(/\[x_id\]/g, x_id);

            if( modules[m].getAttribute('icon') ) {
                var icon = modules[m].getAttribute('icon');
                if( icon.indexOf('.')<=0 )
                    icon = icon+'.png';
                str_template = str_template.replace(/xid\.png/g, icon);
            }else{
                str_template = str_template.replace(/xid\.png/g, x_id+'.png');
            }
            str_template = str_template.replace(/\[iid\]/g, iid);
            str_template = str_template.replace(/\[title\]/g, title);
            str+=str_template;
			//str += '<div class="flap" gtype="flap" etype="radio" x_id="'+ x_id +'" iid="'+ iid +'" action="site.switch_tab();"><span class="f_start">&#160;</span><span class="f_body"><center><img src="/include/images/32/'+x_id+'.png" />'+ title +'</center></span><span class="f_end">&#160;</span></div>';
		}
		$('flap_bar').innerHTML = str +'</div>';

        site.trigger_first_flap();
		//setTimeout(site.trigger_first_flap, 400);
        /* Initialize help bubble */
        if( $('help_bubble') ) {
            site.help_popup.obj = $('help_bubble');
            site.help_popup.title = getChild('help_bubble', 'otype', 'help_bubble_title');
            site.help_popup.desc = getChild('help_bubble', 'otype', 'help_bubble_desc');
            site.help_popup.arrow = getChild('help_bubble', 'otype', 'help_bubble_arrow');
        }

		document.attachEvent('onclick', site.tree.mouse);
		document.attachEvent('ondblclick', site.tree.mouse);
		document.attachEvent('onclick', site.list.mouse);
		document.attachEvent('ondblclick', site.list.mouse);
        
        setTimeout(site.check_session_status, 1000);
	},
    toggle_help: function (action) {
        if( !action && $('frm_help').style.display=='block' ) {
            $('frm_help').style.display = 'none';
            $('helpButton').className = 'tool';
        } else {
            $('frm_help').style.display = 'block';
            if( $('helpButton') ) {
                $('helpButton').className = 'tool_down';
            }

            var help_url = site.get_help();
            if( help_url ) {
                /* We must find the active frmwa container */
                var divs = getChildren($('frm_workarea'), 'gtype', 'frm_container');
                for( var i = 0; i<divs.length; i++ ) {
                    if( divs[i].style.display!='none' ) {
                        var dim = getDim(divs[i]);
                        break;
                    }
                }

                $('helpFrame').style.height = dim.h+'px';
                $('helpFrame').style.width = 'auto';
                //$('helpFrame').innerHTML = '<iframe frameborder="0" src="http://manual.easyinteraction.net/?print=1&id='+help_oid+'" style="height:'+dim.h+'px">&#160;</iframe>';
                if( action=='update' ) {
                    if( $('helpFrame').firstChild.getAttribute('current_help')==help_url ){
                        return;
                    }
                }
                $('helpFrame').innerHTML = '<iframe current_help="'+help_url+'" frameborder="0" src="'+help_url+'" style="height:'+dim.h+'px">&#160;</iframe>';
            }else{
                $('frm_help').style.display = 'none';
            }
        }

        site.onresize_layout();

        /* Signal to the module that we have toggled help */
        var wf = site.module.selectSingleNode("./body/workframe");
        if( wf ) {
            if( wf.getAttribute('module') ) {
                eModule = wf.getAttribute('module');
                if( eModule.indexOf('/')>0 ) {
                    var function_call = eModule.substring(eModule.indexOf('/')+1, eModule.length)+'.on_help_trigger';
                }else{
                    var function_call = eModule+'.on_help_trigger';
                }
                try {
                    eval(function_call+'()');
                } catch( e ) {
                }

            }
        }

    },
    get_help: function () {
         var tab = site.module.getAttribute('id');
         if(  tab ) {
             var help_module = xdbc.ledger.selectSingleNode('//modules/module[@id="'+tab+'"]/help');
             if( help_module  ) {
                
                 return '/?get=help&module='+tab;
             }
         }
         return false;
    },
	trigger_first_flap: function () {
    
            var tabs = getChildren('flap_bar', 'gtype', 'flap');

            // If we have a redirect url, we use that, otherwise, just go to the first flap.
			if( site.redirect_to && site.redirect_to!="" ) {
                // Explode tab_ from redirect and activate that tab, if it is found.
                var isTab = site.redirect_to.slice(0,4);
                if( isTab=='tab_' ) {
                    var activate_tab = site.redirect_to.slice(4);
                    for( i in tabs ) {
                        if( tabs[i].getAttribute ) {
                            var x_id = tabs[i].getAttribute('x_id');
                            if( activate_tab==x_id ) {
                                getChild(tabs[i], 'nodeName', 'A').fireEvent('onclick');
                                return;
                            }
                        }
                    }
                    site.redirect_to = '';
                }

                if( site.redirect_to!='' ) {
                    site.open_url(site.redirect_to, true);
                    site.fix_layout('base', 'hrzn', 'vert');
                    site.activate_tab('content');
                    return;
                }

			}
            
            // Goto to the first tab [0] by firing an onclick event on the <a>-tag of the tab object
            getChild(tabs[0], 'nodeName', 'A').fireEvent('onclick');

	},
	open_url : function(href, hide_frames) {
         /* If help frame is showing, hide it. 
         if( $('frm_help') ) {
             if( $('frm_help').style.display=='block' ) {
                 $('frm_help').style.display = 'none';
             }
         }*/

         /* Should we hide any other frames */
         if( hide_frames ) {
             var divs = getChildren($('frm_workarea'), 'gtype', 'frm_container');
             for( var i = 0; i<divs.length; i++ ) {
                 divs[i].style.display = 'none';
             }
    
             var frames = getChildren(document.body, 'frm_type');
             for (var f=0; f<frames.length; f++) {
                frames[f].className = frames[f].className.split(' ')[0];
                frames[f].style.display = 'none';
                if (frames[f].nextSibling.nodeType == 1) frames[f].nextSibling.style.display = 'none';
             }
         }

         $('frmwa').style.display = 'block';
         if( !site.tab_body ) {
             site.tab_body = $('frmwa');
         }
         if( !$('iSrc') ) {
             $('frmwa').innerHTML = '<iframe frameborder="0" name="frmiSrc" id="iSrc" src="'+ href +'"/>';
         }else{
    		var ifrm = getChildren(site.tab_body, 'nodeName', 'IFRAME');
    		if (!ifrm.length) {
    			 return;
    		}
            ifrm[0].src = href;
         }
	},
	reload_iframe : function() {
		var ifrm = getChildren(site.tab_body, 'nodeName', 'IFRAME');
		if (!ifrm) return false;
		// This is a really ugly hack to reload the current page of the iframe.
		ifrm[0].src = '/include/blank.htm?d='+xdbc.uniqId();
        //The below was replaced with an onload back in blank.htm
		window.setTimeout('history.go(-1)', 500);
	},
	draw_window: function (target_body, name, url, width, height) {
		var content_div = document.createElement('div');
		content_div.style.position = 'absolute';
		content_div.style.top = '20px';
		content_div.style.left = '200px';		
		content_div.style.width = '600px';
		content_div.style.height = '400px';		
		var content = '<iframe src="'+url+'" style="width: 100%; height: 100%;"></iframe>';
		content_div.innerHTML = content;
		document.body.appendChild(content_div);
		//target_body.appendChild(content_div);
	},
	tab_menu : function() {
		var mItems = xdbc.ledger.selectNodes('//modules/module');
		var str = '<input type="text" id="focusEl" style="position: absolute; top: -1000px;"/><div class="ctx_menu" otype="ctx_menu" id="mod_menu"><div class="ctx_minner">'+
					'<table cellspacing="0" cellpadding="0" border="0">'+
					'<col class="colicon"/><col class="coltext"/><col class="colarrow"/>';
		for (var m=0; m<mItems.length; m++) {
			if (mItems[m].getAttribute('status') == 'hidden') continue;
			var type = mItems[m].getAttribute('type');
			var mid = mItems[m].getAttribute('iid');
			var x_id = mItems[m].getAttribute('id');
			var title = mItems[m].getAttribute('title');
			var icon = mItems[m].getAttribute('icon');
			icon = icon || '&#160;';
			var _hc = mItems[m].hasChildNodes();
			var cmenu = (_hc)? '_cmenu="'+ mid +'"' : '' ;
			str += '<tr mId="'+ mid +'" '+ cmenu +' class="chx_mitem" gtype="chx_mitem" onmousedown="site.switch_tab(\''+ x_id +'\', true)">'+
					'<td class="icon">&nbsp;</td><td class="text">'+ title +'</td>'+
					'</tr>';
		}
		str += '</table></div></div>';
		$('ctxmenu').innerHTML = str;
		
		var aDim = getDim(event.srcElement);
		var ml = (aDim.l + $('mod_menu').offsetWidth > document.documentElement.clientWidth)? document.documentElement.clientWidth - $('mod_menu').offsetWidth : aDim.l;

		$('mod_menu').style.top = (aDim.t + aDim.h) +'px';
		$('mod_menu').style.left = ml +'px';
		
		$('focusEl').focus();
		$('focusEl').onblur = function() {
			$('mod_menu').style.left = '-1000px';
		}
	},
    supportEmail: function () {
         var user = xdbc.ledger.selectSingleNode('//userdata');
         if (user.getAttribute('email') )
             var email = user.getAttribute('email')
         else
             var email = '';

         if (user.getAttribute('first_name') )
             var name = user.getAttribute('first_name')
         else
             var name = '';

         if (user.getAttribute('last_name') )
             name+=' '+user.getAttribute('last_name')
         var language = 'se';
         if (user.getAttribute('language') )
             language = user.getAttribute('language');

         /* Get site specific vars */
         var site = xdbc.ledger.selectSingleNode('//site');
         if( site ) {
             var support_category = 1;
             if (site.getAttribute('support_category') )
                 support_category = site.getAttribute('support_category');
             if (site.getAttribute('support_ticket_url') )
                 support_ticket_url = site.getAttribute('support_ticket_url');
             else
                 support_ticket_url = false;

             if (site.getAttribute('support_faq_url') )
                 support_faq_url = site.getAttribute('support_faq_url');
             else
                 support_faq_url = false;

             if( support_ticket_url ) {
                 $('supportEmailIframe').setAttribute('src', support_ticket_url+'?email='+escape(email)+'&name='+escape(name)+'&cat='+support_category+'&lang='+language);
             }else{
                 $('support_support_tab').style.display = 'none';
                 $('support_support').style.display = 'none';
             }

             if(  $('support_faq_tab') ) {
                 if( support_faq_url ) {
                     $('supportFaqIframe').setAttribute('src', support_faq_url);
                 }else{
                     $('support_faq_tab').style.display = 'none';
                     $('support_faq').style.display = 'none';
                 }
             }

             /* Activate the first visible tab. */
             var tabs = getChildren(getChild($('supportEmail'), 'className', 'frm_tab_row'), 'tlink');
             for( var i = 0; i<tabs.length; i++ ) {
                 if( tabs[i].style.display!='none' ) {
                     getChild(tabs[i], 'nodeName', 'SPAN').fireEvent('onclick');
                     break;
                 }
             }

             $('supportEmail').style.display = 'block';
         }
         return false;
    },
    /* Title updates can be added to this array. */
    update_title_functions: {  }, 
    update_title: function () {
         if( !top.document.title || !site.original_title )
             return;
         var new_title = '';
         new_title = site.original_title+' - '+site.module_title;

         for( i in site.update_title_functions ) {
             addon_title = site.update_title_functions[i]();
             if( addon_title!='' ) {
                 new_title+=' - '+addon_title;
             }
         }
         top.document.title = new_title;
    },
	switch_tab : function() {
        
        site.help_popup.close();
        $('ctxmenu').innerHTML = '';
		if (arguments.length>= 2) {

            /* Accept options, when switching tab, so the module can pick it up. */
            if( arguments.length==3 ) {
                site.module_options = arguments[2];
            }
            
			var x_id = arguments[0];
			var ltb = arguments[1];
			var tabEl = getChild('flap_bar', 'x_id', x_id);
            site.activate_tab(x_id);
            getChild(tabEl, 'nodeName', 'A').fireEvent('onclick');
            site.module_title = tabEl.getAttribute('flap_title');
            site.update_title();
            return;
		}

		var srcEl = event.srcElement;
		var tabEl = getParent(srcEl, 'gtype', 'flap');
		if (!tabEl) return;
        site.module_title = tabEl.getAttribute('flap_title');
        site.update_title();

        var tabId = tabEl.getAttribute('iid');
        var xId = tabEl.getAttribute('x_id');
        
        // Prompt the user to save layout if none exists
        if( site.eb_initial_layout_is_saved == 'not_saved' && site.previous_tab_x_id == 'layout' &&  site.previous_tab_x_id != xId ) {
            if( confirm("Du verkar inte ha sparat din första design. Vill du spara nu?") ){
                eLayout.save(true, function(){
                    top.location.href = '/?get=gui&redirect=tab_content';
                    return true;
                });
            }
        }
        site.previous_tab_x_id = xId;
        // - - - - - - - - - - - - -
        
        site.activate_tab(xId);
        

		if (site.list.root) site.list.root.innerHTML = '';
		if (site.tree.root) site.tree.root.innerHTML = '';

        site.module = xdbc.ledger.selectSingleNode('//modules/module[@iid="'+ tabId +'"]');
		var tools = site.module.selectNodes('./toolbar/*');
		$('tool_bar').innerHTML = site.toolbar.render(tools);
		
		var tree = site.tree.xdata = site.module.selectSingleNode("./body/frame[@type='tree']");
		var list = site.list.xdata = site.module.selectSingleNode("./body/frame[@type='list']");
		var cust = site.module.selectSingleNode("./body/frame[@type='custom']");
		var wf = site.module.selectSingleNode("./body/workframe");
		if (wf && !wf.getAttribute('iSrc')) $('frmwa').innerHTML = '';
		

		var frames = getChildren(document.body, 'frm_type');
		for (var f=0; f<frames.length; f++) {
			frames[f].className = frames[f].className.split(' ')[0];
			frames[f].style.display = 'none';
			if (frames[f].nextSibling.nodeType == 1) frames[f].nextSibling.style.display = 'none';
		}
		$('search_bar').style.display = 'none';
		
		site.tab_body = $('frmwa');
		
		var frames = site.module.selectNodes('./body/frame');
		for (var f=0; f<frames.length; f++) {
			var ftype = frames[f].getAttribute('type');
			var fsearch = frames[f].getAttribute('search');
			var hFrame = getChildren('base', 'frm_type', ftype);
			if (!hFrame.length) return;
			hFrame = hFrame[0];
			if (frames[f].getAttribute('width')) hFrame.setAttribute('lw', frames[f].getAttribute('width'));
			if (fsearch) hFrame.className = hFrame.className +' search';
			hFrame.style.display = 'block';
			if (hFrame.nextSibling.nodeType == 1) hFrame.nextSibling.style.display = 'block';
		}
		site.fix_layout('base', 'hrzn', 'vert');

		site.search.init();
		//if (tree && tree.hasChildNodes()) site.tree.init(tree);
		//if (list && list.hasChildNodes()) site.list.init(list);
		if (cust) {
			var cHtml = cust.xml.replace(/<\!\[CDATA\[|\]\]>|\t/g, '');
			if (env.ie) {
				$('custom').innerHTML = cHtml;
			} else {
				var rng = $('custom').ownerDocument.createRange();
				rng.setStartBefore($('custom'));
				$('custom').innerHTML = '';
				$('custom').appendChild(rng.createContextualFragment(cHtml));
			}
		}
		
        /* If a workframe node is available */
		if (wf) {
			var iSrc = wf.getAttribute('iSrc');
			var xsl_url = wf.getAttribute('xsl_url');
			var eModule = wf.getAttribute('module');

            /* Hide all frm_containers 
            Some modules should only be loaded once, if they should,
            they should have their own container in v4gui. It will be hidden 
            and displayed when neeeded. 
            */
            var divs = getChildren($('frm_workarea'), 'gtype', 'frm_container');
            for( var i = 0; i<divs.length; i++ ) {
                divs[i].style.display = 'none';
            }
            if( wf.getAttribute('loadtype') ) {
                var frmwa_container = 'frmwa_'+xId;
                var loadtype = 'once';
            } else {
                var loadtype = '';
                var frmwa_container = 'frmwa';
            }
            $(frmwa_container).style.display = 'block';
            if( loadtype=='once' ) {
                if ($(frmwa_container).childNodes.length > 1) {
                    site.fix_layout('base', 'hrzn', 'vert');

                    /* Trigger a notifier to make sure the module knows its active again. */
                    var notifier_function = xId+'_notifier';
                    if( notifier_function ) {
                        try {
                            eval(notifier_function+'("update");');
                        } catch( e ) {

                        }
                    }
                    return;
                }
            }
            /* Store some properties of the current module. */
            $('frm_workarea').setAttribute('loadtype', loadtype);
            $('frm_workarea').setAttribute('loaded_xid', xId);

            if (eModule) { /* Use the XSL Module */
                // Add support for newly created XSL-Modules
                if( eModule.indexOf('/')>0 ) {
                    var eModule_module = eModule.substring(0, eModule.indexOf('/'));
                    var eModule_package = eModule.substring(eModule.indexOf('/')+1, eModule.length);
                    $(frmwa_container).setAttribute('module', eModule_package);
                    var eModuleLocation = '/?get=gui&action=xsl_module&module='+eModule_module+'&package='+eModule_package+'&/package.xsl';
                    var xMod = xdbc.load('<data><'+ eModule_module+'_'+eModule_package+'/></data>');
                }else{
                    var eModuleLocation = '/include/xsl/'+ eModule +'.xsl';
                    var xMod = xdbc.load('<data><'+ eModule +'/></data>');
                    $(frmwa_container).setAttribute('module', eModule);
                }
                xdbc.transform(xMod, eModuleLocation, frmwa_container, "site.fix_layout('base', 'hrzn', 'vert');")
                return;
			}
			if (iSrc) { // Or use an fallback URI
				var href = (iSrc.slice(0,4) == 'http')? iSrc : site.url_base + iSrc ;
				if ($('iSrc')) {
				    // An iframe already exist, populate that one.
				    $('iSrc').src = href;
				} else {
				    // First load or iframe not existing, construct it.
				    $('frmwa').innerHTML = '<iframe frameborder="0" name="frmiSrc" id="iSrc" src="'+ href +'"/>';
				}
				
                $(frmwa_container).parentNode.style.display = 'block';
                //site.fix_layout(frmwa_container, 'wf_hrzn', 'wf_vert');
				return;
			}
			var cHtml = wf.firstChild.xml.replace(/<\!\[CDATA\[|\]\]>|\t/g, '');
			if (env.ie) {
				$('frmwa').innerHTML = cHtml;
			} else {
				var rng = $('frmwa').ownerDocument.createRange();
				rng.setStartBefore($('frmwa'));
				$('frmwa').innerHTML = '';
				$('frmwa').appendChild(rng.createContextualFragment(cHtml));
			}
		//site.fix_layout('frmwa', 'wf_hrzn', 'wf_vert');
		}
	},
    activate_tab: function (x_id) {
        var tabEl = getChild('flap_bar', 'x_id', x_id);
        if (tabEl ) {
            var cln_before = tabEl.className; // Get the class name before, and check if was down.
            var eopt = tabEl.getAttribute('eopt');
            if (cboard[eopt]) 
                eMouse.classname(cboard[eopt]);
            cboard[eopt] = tabEl;
            eMouse.classname(tabEl, 'down');
            if( cln_before.indexOf('flap_down')==-1 ) { // Update submenu if it wasnt active before.
                site.module = xdbc.ledger.selectSingleNode('//modules/module[@id="'+ x_id +'"]');
                var tools = site.module.selectNodes('./toolbar/*');
                site.toolbar.init(tools);
            }
        }
    },
    onresize_layout: function() {
        if( !site.onresize_active ) {
            setTimeout(function() {
                site.fix_layout('base', 'hrzn', 'vert');           
                site.onresize_active = false;
            }, 100);    
        }    
        site.onresize_active = true;
    },
	
	fix_layout : function(el, hrzn, vert) {
        var fel = el;
		var el = $(el) || document.body;

        /* Find all horizontal divs that need to get a good width and height. */
		var tmp_uh = 0;
		var tmp_hel = new Array();
		var hDiv = getChildren(el, 'ltype', hrzn);
        var static_width = 0;
		for (var h=0; h<hDiv.length; h++) {
			if ( hDiv[h].currentStyle.display == 'none' )
                continue;   
			if ( !hDiv[h].getAttribute('lh') ) {
				tmp_hel.push(hDiv[h]);
				continue;
			}

			var bN = parseInt(hDiv[h].currentStyle.borderTopWidth);			bN = bN || 0;
			var bS = parseInt(hDiv[h].currentStyle.borderBottomWidth);		bS = bS || 0;
			tmp_uh += parseInt(hDiv[h].getAttribute('lh')) + bN + bS;
			hDiv[h].style.height = hDiv[h].getAttribute('lh') +'px';
		}

        // Strip the toolbar height from the window height, to get a workarea height.
        var workarea_height = parseInt(document.documentElement.clientHeight-tmp_uh)
        tmp_uh = 0;
        var workarea_width = document.documentElement.clientWidth;

		/* Fix vertically? */
		var tmp_uv = 0;
		var tmp_vel = new Array();
		var vDiv = getChildren(el, 'ltype', vert);
		if (vDiv.length) {
			var pbE = parseInt(vDiv[0].parentNode.currentStyle.borderLeftWidth);	pbE = pbE || 0;
			var pbW = parseInt(vDiv[0].parentNode.currentStyle.borderRightWidth);	pbW = pbW || 0;
			var pbN = parseInt(vDiv[0].parentNode.currentStyle.borderTopWidth);		pbN = pbN || 0;
			var pbS = parseInt(vDiv[0].parentNode.currentStyle.borderBottomWidth);	pbS = pbS || 0;
		}


		for (var v=0; v<vDiv.length; v++) {
			if (vDiv[v].currentStyle.display == 'none')
                continue;
			if (!vDiv[v].getAttribute('lw')) {
				tmp_vel.push(vDiv[v]);
				continue;
			}
			
			var bE = parseInt(vDiv[v].currentStyle.borderLeftWidth);	bE = bE || 0;
			var bW = parseInt(vDiv[v].currentStyle.borderRightWidth);	bW = bW || 0;
			var bN = parseInt(vDiv[v].currentStyle.borderTopWidth);		bN = bN || 0;
			var bS = parseInt(vDiv[v].currentStyle.borderBottomWidth);	bS = bS || 0;

			tmp_uv += parseInt(vDiv[v].getAttribute('lw')) + bE + bW;
            var s_width = parseInt(vDiv[v].getAttribute('lw'));
            if(  env.ie6 && s_width>3  ) {
                s_width-=3;
            }

            vDiv[v].style.width = s_width +'px';
			vDiv[v].style.height = workarea_height+'px';
            
		}

        for (var h=0; h<tmp_hel.length; h++) {
            var bN = parseInt(tmp_hel[h].currentStyle.borderTopWidth);		bN = bN || 0;
            var bS = parseInt(tmp_hel[h].currentStyle.borderBottomWidth);	bS = bS || 0;
            tmp_uh += bN + bS;
            var hel = Math.abs(parseInt((tmp_hel[h].parentNode.offsetHeight-tmp_uh)/tmp_hel.length)) +'px';
        
            if( tmp_hel[v] ) {
    			tmp_hel[v].style.width = (workarea_width-tmp_uv) +'px';
    			tmp_hel[v].style.height = (workarea_height-tmp_uh) +'px';
            }
        }

        tmp_uh = 0;
		for (var v=0; v<tmp_vel.length; v++) {
			var bE = parseInt(tmp_vel[v].currentStyle.borderLeftWidth);		bE = bE || 0;
			var bW = parseInt(tmp_vel[v].currentStyle.borderRightWidth);	bW = bW || 0;
			var bN = parseInt(tmp_vel[v].currentStyle.borderTopWidth);		bN = bN || 0;
			var bS = parseInt(tmp_vel[v].currentStyle.borderBottomWidth);	bS = bS || 0;
			
			tmp_uv += bE + bW;

            if( tmp_vel[v] ) {
                var st_width = (workarea_width-tmp_uv);
                if( env.ie6 ) {
                    st_width-=2;
                }
    			tmp_vel[v].style.width =  st_width+'px';
    			tmp_vel[v].style.height = (workarea_height-tmp_uh) +'px';
            }
            tmp_vel[v].style.styleFloat = 'left'; 
            
		}

        /* Find any other frmwa containers than the regular */
        frms = getChildren('base', 'gtype', 'frm_container');
        for( var i = 0; i<frms.length; i++ ) {
            if( frms[i].style.display=='block' && frms[i].id!='frmwa'  ) {
                frms[i].style.height = workarea_height+'px';
                frms[i].style.width = (workarea_width-tmp_uv)+'px';
                $('frmwa').style.height = workarea_height+'px';
                $('frmwa').style.width = (workarea_width-tmp_uv)+'px';
            }
        }

        /* If layout is showing, make sure the interiors resize as well */
        if( $('frm_help').style.display=='block' ) {
            $('helpFrame').style.height = workarea_height+'px';
            $('helpFrame').firstChild.style.height = workarea_height+'px';
        }

        /* Call the modules resize function to make sure it can do local adjustments. */
        var modules = getChildren('workarea_space', 'gtype', 'frm_container');
        var active_module = null
        for( var i = 0; i<modules.length; i++ ) {
            if( modules[i].style.display=='block' ) {
                active_module = modules[i];
                break;
            }
        }

        if( active_module ) {
            var m = active_module.getAttribute('module');
            if( m ) {
                var onresize = m+'.onresize();';
                try {
                    eval(onresize);
                } catch( e ) {

                }
            }
        }

        /* Position the logged in as layer.*/
		if ($('login_as')) {
            $('login_as').style.right = '5px';
        }
	},
	toolbar : {
		init : function(nodes) {
			site.toolbar.root = $('tool_bar');
			site.toolbar.root.innerHTML = site.toolbar.render(nodes);
		},
		render : function(nodes) {
			var str = '';
			for (var t=0; t<nodes.length; t++) {
				if (nodes[t].getAttribute('type') == 'divider') {
					str += '<div class="divider">&#160;</div>';
				} else {
					var title	= nodes[t].getAttribute('title');
					var t_id	= nodes[t].getAttribute('t_id');
					var action	= nodes[t].getAttribute('action'); action = (action)? action.replace(/'/g, '\'') : '' ;
					var iSrc	= nodes[t].getAttribute('iSrc'); iSrc = (iSrc)? 'iSrc="'+ iSrc +'"' : '' ;
					var icon	= nodes[t].getAttribute('icon'); icon = (icon)? '<img src="/include/images/16/'+ icon +'.png" align="absmiddle"/>' : '' ;
					var etype	= nodes[t].getAttribute('etype'); etype = (etype)? ' etype="'+ etype +'"' : '' ;
					var eopt	= nodes[t].getAttribute('eopt'); eopt = (eopt)? ' eopt="'+ eopt +'"' : '' ;
					var cName	= (nodes[t].getAttribute('status') == 'disabled')? 'tool_disabled' : 'tool' ;
					str += '<div class="'+ cName +'" t_id="'+ t_id +'" gtype="tool"'+ etype + eopt +' action="'+ action +'" '+ iSrc +'>'+ icon +' '+ title +'</div>'
				}
			}

            /* Lets not show any help if there are no tools. */
            if( site.toolbar_help_caption!='' && nodes.length>0 ){
                /* If help frame is already visible, update the content, if needed. */
                var help_mode = 'tool';
                if( $('frm_help') ) {
                    if( $('frm_help').style.display=='block' ){
                        site.toggle_help('update');
                        help_mode = 'tool_down';
                    }
                }

                if( site.get_help() ) {
                    str += '<div class="'+help_mode+'" id="helpButton" t_id="help" onclick="site.toggle_help();"><img src="/include/images/16/help.png" align="absmiddle" /> '+site.toolbar_help_caption+'</div>';
                }
            }

            return str;
		},
		changeTo : function(state, tools) {
            try { 
            if( !$('tool_bar') )
                return;
            } catch(e) { }
			if (typeof(tools) == 'string') tools = new Array(tools);
			for (var i=0; i<tools.length; i++) {
				var t = getChildren('tool_bar', 't_id', tools[i]);
				if (!t.length) continue;
				t[0].className = (state == 'disabled')? 'tool_disabled' : 'tool' ;
			}
		},
        setAction: function (tool, action) {
            var t = getChildren('tool_bar', 't_id', tool);
            if (!t.length) 
                return;
                t[0].setAttribute('action', action);
        }
	},
	search : {  
		init : function() {
			if (site.search.button) return;
			site.search.button = $('btn_search');
			$('inp_search').attachEvent('onkeypress', site.search.key);
		},
		key : function() {
			if (event.keyCode == 13) {
				site.search.value = $('inp_search').value;
				site.search.button.fireEvent('onclick');
			}
		}
	},
	tree : {
		init : function(xTree, title) {
			site.tree.root = $('frm_tree');
            var tree_title = getChild('base', 'otype', 'tree_title');
            if( tree_title ) {
                if(  title ) {
                    tree_title.style.display = 'block';
                    tree_title.innerHTML = '<h2>'+title+'</h2>';
                }else{
                    tree_title.style.display = 'none';
                }
            }
            // Deprecated 
			//while (site.tree.xdata.hasChildNodes()) site.tree.xdata.removeChild(site.tree.xdata.firstChild);
			//while (xTree.documentElement.hasChildNodes()) site.tree.xdata.appendChild(xTree.documentElement.firstChild);

            // Delete all tree nodes first.
            var nodes = site.tree.xdata.selectNodes('.//i');
            for( var i = 0; i<nodes.length; i++ ) {
                nodes[i].parentNode.removeChild(nodes[i]);
            }

            // Append the new ones.
            var nodes = xTree.selectNodes('//i');
            for( var i = 0; i<nodes.length; i++ ) {
                site.tree.xdata.appendChild(xTree.documentElement.firstChild);
            }
            site.tree.render(site.tree.xdata);
		},
		mouse : function(srcEl, event_type) {
            if( !(srcEl && event_type) ) {
                var srcEl = event.srcElement;
                var event_type = event.type;
            }
            if( !srcEl )
                return;

            var trEl = getParent(srcEl, 'etype', 'tree');
            if (!trEl) return;

            var t_id = trEl.getAttribute('t_id');
            var ttype = srcEl.getAttribute('ttype');
                
            if( event_type=='click' ) {
                switch (ttype) {
                    case 'ico': // If you clicked the folder, we should click the ttl.
                        var n = getChild(srcEl.parentNode, 'ttype', 'ttl');
                        if( n ) {
                            n.fireEvent('onclick');
                        }
                        break;
                    case 'ind':
                        var iSt = srcEl.getAttribute('state');
                        if (!iSt) return;
                        var icon = (iSt == 'col')? 'minus' : 'plus' ;
                        srcEl.setAttribute('state', ((iSt == 'col')? 'exp' : 'col'));
                        srcEl.src = '/include/images/16/tree/'+ icon +'.gif';
                        trEl.style.overflow = (iSt == 'col')? 'visible' : 'hidden' ;
                        trEl.style.height = (iSt == 'col')? 'auto' : '16px' ;
                        if (!trEl.lastChild.hasChildNodes()) {
                            var xNode = site.module.selectSingleNode("./body/frame[@type='tree']//*[@id='"+ t_id +"']");
                            if (xNode.hasChildNodes()) site.tree.render(xNode);
                            else {
                                /*	SERVER REQUEST	*/
                            }
                        }
                        break;
                    case 'ttl':
                        if (site.tree.active) site.tree.active.className = '';
                        srcEl.className = 'active';
                        site.tree.active = srcEl;
                        
                        var act = trEl.getAttribute('action');
                        if (act) {
                            try {eval(act);}
                            catch(e) {alert('Felmeddelande:\n'+ e.description);}
                        }
                        break;
                }
            }else if( event_type=='dblclick' ) {
                switch( ttype ) {
                    case 'ico': 
                    case 'ttl':
                        var n = getChild(srcEl.parentNode, 'ttype', 'ind');
                        if( n ) {
                            n.fireEvent('onclick');
                        }
                        break;
                        break;
                }
            }
		},
		render : function(xData) {
			if (xData.nodeType == 9) {
				xData = xData.documentElement.firstChild;
			}

			var tree_node = getChildren(site.tree.root, 't_id', xData.getAttribute('id'));
			var tNode = (tree_node.length)? tree_node[0].lastChild : site.tree.root ;
			var xTree = xData.selectNodes('./*');
			var tStr = '';

            /* If node doesnt have any children, lets remove the collapse arrow. */
            /* If a node gets some children, we also verify that it can be expanded/collapsed. */
            var collapse_img = getChild(tNode.parentNode, 'ttype', 'ind');
            if( collapse_img ) {
                if( xTree.length==0 ){
                    collapse_img.setAttribute('src', '/include/images/16/tree/_.gif');
                    collapse_img.removeAttribute('state');
                }else{
                    if( !collapse_img.getAttribute('state') ) {
                        collapse_img.setAttribute('src', '/include/images/16/tree/plus.gif');
                        collapse_img.setAttribute('state', 'col');
                    }
                }
            }

			for (var i=0; i<xTree.length; i++) {
				var t_hc	= xTree[i].getAttribute('sys:hc');
				var t_id	= xTree[i].getAttribute('id');
				var t_ind	= (t_hc > 0 || xTree[i].hasChildNodes())? 'plus' : '_' ;
				var state	= (t_hc > 0 || xTree[i].hasChildNodes())? 'state="col"' : '' ;
				var t_icon	= xTree[i].getAttribute('icon');
				var t_title = xTree[i].getAttribute('title');
				var t_act	= xTree[i].getAttribute('action');
				t_act = (t_act)? 'action="'+ t_act +'"' : '' ;
				tStr += '<div etype="tree" t_id="'+ t_id +'" '+ t_act +' title="'+t_title+'">'+
							'<nobr><img ttype="ind" '+ state +' src="/include/images/16/tree/'+ t_ind +'.gif" align="absmiddle"/>'+
							'<img ttype="ico" src="/include/images/16/'+ t_icon +'" align="absmiddle"/>'+
							'<span ttype="ttl" title="'+t_title+'">'+ t_title +'</span></nobr>'+
						'<sys:tree ttype="cld"/></div>';
                
			}
            tNode.innerHTML = tStr;
		},
		reload : function(tEl) {
			tEl = getParent(tEl, 'etype', 'tree');
			var xNode = site.tree.xdata.selectSingleNode('.//*[@id="'+ tEl.getAttribute('t_id') +'"]');
			if (xNode) {
				while (xNode.firstChild) xNode.removeChild(xNode.firstChild);
			}
			
			var indImg = getChildren(tEl, 'nodeName', 'IMG')[0];
			indImg.setAttribute('state', 'col');
			indImg.src = '/include/images/16/tree/plus.gif';
			tEl.lastChild.innerHTML = '';
			indImg.fireEvent('onclick');
		}
	},
	list : {
		init : function(xList) {
			site.list.root = $('frm_list');
			site.list.root.innerHTML = '';
			
			while (site.list.xdata.hasChildNodes()) site.list.xdata.removeChild(site.list.xdata.firstChild);
			while (xList.documentElement.hasChildNodes()) site.list.xdata.appendChild(xList.documentElement.firstChild);
			site.list.render(site.list.xdata);
		},
		mouse : function() {
			var srcEl = event.srcElement;
			var lsEl = getParent(srcEl, 'etype', 'list');
			var lscEl = getParent(srcEl, 'ltype', 'ls_child');
			if (!lsEl && !lscEl) return;
			var l_id = (lscEl)? lscEl.getAttribute('l_id') : lsEl.getAttribute('l_id') ;
			var ltype = srcEl.getAttribute('ltype');
			switch (event.type) {
                case 'click':
					var xNode = site.module.selectSingleNode("./body/frame[@type='list']//*[@id='"+ l_id +"']");
					if (!xNode.getAttribute('nType')) xNode.setAttribute('is_read', 'true');
					
					var lObj = (lscEl)? lscEl : lsEl ;
					var liType = lObj.getAttribute('cname');
					var isRead = (xNode.getAttribute('is_read'))? ' is_read' : '';
					if (site.list.active && site.list.active.className.indexOf('active') > -1) site.list.active.className = site.list.active.className.slice(0,-7);
					if (lObj.parentNode.active) lObj.parentNode.active.className = liType + isRead;
					
					lObj.className = liType + isRead +' active';
					lObj.parentNode.active = lObj;
					if (lObj == lscEl) site.list.active = lscEl;
					
					if (ltype == 'ind') {
						var iSt = srcEl.getAttribute('state');
						var icon = (iSt == 'col')? 'minus' : 'plus' ;
						srcEl.src = '/include/images/16/tree/'+ icon +'.gif';
						srcEl.setAttribute('state', ((iSt == 'col')? 'exp' : 'col'));
						
						lsEl.style.overflow = (iSt == 'col')? 'visible' : 'hidden' ;
						lsEl.style.height = (iSt == 'col')? 'auto' : '30px' ;
						
						if (!lsEl.lastChild.hasChildNodes() && xNode.getAttribute('sys:hc')) {
							if (xNode.hasChildNodes()) site.list.render(xNode);
							else {
								xdbc.load('/include/xml/req_mail_list_children.xml', site.list.render);
							}
						}
					}
					break;
				case 'dblclick':
					if (ltype == 'ind') return;
					var indEl = getChildren(lsEl, 'ltype', 'ind')[0];
					indEl.fireEvent('onclick');
					break;
			}
		},
		render : function(xData) {
			var lNode = site.list.root;
			if (xData.nodeType == 9) {
				var xDt = xData.selectSingleNode('//data/*');
				var xPrt = site.module.selectSingleNode("./body/frame[@type='list']//*[@id='"+ xDt.getAttribute('id') +"']");
				var xFrm = (xPrt)? xPrt : site.module.selectSingleNode("./body/frame[@type='list']");
				while (xFrm.hasChildNodes()) xFrm.removeChild(xFrm.firstChild);
				while (xDt.hasChildNodes()) xFrm.appendChild(xDt.firstChild);
				
				var list_node = getChildren(site.list.root, 'l_id', xDt.getAttribute('id'));
				lNode = (list_node.length)? list_node[0].lastChild : lNode;
				xData = xFrm;
			} else {
				if (xData.getAttribute('id')) lNode = getChildren(site.list.root, 'l_id', xData.getAttribute('id'))[0].lastChild;
			}
			
			var xList = xData.selectNodes('./*');
			var lStr = '';
			for (var i=0; i<xList.length; i++) {
				var l_id	= xList[i].getAttribute('id');
				var l_icon	= xList[i].getAttribute('icon');
				var l_title = xList[i].getAttribute('title');
				var l_text	= xList[i].getAttribute('text');
				var l_hc	= xList[i].getAttribute('sys:hc');
				var is_read = xList[i].getAttribute('is_read');
				var action	= xList[i].getAttribute('action');
				l_hc = (l_hc)? '<tt>('+ l_hc +')</tt>' : '' ;
				is_read = (is_read)? ' is_read' : '' ;
				action = (action)? ' action="'+ action +'"' : '' ;
				if (xList[i].getAttribute('ntype') == 'parent') {
					lStr += '<div class="ls_item" cname="ls_item" ltype="list" etype="list" '+ action +' l_id="'+ l_id +'"><div class="ls_capt">'+ l_hc +
								'<img ltype="ind" state="col" src="/include/images/16/tree/plus.gif" align="absmiddle"/>'+
								'<span ltype="ttl">'+ l_title +'</span></div>'+
							'<sys:list ltype="cld"/></div>';
				} else {
					lStr += '<div class="ls_child'+ is_read +'" cname="ls_child" ltype="ls_child" '+ action +' l_id="'+ l_id +'"><img src="/include/images/16/'+ l_icon +'" ltype="ls_child_x"/>'+
							'<span class="caption" ltype="ls_child_x">'+ l_title +'</span><br/><span ltype="ls_child_x">'+ l_text +'</span></div>';
				}
			}
			lNode.innerHTML = lStr;
		}
	},
    help_popup: {
        help_node: '',
        init_help: function () {
            if( typeof(site.help_popup.help_node)=='string' ) {
                site.help_popup.help_node = xdbc.load('/xsl/help/se.xml');
            }
        },
        show: function (help_key, srcEl) {

            if( !srcEl ) {
                var srcEl = event.srcElement;
            }
            site.help_popup.init_help();
            // If we werent passed what got clicked, try to find out!
            if( help_key==null ) {
                var parentWindow = getParent(event.srcElement, 'otype', 'window');
                if( parentWindow )
                    var help_key = parentWindow.id;
            }

            if( help_key ) {
                var event_position = getDim(srcEl);
                var help_node = site.help_popup.help_node.selectSingleNode('//help/section[@name="'+help_key+'"]');
                if( help_node && help_node.getAttribute('title') ) {
                    site.help_popup.title.innerHTML = help_node.getAttribute('title');
                    site.help_popup.desc.innerHTML = help_node.text;
                    site.help_popup.desc.style.overflow = 'auto';
                    site.help_popup.desc.style.height = '80px';

                    if( (event_position.t-167)<0 ) {
                        site.help_popup.obj.style.top = (event_position.t+40)+'px';
                        getChild(site.help_popup.obj, 'otype', 'bubble_arrow').className = 'help_bubble_arrow_up';
                        getChild(site.help_popup.obj, 'className', 'help_bubble_shadow').style.display = 'none';
                    }else{
                        site.help_popup.obj.style.top = (event_position.t-167)+'px';
                        getChild(site.help_popup.obj, 'otype', 'bubble_arrow').className = 'help_bubble_arrow';
                        getChild(site.help_popup.obj, 'className', 'help_bubble_shadow').style.display = '';
                    }
                    site.help_popup.obj.style.left = (event_position.l-28)+'px';

                    site.help_popup.obj.style.display = 'block';
                    return false;
                }
            }
            alert('Hoppsan, det finns ingen hjälptext skriven här än!');
            return false;            
        },
        close: function (moved_name) {
            if( !event )
                return;
            var srcEl = event.srcElement;
            var cEl = getParent(srcEl, 'className');                    
            if( cEl ) {
                if( cEl.className!='help_icon' ) {
                    $('help_bubble').style.display = 'none';
                }
            }
        }
    },
    /* Handle printing of iframe pages, module content and widgets. */
    set_iframe_document: function (d) {
         site.iframe_document = d;
    },
    printPage: function() {
         var css = '';
         
         
         /** This code as been generated because IE lallar fett
          *  It loops the frame sets. Works fine in IE8
          */
         if(document.all){
             for(var f=0; f < window.frames.length; f++){
                // Check if this function exists // alt. //if(window.frames[f].print_extend !== undefined ){
                if(typeof window.frames[f].print_extend == 'function'){
                    /** Tested in IE 8 and compatibility view **/
                    window.frames[f].print_extend();
                    return false;
                }
             }
         }
         
         var links = getChildren(site.iframe_document, 'nodeName', 'LINK');
         for( var i = 0; i<links.length; i++ ) {
             if( links[i].getAttribute('rel')=='stylesheet' ) {
                 css+=links[i].outerHTML;
             }
         }

         if( getChild(site.iframe_document.body, 'id', 'printDiv') ){
             content = getChild(site.iframe_document.body, 'id', 'printDiv')
         }else{
             content = site.iframe_document.body.cloneNode(true);
         }

         var scripts = getChildren(content, 'nodeName', 'SCRIPT');
         if( scripts ) {
             for( var i = 0; i<scripts.length; i++ ) {
                scripts[i].parentNode.removeChild(scripts[i]);
             }
         }

         site.printWindow('', css, content.innerHTML, 850, 400);
    },
    printWindow: function(title, css, html, width, height) {
	var url = document.location.toString();
	var protocol = url.substring(0, url.indexOf('/')+2);
	var address = url.substring(protocol.length, url.length);
	var hostname = address.substring(0, address.indexOf('/'));

         var w = window.open('', 'printWindow', 'scrollbars=yes,width='+width+',height='+height);
         w.document.writeln('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head><title>'+title+'</title><link rel="stylesheet" type="text/css" href="'+protocol+hostname+'/include/css/global.css" />'+css+'</head><body class="printWindow">'+html+'</body></html>');
         w.document.close();
         w.print();
    },   
    /* Handle tabs in support popup */
    switch_sub_tab: function () {
         var srcEl = event.srcElement;
         var tLink = getParent(srcEl, 'tlink');
         if (!tLink) return false;
         var frmEl = getParent(srcEl, 'otype', 'frm_tab');
         var tb = getChildren(frmEl, 'tlink');
         for (var i=0; i<tb.length; i++) {
             tb[i].className = (tb[i] == tLink)? 'frm_tab_ttl' : 'frm_tab_ttl_off' ;
         }
         var tb = getChildren(frmEl, 'otype', 'tbody');
         for (var i=0; i<tb.length; i++) {
             tb[i].style.display = 'none';
         }
         getChild(frmEl, 'id', tLink.getAttribute('tLink')).style.display = 'block';
         return false;
    }
};

/**
 * This is the jquery way of interacting with our ledger.
 * Supply your call_back that may look something like: my_test_callback(resp) or
 * write it inline.
 * TODO: Lift this out to a very global place
 *
 * @param post_xml <String> ie [ '<SmsCredit _cmdId="smscredit_01" sys:save="'+quantity+'"></SmsCredit>'
 * @param callback <Function>
 * @param debugging <Boolean> [ optional ]
 *
 */
jledger_call = function(post_xml, call_back, debugging){
    var ledger_location = 'index.php?get=xmlapi';
    var post_xml_full = '<data xmlns:sys="http://www.easybusiness.se/sys" xmlns:docs="http://www.easybusiness.se/docs">'
    + post_xml
    + '</data>';
    if(debugging){
        console.debug('POSTED:'); console.debug( post_xml_full );
    }
    if($j && $j != null){
        // Dont break nothing if jquery is not loaded
        $j.post(ledger_location, post_xml_full, call_back, "xml");
    }
}


var ToV5 = {
    /* Make
     * sure we have a current session, and that the user isnt inactive to long.
    */
    upload_file_iframe: function(form_name, element_id_before_loader_indicator) {
        document.forms[form_name].submit();
        $j('#'+element_id_before_loader_indicator).after('<div id="tmp_spinner_loader"><img src="/include/images/spinner.gif" align="absmiddle"/></div>');
        
        return true;
    },
    /**
     * Called mainly from layout_image_upload_clean.tpl.html
     */
    preview_just_uploaded: function(image_file_name, preview_container_id){
        var img_src = '<img src="/?get=gui&action=get_upload_image&id=' + image_file_name + '&x=180&unique=' + xdbc.uniqId() + '" />';

        $j('#tmp_spinner_loader').remove();
        $j('#id_' + image_file_name + '_preview').html(img_src);
        

        // Depending on what upload.. fill more here as types grow..
        if( image_file_name == 'upload_file_own_bg_image' ) {
            eLayout.set_theme('own_bg');
            $j('#available_themes option[value="own_bg"]').remove();
            
            $j('<option value="own_bg">Egen bakgrund</option>').prependTo('#id_selectbox_place_own_bg');
            $j('#available_themes option[value="own_bg"]').attr("selected","selected");

        } else if( image_file_name == 'layout_header_image' ) {
            eLayout.set_header('custom_image');
            $j('#available_headers option[value="custom_image"]').remove();
            
            $j('<option value="custom_image">Eget sidhuvud</option>').prependTo('#id_selectbox_place_header');
            $j('#available_headers option[value="custom_image"]').attr("selected","selected");
            
        }
        
        ToV5.reload_iframe();
    },
    /**
     * Reload the main iframe
     */
    reload_iframe: function(){

        $j('.workarea iframe').each(function() {
            this.contentWindow.location.reload(true);
        });
    
    }
}



