/* TJ.Admin.ClientSide Editing Module


*/


TJ.Admin.ClientSide = function (){
	var first=true;
	var menu=false;
	var tip=false;
	var win=false;
	var loginWindow=false;

	var AdminWindow=false;
	return {
		initPoweredBy: function(id){
			el= Ext.get(id);
			el.on('contextmenu',TJ.Admin.ClientSide.poweredContext,this);
		},
		poweredContext: function(e,target){
	        e.preventDefault();
			if(!menu) {
				menu=new Ext.menu.Menu( {
					items: [
									{text: 'Login', iconCls: 'icon_user_go', handler: TJ.Admin.ClientSide.loginForm, scope: this}
					]

				});
			}
			menu.show(target);


		},
		loginForm: function(){
			if(! loginWindow){
				loginWindow=new TJ.Admin.LoginForm({
					closable: true,
					callback: function(action){  window.location.reload();}	
					
				});

			}
			loginWindow.show();

		},
		init: function(){
				el = Ext.get('AltiusComponent');
				if(el) {
					preview=el.getAttributeNS('','preview');

					var AltiusButton = new Ext.Toolbar({
						text: 'Tools',
						iconCls: 'icon_cog',
						renderTo: 'AltiusComponent',
						items: [ new TJ.AltiusBtn(),'-',
								new Ext.Button ({
									text: 'Admin',
									iconCls:'icon_application_lightning',
									toolTip:  'Open main administrative screen in a new window',
									handler: function(){ 
											AdminWindow=window.open(TJ.LANGUAGESS +'admin','AltiusAdmin').focus();
									
										}
									, scope: this}),
										'|',

						new Ext.Button ({
									text: 'Show Icons',
									iconCls:'icon_cog',
									enableToggle: true,
									toolTip:  'Toggle display of content editing icons',
									handler: function(){TJ.Admin.ClientSide.toggle();} }),
										'|',
								new Ext.Button ({
									text: 'Preview',
									iconCls:'icon_page_white_magnify',
									enableToggle: true,
									toolTip:  'Toggle display of non-published content',
									pressed: preview,
									handler: function(){TJ.Admin.ClientSide.togglePreview();} }),
										'|',
								new Ext.Button ({
									text: 'Clear Cache',
									iconCls:'icon_page_refresh',
									toolTip:  'Reset system cache',
									handler: function(){
										TJ.Admin.ValidateRequest({url: TJ.LANGUAGESS + 'admin:ClearMainCache'});
											} }),
										'|',
									new Ext.Button ({
									text: 'Logout',
									toolTip:  'Logout',
									iconCls:'icon_user_delete',
									handler: function(){ window.location=TJ.LANGUAGESS + 'user/logout'; } })



						]
//										,						width: 220
					});
				}
		},
		togglePreview: function(){
			TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin:previewmode'});
		},
		toggle: function(){
			spans = Ext.select('.InlineAdmin');
			for(var span=0; span < spans.elements.length;span++){
				if(first){
					el=Ext.get(spans.elements[span]);

					info=Ext.util.JSON.decode(el.getAttributeNS('','info'));
					el.info=info;

					el.toggle();
					el.on('contextmenu',TJ.Admin.ClientSide.display);
					el.on('click',TJ.Admin.ClientSide.display);

				}
				else {
					Ext.fly(spans.elements[span]).toggle();
					if(tip)
						tip.hide();
				}
			}
			first=false;
		},

		display: function(e,el,c){

			e.preventDefault();
			info=Ext.util.JSON.decode(Ext.fly(el).getAttributeNS('','info'));

			if(! tip){

				tip = new Ext.Tip({
				    baseCls: 'x-panel',
					draggable: true,
					closable: true,
					layout: 'fit',
					title: 'Tip here',
					iconCls: 'icon_cog',
					border: true,
					items: grid = new Ext.grid.PropertyGrid({height: 200,		startEditing: Ext.emptyFn}),
					tools: [{ id: 'gear',handler: TJ.Admin.ClientSide.handle}],
					minWidth: 200
				});
			}

			tip.setTitle(info.title);
			tip.showBy(el);
			grid.store.sortInfo = null; 
			grid.getColumnModel().config[0].sortable=false;
			grid.setSource(null);
			grid.body.mask();

			Ext.Ajax.request({ url: TJ.LANGUAGESS + 'admin/client:getpopupinfo',
								params: info,
								callback:  function (a,b,c){ 
									grid.body.unmask();
									val = TJ.Admin.ProcessJSONResponse(a,b,c);
									grid.setSource(val.data);
									grid.comp=val.comp;
								}
				
				
			});
//			menu.show(el);
		},
		handle: function(e){
			if(tip)
				tip.hide();

			if(! win){
				console.log('creating win');
				win = new Ext.Window({
					constrainHeader:true,				
					stateful:true,
					stateId: 'TJ_Admin_Client_Popup',
					maximizable : true,
					title: tip.title,
					width:  800,
					height:  600,
					layout: 'fit',
					closeAction: 'hide'

				});
			}
			if(grid && grid.comp) {
				TJ.Admin.ClearPanel(win);
				win.add(Ext.ComponentMgr.create(grid.comp));
				win.show();
			}
			else
				Ext.MessageBox.alert('Error','Editor not yet defined');
		}
	};


} ();

TJ.SubmitForm=function(e){
	if(Ext.get(e).parent('form'))
		Ext.get(e).parent('form').dom.submit();
	return false;
};

TJ.DumpBoxModel = function(el) {
//	console.log(el);
	el = Ext.get(el);
	var output;
	output = String.format('Div: {0}',el.id);
	console.log(' ');

	console.log('Box Model for:',output, el.dom);


	var functions= ['getWidth','getMargins', 'getBorderWidth','getPadding'];

	Ext.each(functions,function(f) {

		console.log(String.format('{0}: ',f),el[f].call(el,'lr'));

	});


	el.highlight();
	if(el.hasClass('pm_row')) {
			TJ.FixColumnWidths(el);
			TJ.FixColumnHeights(el);
	}

};

TJ.FixColumnWidths= function(row, even) {
			rowInnerWidth =row.getWidth() - row.getBorderWidth('lr') - row.getPadding('lr'); // determine inner width
			cols= row.select('> .pm_column');
			lastCol=null;			
			colWidth=0;
			cols.each(function(c) {
				c.setWidth(c.getWidth());		// This is to round this down.
				colWidth +=(c.getWidth()+ c.getMargins('lr'));
				lastCol=c;
			});
			// update lastCol both smaller and larger as nescessary
			var delta = (rowInnerWidth - colWidth);
			if(even) {
				if(delta !== 0) {
						if(cols.getCount() > 0) {
							var each = Math.floor( delta / cols.getCount());
//							console.log('each',each);
							cols.each(function(c) {
								c.setWidth(c.getWidth() + each);
								delta-=each;
//								console.log('new width',c.getWidth());
							});


					}
				}
			}
//			console.log('remain',delta);
			if(delta !==0) {
				if(lastCol)					lastCol.setWidth(lastCol.getWidth() + delta);
			}




};

TJ.FixColumnHeights = function(row) {
//	return;
		var clean = row.select('.AltiusHeightAdjust');

//		row.select('.AltiusHeightAdjust');
		console.log('toclear',row.select('.AltiusHeightAdjust'));
		clean.removeClass('AltiusHeightAdjust');
		clean.setStyle('min-height','');


		var cols = row.select('> div.pm_column');		// deprecate .pm_column.expandheight-child...
		
		cols.each(function(e) {
//			e.setHeight(e.getHeight());//remove rounding.

			var diff = (e.parent().getHeight(1)) - // Row Content Height
					   ( e.getHeight() + e.getMargins('tb'));	// minus column outer Height.

			if(diff>0) {
//					e.setHeight(e.getHeight() + diff);

					e.setStyle('min-height', String.format('{0}px',e.getHeight(1) + diff));
					e.addClass('AltiusHeightAdjust');
//						e.set('AltiusminHeight',1);


					while(e=e.child('> :last-child')) {
						if ( (e.getStyle('display')=='block') &&
							 ( e.is('div') || e.is('ul') )		)
						{	// recursively update the last child.

//							e.setHeight(e.getHeight(1));
//							e.addClass(String.format('Height_{1}_Diff_{0}',diff,e.getHeight(1)));
							e.setStyle('min-height', String.format('{0}px',e.getHeight(1) + diff));
							e.addClass('AltiusHeightAdjust');
//							e.set('AltiusminHeight',1);
						} else
							break;

					}

			}
		});
};

TJ.ExpandColumns=function(opts){
		opts = opts || { widths: true,
						 heights: true};

		var rows  =Ext.select('div.pm_row');
		var cols;
		// This allows us to fix the deprecated model where we put the expansion on the column level.
		cols = Ext.select(' .pm_column.expandheight-child');
		cols.each(function(e) {
			e.parent().addClass('expandheight');
		});

		rows.each(function(r) {
//			r.on('click',function(e,el) { TJ.DumpBoxModel(el);},r );
			if(opts.widths) {
				if(r.hasClass('expandwidth_last')) {
					TJ.FixColumnWidths(r,false);
				}
				if(r.hasClass('expandwidth_even'))
					TJ.FixColumnWidths(r,true);
			}
			if(opts.heights) {
				console.log('heights!!!');
				if(r.hasClass('expandheight')) {
					TJ.FixColumnHeights(r);
				}
			}

		});
};

TJ.InitTabs = function() {
	var tabSets = Ext.select('div.tabSet');
	tabSets.each(function(ts,e,index) {
		new Altius.Tabset({renderTo: Ext.id(ts)});
	});
	TJ.InitTabs = Ext.emptyFn;	// only call once.
};

TJ.SearchForm = function (){
	var items=Ext.select('.checkboxList label');
	var cb;
	items.each(function(l){
		if(l && l.dom && l.dom.htmlFor) {
			cb=Ext.get(l.dom.htmlFor);
			if(cb) {
				if(cb.dom.checked)
					l.addClass('selected');
				else
					l.removeClass('selected');
				
				cb.labelId = Ext.id(l);
			
				cb.on('click',function(e,cb) {
					Ext.fly(this.labelId).toggleClass('selected');

				},cb);
			}
		}
	});

	items=Ext.select('a.showhide');



	items.each(function(l){
		div = Ext.get(l.getAttributeNS('','ref'));
		if(div) {
//			div.setHeight(div.getHeight());
//			div.setWidth(div.getWidth());
			if (l.hasClass('closed')){
				Ext.emptyFn(); //div.slideOut('t',{useDisplay: true});
			}
		}


		l.on('click',function(e){
			e.preventDefault();
			div = Ext.get(this.getAttributeNS('','ref'));
			if(div){

				if(l.hasClass('closed')){
//					l.dom.innerHTML="&#25B4;";
					l.dom.innerHTML="&#x25b4;";
					div.slideIn('t',{useDisplay: true});
				}else{
//					l.dom.innerHTML="&#25BE;";
					l.dom.innerHTML="&#x25be;";
					div.slideOut('t',{useDisplay: true});
				}
				l.toggleClass('closed');
			}
		},l);
	});


};

TJ.TextSize = function (){
	var sizes=[ 77, 85, 93, 100, 108, 116, 123.1];
	var index=3;
	var larger;
	var smaller;
	var getRule;
	var cookie='textSize2';
	var setSize =  function() {
		index= index % (sizes.length);
		Ext.util.CSS.updateRule('.textSizeBase','font-size',String.format('{0}%',sizes[index]));
		Ext.util.Cookies.set(cookie,index);
	};
	return {
		Init: function() {
			Ext.util.CSS.createStyleSheet(" .textSizeBase { font-size: 100%; } " , 'textSizeBase');
			index=Ext.util.Cookies.get(cookie) || index;
			setSize();


			larger = Ext.get('textLarger');
			if(larger) {
				larger.on('click',function(e,i) {
					index = Math.min(index +1, sizes.length-1);
					setSize();
				});
			}
			smaller = Ext.get('textSmaller');
			if(smaller) {
				smaller.on('click',function(e,i) {
					index = Math.max(index -1,0);
					setSize();

				});
			}
		}
	};
}();

TJ.ShowHide= function() {

	var items;

	items = Ext.select('.ShowSiblingsAndHide');
	items.on('click',function (e,i) {
        e.preventDefault();
		var target = Ext.get(i);
		target.hide();
		while(target = target.prev()) {
			target.show(1);
		}





	});
};


TJ.CSS3 = function(){
	TJ.TextSize.Init();
	TJ.ShowHide();
	TJ.SearchForm();
//	if(! (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) )
	//	return;
	items=Ext.select('ol,ul,tbody,div.pm_row');

	items.each(function(el){
		if(true || Ext.isIE6) {
			child=el.first();
			if(child) {
				child.addClass('first-child');
			}
		}
		if(true ||Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
			child=el.last();
			if(child) {
				child.addClass('last-child');
			}
			evens=el.select(':nth-child(even)');

			evens.each(function(e){
				e.addClass('even');
			});
		}
	});
};

TJ.Menus=function() {
	items=Ext.select('ul.menu.horizontal li.parent, ul.menu.vertical li.parent');

	var width=0;

	items.each(function(li){
		li.select('> ul').each(function(ul){
		/*
			1.  Set the widths of vertical child menus.
			2.  Position vertical menus to the right
			3.  Add fade/slide effect

		*/	


			if(li.parent().hasClass('horizontal')) {
				width=li.getWidth();
			}
			else {
				width=0;
				ul.setStyle('left',li.getWidth() + 'px');
			}

			// assume child menus are all vertical.
			lis=ul.select('> li');			
			lis.each(function(li){
				if (li.getWidth()+li.getBorderWidth('lr')>width)
					width=li.getWidth() + li.getBorderWidth('lr') ;
			});

			ul.setWidth(width + ul.getBorderWidth('lr'));
			lis.each(function(li){
				li.setWidth(width);
			});

			li.on('mouseover',function(){
				if(! ul.disp) {
					ul.stopFx();
					if(ul.getX() + ul.getWidth() > Ext.lib.Dom.getViewWidth()) {
						ul.setX( ul.getX() - (ul.getX()+ul.getWidth() - Ext.lib.Dom.getViewWidth()));
					}
//					ul.slideIn('t',{duration: 0.4});
					ul.fadeIn({duration: 0.4});
				}
				ul.disp=2;
			});
			li.on('mouseout',function(){
				ul.disp=1;
			});

			li.on('mouseout',function(){
				if(ul.disp == 1) {
					ul.stopFx();
//					ul.slideOut('t',{duration: 0.4});
					ul.fadeOut({duration: 0.4});	
					ul.disp=0;
				}
			},this,{buffer:50});
		});
	});


	items=Ext.select('img.YouTubePreview');


	items.each(function(el){

//		console.log('youtubers',el,el.getAttributeNS('','src'));
		var src=el.getAttributeNS('','src');
		el.src1= src;

		el.set({ 
			src1: src,
			src2: src.replace('1.jpg','2.jpg' ),
			src3: src.replace('1.jpg','3.jpg' )
		});

		el.on("mouseover", function(e,t,o){
			var task = {
			    run: function(){
					var src = t.getAttributeNS('','src');
					switch (src)
					{
						case t.getAttributeNS('','src1'):
							t.src=t.getAttributeNS('','src2');
						break;
						case t.getAttributeNS('','src2'):
							t.src=t.getAttributeNS('','src3');
						break;
						default:
							t.src=t.getAttributeNS('','src1');
						break;
					
					}
			    },
			    interval: 1000 //1 second
			};
			Ext.TaskMgr.start(task);
		},this,{single:true});
	});



};



TJ.AutoCaption=function(){




	items=Ext.select('img.autocaption');
//	console.log('stuff',items);
		
	var setPosition=function(caption) {

		console.log('setpos', caption, caption.parent(),caption.parent().next());
		var wrap = caption.parent();

		var el = wrap.next();

		wrap.setWidth(el.getWidth()-el.getPadding('lr') - el.getBorderWidth('lr'));
		wrap.setX(el.getX() + el.getBorderWidth('l') + el.getPadding('l'));
		wrap.setY(el.getY() + el.getBorderWidth('t') + el.getPadding('t'));

		wrap.setHeight(el.getHeight()-el.getPadding('tb') - el.getBorderWidth('tb'));

		console.log('widths',el.getWidth(), wrap.getWidth());



	};

	items.each(function(el){
		caption = el.getAttributeNS('','caption');
		credit  = el.getAttributeNS('','credit');
		text='';
		if(caption) {
			text+='<span class="caption">'+caption+'</span>';
		}
		if (credit) {
			text+='<span class="credit">'+credit+'</span>';
		}
		if(text) {

			var div = Ext.get(Ext.DomHelper.insertBefore(el,{cls:'ImageCaptionWrap',tag:'div'}));
			var captionEl = Ext.get(Ext.DomHelper.append(div,{cls:'ImageCaption',tag:'div',html:text}));
			setPosition(captionEl);

		if(1==1) {
			captionEl.display=0;

			div.on("mouseover", function(e,t,o){
				console.log('options',o,t);
				setPosition(o.caption);

				if(!o.caption.display) {
					o.caption.stopFx().slideIn('b');
				}
				o.caption.display=2;
			},div,{caption: captionEl});

			captionEl.on("mouseover",function(e,t,o){
				if(!o.caption.display) {
					o.caption.stopFx().slideIn('b');
				}
				o.caption.display=2;
			},div,{caption: captionEl});


			captionEl.on("mouseout",function(e,t,o){
				o.caption.display=1;
			},div,{caption: captionEl});

			div.on("mouseout",function(e,t,o){
				o.caption.display=1;
			},div,{caption: captionEl});


			div.on("mouseout",function(e,t,o){
				if(o.caption.display <2) {
					o.caption.stopFx().slideOut('b');
					o.caption.display=0;
				}
			},div,{caption: captionEl, buffer: 500});

			captionEl.on("mouseout",function(e,t,o){
				if(o.caption.display <2) {
					o.caption.stopFx().slideOut('b');
					o.caption.display=0;
				}

			},div,{caption: captionEl, buffer: 500});

	}
		}


	});
};

Ext.namespace('TJ.Twitter');

TJ.Twitter.FeedPreview = Ext.extend(Ext.Component,{
	refreshInterval: 5000,
   initComponent : function(){
        TJ.Twitter.FeedPreview.superclass.initComponent.call(this);
		return;
		/*
        this.addEvents("update");
		this.callbackName = 'TwitterCallback_' + this.conf.id;

		console.log(this.callbackName);
		window[this.callbackName] = function(data) {
			console.log('hello');
			Yourfunction(this,data);


		};
	*/

    },
    onRender: function() {
        TJ.Twitter.FeedPreview.superclass.onRender.apply(this, arguments);
		console.log('TJ.Twitter.Feedpreview',this,this.container,this.getEl());
		this.list = this.container.createChild({cls:'content',tag:'ol'});
		if(this.data)
			this.doPaint(this.data);
		
		this.task = {
			run: function() {
//				console.log('dorun');
//				TJ.LoadScript(String.format('http://twitter.com/status/user_timeline/{0}.json?count={2}&callback={1}',this.conf.userid,this.callbackName,this.conf.count));
//				console.log(String.format('http://twitter.com/status/user_timeline/{0}.json?count={2}&callback={1}',this.conf.userid,this.callbackName,this.conf.count));
			},
			scope: this,
			interval: 20000
		};

//		Ext.TaskMgr.start(this.task);

    },
	doPaint: function(data) {
		for(var i =0 ; i < data.length ; i++){
			var li = this.list.createChild({tag:'li'});
			li.createChild({tag:'p',style:"word-wrap:break-word;"} ).update(data[i].text.parseURL().parseUsername().parseHashtag());
			li.createChild({tag:'p',style:"word-wrap:break-word;", cls:"byline", title:data[i].created_at}).update(TJ.RelativeDate(data[i].created_at));
		}
	},
	TwitterCallback: function(obj){
		console.log('Update Twitter',obj,this);


	}
});


// Add a script tag in order to load a script.  No callback suppport.
TJ.LoadScript = function(url){
    //create element
    var script = document.createElement("script");
    script.type = "text/javascript";
    if(script.readyState){ //for IE
        script.onreadystatechange = function(){
            if(script.readyState == "loaded" || script.readyState == "complete"){
                script.onreadystatechange = null;
//                callBack();
            }
        
        };
    }
    else{ //other browsers
        
        script.onload = function(){
//            callBack();
        };
    }
    
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);

};

String.prototype.parseURL = function() {
//	&#8203 &aacute;
	return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
		return url.link(url);
	});
};

String.prototype.parseUsername = function() {
	return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
		var username = u.replace("@","");
		return u.link("http://twitter.com/"+username);
	});
};

String.prototype.parseHashtag = function() {
	return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
		var tag = t.replace("#","%23");
		return t.link("http://search.twitter.com/search?q="+tag);
	});
};



 Ext.History.init();

 Ext.History.RegisterComponent=function(id) {
		// create a unique id for this component based on the id passed.
	 Ext.History.map=Ext.History.map || {};
	 var x='';
	 while( Ext.History.map[id + x]) {
			x++;
	 }

	 Ext.History.map[id+x]=1;
	 return id+x;

 };
 Ext.History.AltiusAdd=function(comp,hash) {
	 if(comp.length===0){
		 Ext.History.add(hash);
	 } else
		Ext.History.add(comp + ':' + hash);


 }

