/*******************************************************************************
 * Copyright (c) 2007 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
dojo.provide("cosmos.widget.BIRTContainer");


 dojo.widget.defineWidget(
	'cosmos.widget.BIRTContainer',
	dojo.widget.HtmlWidget,
	{
		widgetClass:'cosmos:BIRTContainer',
		widgetId: "birtcontainer",
		// width
		width : "100%",
		// height
		height : "400",
		content_provider: "",
		postCreate: function(){
			//call superclass
			cosmos.widget.BIRTContainer.superclass.postCreate.apply(this, arguments);
		  	dojo.event.topic.subscribe("initializeWidget", this, "initWidget");				
			
		},		
		initWidget: function(styles){
			initParam = styles.getStyles()[this.widgetClass];
		    this.topic = initParam.topic;
		    this.handler = initParam.handler;
			dojo.event.topic.subscribe(this.topic, this, "refreshContent");	
			dojo.debug("initalizing birt container "  + this.id);	
		},		
		URLEncode: function(sStr) {
		    return escape(sStr)
       			.replace(/\+/g, '%2B')
          			.replace(/\"/g,'%22')
             			.replace(/\'/g, '%27');
  		},			
	    refreshContent:function(contextMap) {
	    	if (typeof(contextMap) != 'undefined'){
		  	//should add a javascript method that will render itself and make a call
			//back to the server.  It will get the context from a queue.			
				resourceContext = contextMap['RESOURCE_CONTEXT'];	
				type = this.URLEncode(contextMap['REPORT_TYPE']);	
				datasource = this.URLEncode(contextMap['DATASOURCE_KEY']);	
			}
			//make REST call to get content data
	    	if ((typeof(resourceContext) != 'undefined') && (typeof(type) != 'undefined')){
	    	dojo.debug( this.handler+"&context="+resourceContext+"&type="+type+"&datasource="+datasource);
				dojo.io.bind({changeit : this.changeit,
					widgetId: this.widgetId,
					url: this.handler+"&context="+resourceContext+"&type="+type+"&datasource="+datasource,    
					load: function(type, data, evt){
						this.changeit(data, this.widgetId);						 
					 },    
				 error: function(type, error){
				 	dojo.debug(error.message);
				 },
					mimetype: "text/plain"
				});											
			}
			else{
			//reset page
				this.changeit(this.blankPath, this.widgetId);
			}
	    },
		changeit:function(url, id){
  			document.getElementById(id).src=url;
		},
	    
		// definitions
		templatePath : new dojo.uri.Uri('', 'cosmos/widget/html/BIRTContainer.html'),
		blankPath : new dojo.uri.Uri('', 'cosmos/widget/html/blank.html')
	}
);
