define(["dojo/_base/declare","dojo/_base/array","dojo/back","dojox/encoding/base64","dojo/topic","dojo/io-query","dojo/dom", "dojo/dom-construct","dojo/_base/config","dojo/_base/lang"],
	function(declare,array,back,base64,topic,ioQuery,dom,domConstruct,config,lang)
{
	return declare("chy.History", null, {
		windowIDs:[],
		lastUrl:null,
		
		appState:function(url){
			this.histUrl=url;	
		},
		
		constructor: function(args){
	        	console.log("History construct");
	        	declare.safeMixin(this,args);
			
			//init dojo.back.init overwrite
			// prevent reinit
			if(dom.byId("dj_history")){ return; } 
	
			var src = config["dojoIframeHistoryUrl"] || require.toUrl("dojo/resources/iframe_history.html");
			domConstruct.place('<iframe style="border:0;width:1px;height:1px;position:absolute;visibility:hidden;bottom:0;right:0;" name="dj_history" id="dj_history" src="' + src + '"></iframe>',document.body);
				        	
	        	lang.extend(this.appState,{
				back:function(){
					console.log("back was clicked",this.histUrl);
					if (this.histUrl!=null) {
						KPWindowLoad(this.histUrl,'kpwindowb2',false);
					} else {
						location.href=location.href;	
					}
				},
				forward:function(){
					console.log("forward was clicked",this.histUrl);
					KPWindowLoad(this.histUrl,'kpwindowb2',false);
				}
	        		
	        	});
	        	
	        	back.setInitialState(new this.appState(null));	
	        	
	            
	        },
	        
	        doHash:function(url){
	        	console.log("Got hash",url,base64.decode(url));
	        },
	        
	        add:function(url,windowId){
	        	if (array.indexOf(this.windowIDs,windowId)!=-1){
	        		var newHash=base64.encode(url)
	        		if(this.lastUrl!=null  && this.lastUrl!=url){
	        			
	        			back.addToHistory(new this.appState(url),true);
	        		}	
	        		this.lastUrl=url;
	        		console.log("history:" , base64.encode(url),ioQuery.queryToObject(url));
	        	}	
	        }			
	});
});
