////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tab Object
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Represents a Webwag Tab holding Widgets
// 
var Tab = Class.create();
Tab.prototype = {
	
	// Constants
	TAB_MAX_WIDTH : 99.5,

	// constructor
	initialize: function(settings, widgets) {
		if(!settings) {
			return;
		}

		Object.extend(this, settings);
		this.widgets 	= widgets;
		
		// Generate a hash to handle widgets sorting.
		// this.widgetsHash = {};
		// for (var i = 0; i < this.widgets.length; i++) {
		//             this.widgetsHash[this.widgets[i].id] = this.widgets[i];
		//         }

		this.elTabCols 	= new Array();
		
		if (!this.nb_columns) {
			this.nb_columns = 2;
		}
		
		var sizes 		= settings.colsizes;
		this.colsizes 	= sizes ? (sizes.split("|")) : new Array(this.nb_columns);

		var defaultWidth = Tab.prototype.TAB_MAX_WIDTH / this.nb_columns;

		var totalSizes = 0;
		
		for (var i = 0; i < this.nb_columns; i++) {
			sizes = Number(this.colsizes[i]);
			if (isNaN(sizes)) {
				sizes = defaultWidth;
			}

			this.colsizes[i] = sizes;
			totalSizes += sizes;
		}
		// auto correcting colsizes if pb detected
		if (totalSizes > 110 || totalSizes < 90) {
			for (var i = 0; i < this.nb_columns; i++) {
				this.colsizes[i] = defaultWidth;
			}
		}
		
		this.backup();
	},

    _cbContextMenu: function(item) {
        debugEcho("_cbContextMenu", item, this);
        switch (item) {
        case 0:
            this.show();
            this.setEditMode();
            return;
        case 1:
            if (confirm(_("REMOVE_TAB") + "\r\n" + _("CONFIRM")))
                this.remove();
            return;
            break;
        case 2:
            this.addColumn();
            this.resizeColumns();
            return;
        case 3:
            if (confirm(_("REMOVE_COLUMN") + "\r\n" + _("CONFIRM")))
                this.removeColumn();
            return;
            break;
        case 4:
            this.resizeColumns();
            dataHandler.saveTabs([this]);
            return;
            break;
        case 5:
            break;
        }
    },

    setEditMode: function() {
        var ed,
        el = this.elTab.firstChild.firstChild;
        if (this.elMenuButton)
        	this.elMenuButton.style.display = "none";
        var p,t = el.firstChild.data;
        var editQuit;
        el.removeChild(el.firstChild);
        ed = document.createElement("input");
        //ed.setAttribute("maxlength", 28);
        this.elEditInput = ed;
        editQuit = this.evEditQuit.bind(this);
        //this.evEditQuit.bindAsEventListener(ed);
        Event.observe(ed, "blur", editQuit);
        Event.observe(ed, "keypress", function(e) {
            var key = window.event ? event.keyCode: e.keyCode;
            debugEcho("keypress:", key, e);
            if (key == Event.KEY_RETURN || key == Event.KEY_ESC)
                editQuit();
        });
        ed.value = t;
        p = el.parentNode;
        el.appendChild(ed);
        ed.focus();
        this.onEdit=true;
    },

    evEditQuit: function() {
        var p,e,v;
        e=this.elEditInput;
       // v = e.value.substr(0,22);
       // e.value = v;
	   v = e.value;
	   
        p = this.elEditInput.parentNode;
        if(!p)// protecting from quitting edit mode if not activated..
        	return;
        this.elMenuButton.style.display = "";
        this.name = v;
        p.removeChild(this.elEditInput);
        p.insertBefore(document.createTextNode(v), p.firstChild);
       	this.onEdit=false;
        dataHandler.saveTabs([this]);
    },

    _click: function(evt) {
			var id,ct=user.currentTab;
			debugEcho("tab._click: id="+this.id,this);
			//while(target.tagName.toLowerCase()!="li")return;
			id = this.id;
			var tg = evt.target || evt.srcElement;
			debugEcho(evt, "_click:   tag event=" + tg.tagName);
			if (tg.tagName && (tg.tagName.toLowerCase() == "input" || tg.tagName.toLowerCase() == "img"))
					return;
			if(ct.onEdit)
				ct.evEditQuit();

			if (!this.demo && ct==this)
				this.setEditMode();

			this.show();
    },
    // methods
    render: function() {
			debugEcho("Tab.prototype.render: " + this.id + " " + this.name);
			// tab rendering
			var a,d,e,i,m,s,li = document.createElement("div");
			this.elTab = li;
			li.id = "tab" + this.id;
			li.className = "tab";
			s = document.createElement("span");
			s.appendChild(document.createTextNode(this.name));
			
			if (this.demo){
				d = $(document.createElement("div"));
				App.elTabContent.appendChild(d);
				this.elTabZone = d;
			}
			else{
				this.elMenuButton = m = document.createElement("img");
				m.src = "/images/icons/info.gif";
				m.height=9;
				m.width=11;
				s.appendChild(m);
				m.style.cursor = "pointer";
				Event.observe(m, "mousedown",this.tabMenuClick.bindAsEventListener(this));
			}
			a = document.createElement("a");
			a.appendChild(s);
			li.appendChild(a);
			
			if (App.elTabs) {
				App.elTabs.insertBefore(li, App.elAddTab);
				/* edit/click tab */
				this.evClick = Event.observe(li, "click", this._click.bindAsEventListener(this));
			}
    },

    addColumn: function(i) {
    	var i,e;
    	this.nb_columns++;
    	for(i=0;i<this.nb_columns;++i){
    		e=this._getElCol(i);
    		e.show();
    		//if(i!=this.nb_columns-1)
    			//$("colSizer"+i).show();
    	}
    	return;
        var eltab,
        z,
        d = this.elTabZone,
        e = document.createElement("div");
        if(typeof i == "undefined")
        	i = this.nb_columns++;
        e.id = "tabCol" + this.id + "_" + i;
        eltab = e;
        this.elTabCols[i]=$(e);
        e.className = "tabCol";
        if(!this.colsizes)
        	this.colsizes=this.resizeColumns();
        e.style.width = (i < this.colsizes.length ? this.colsizes[i] : parseInt(Tab.prototype.TAB_MAX_WIDTH / this.nb_columns)) + "%";

        d.appendChild(e);
    },

    removeColumn: function() {
        var n,c,e,d,psizer;
        if(!this.nb_columns)
        	return false;
        	this.nb_columns--;
           for (i = 5; i >=this.nb_columns ;--i) {
           	c = this._getElCol(i);
           	c.hide();
        }
        //$("colSizer"+(this.nb_columns-1)).hide();
        this.colsizes.pop();
        this.resizeColumns();
        //dataHandler.saveTabs([this]);
    },
    
    setColumns:function(n){
			var i,j=this.nb_columns,s=n-j;
			i=s/Math.abs(s);
			for(;j!=n;j+=i){
				debugEcho("i="+i+" j="+j+" n="+n);
				this[i>0?"addColumn":"removeColumn"]();
			}
			this.resizeColumns();
			this.removeColSizers();
			this.setColSizers();
			
    },

    resizeColumns: function() {
        var p,e,i,j,s,tz;
		this.colsizes = [];
        s = (Tab.prototype.TAB_MAX_WIDTH / this.nb_columns);
        for (i = 0; i < this.nb_columns; i++) {
                e=this._getElCol(i);
                this.colsizes.push(s);
                e.style.width = s+"%";
        }
    },
		
	setColSizers: function() {
		var i = 0;
		var tab = user.currentTab;

		var handleDragEnd = function (splitPane, event) {
			var parentWidth = $("webwagCol0").parentNode.offsetWidth;
			var j = 0;
			for(j; j< 5; j++){
				tab.colsizes[j] = ($("webwagCol"+j).offsetWidth / parentWidth * 100)
				//$("webwagCol"+j).style.width = tab.colsizes[j] + "%";
			}
			dataHandler.saveTabs([tab]);
		}

		for(i; i<tab.nb_columns-1; i++){
			new SplitPane("webwagCol"+i, tab.colsizes[i], "webwagCol"+(i+1), tab.colsizes[i+1], tab.colsizes[i+1],"tabContentSizer" , { onEnd: handleDragEnd, active: true});
		}
		SplitPane.setAll();
	},
	
	removeColSizers: function(){
		SplitPane.removeAll();
	},

    tabMenuClick:function(evt){
    	var c,d,e,i,m,t,tg,html;
    	tg=evt.target || event.srcElement;
    	d=App.elTabMenu;
    	debugEcho("tabMenuClick evt=",evt,"this",this);
    	this.show();
	if(!d){
		App.elTransLayer = t = document.createElement("div");
		t.className="transLayer";
		
		App.elTabMenu = d = document.createElement("div");
		d.className="tabMenu";
		d.style.display="none";
		html="<img style='float:right;margin:3px' onclick=\"App.tabMenuClose()\" src='"+WWG_STATIC+"images/icons/button_close_over.gif'/>";
		html+="<div id='menuTabCols'><div style='padding:5px; border-bottom:1px ridge #333;'>"+_("COLUMN_NUMBER")+"</div>"+
		"<div style='padding-top:5px; padding-bottom:5px; border-bottom:1px ridge #333;'>"+
'<table class="tabMenuCols"><tr><td><img src="images/tabcol.gif"/><img src="images/tabcol.gif"/><img src="images/tabcol.gif"/><img src="images/tabcol.gif"/></td>\
<td><img src="images/tabcol.gif"/><img src="images/tabcol.gif"/><img src="images/tabcol.gif"/></td>\
<td><img src="images/tabcol.gif"/><img src="images/tabcol.gif"/></td>\
<td><img src="images/tabcol.gif"/></td></tr>\
<tr><td><input type="radio" name="menuTabNbCols" value="4" onclick="App.tmSetNumCol(this)"/>\
</td><td><input type="radio" name="menuTabNbCols" value="3" onclick="App.tmSetNumCol(this)"/>\
</td><td><input type="radio" name="menuTabNbCols" value="2" onclick="App.tmSetNumCol(this)"/>\
</td><td><input type="radio" name="menuTabNbCols" value="1" onclick="App.tmSetNumCol(this)"/>\
</td></tr></table>'+
		"</div></div>";
		html+="<div style='padding:10px;'><input type='button' onclick='App.tmAction(1)' value='"+_("REMOVE")+"'/></div>";
		
		d.innerHTML= html;
		//"<div>SET_ICON</div><hr/><div><img src='images/icons/icons.png'/></div>";
		App.translate(d);
		document.body.appendChild(t);
		document.body.appendChild(d);
		new Effect.BlindDown(App.elTabMenu);
		Event.observe(t,"click",function(evt){
				debugEcho("event on translayer click",evt);
				App.tabMenuClose();
				Event.stop(evt);
			});
	}
	else{
		t=App.elTransLayer;
		d.style.display=t.style.display="block";
	}
	//debugEcho("tg.par pos======== > "+tg+"           px  //   "+tg.parentNode.offsetTop+"px");
	i=Position.cumulativeOffset($(tg));
	d.style.left=i[0]+"px";
	d.style.top=i[1]+"px";
	t.style.width= (Prototype.Browser.IE?document.body.offsetWidth:window.innerWidth)+"px";
	t.style.height=(Prototype.Browser.IE?document.body.offsetHeight:window.innerHeight)+"px";
	
	if (this.search != undefined)
		$("menuTabCols").hide();
	else
		$("menuTabCols").show();

	c=document.getElementsByName("menuTabNbCols");
	i=c.length;
	while(i){
		e=c[--i];
		e.checked= e.value==this.nb_columns;
		//debugEcho("while i="+i,e,e.checked);							
	}
	Event.stop(evt);
    },
    
    highlight: function(st){
    var e;
    	e = this.elTab;
    	if(st){
    		if (App.tabSel == this)
    			return;
    		if(App.tabSel)
    			App.tabSel.highlight(0);
		e.style.border = "1px dotted green";
		App.elTabSel_old_class = e.firstChild.className;
		e.firstChild.className = "tabActive";
		App.tabSel = this;
    	}else
    	{
		e.style.border = "";
		e.firstChild.className = App.elTabSel_old_class;
		delete App.tabSel;
    	}
    },

    show: function(params) {
				var i = 0,e,c,w,i,j,l,p;
				var widgets_visible = [];
				c = App.elTabContent;
        
				if (this.theme && this.theme != user.theme) {
					App.settings.switchCSS(this.theme);
				}
				if(this.demo && this.type!= "search"){
					App.elTabContentTable.hide();
					this.elTabZone.show();
				}
				else{
				// table not visible so a non widget tab is shown, undisplay all of them and show the table widget
				if(App.elTabContentTable.style.display=="none"){
					var els=App.elTabContent.childNodes;
					for(i=0;i<els.length;++i){
						e=els[i];
						if(e.nodeType==1)// 1 == element node
							e.style.display="none";
					}
					App.elTabContentTable.show();
				}
				
				if (!this.rendered) {
					for(i=0;i<6;++i){
						c=this._getElCol(i);
						if(i<this.colsizes.length){
							c.style.width=this.colsizes[i]+"%";
							c.style.display="";
						}else
							break;
						j=0;
						while ((e = c.childNodes[j++]))
								e.style.display = "none";
					}
					this.renderWidgets();
				}
				for(i=0;i<6;++i){
					c=this._getElCol(i);
					if(i>=this.nb_columns){
						c.hide();
						//if(i<5)
						//	$("colSizer"+i).hide();
						continue;
						}
						c.style.width=this.colsizes[i]+"%";
						c.style.display="";
						j=0;
			 			while ((e = c.childNodes[j++])) {
			 				if (e.widgetId){
								e.style.display = user.getWidgetById(e.widgetId).getValue("tab") == this.id  ? "": "none";
								if (user.getWidgetById(e.widgetId).getValue("tab") == this.id)
									widgets_visible.push(e.widgetId)
							}
							else if (e.nodeType == 1 && e.getAttribute("wwg_tab")) {
								e.style.display = e.getAttribute("wwg_tab") == this.id  ? "": "none";
							}
						}
						
						//if(i<5)
						//	$("colSizer"+i).show();
			 			if(i==this.nb_columns-1){
			 			//debugEcho("||||||||||||||||||||||||||||||||          nbc="+this.nb_columns+"   colSizer"+i);
			 				//$("colSizer"+i).hide();
						}
						
				}
			}// endif demo
			if (user.currentTab) {
					$(user.currentTab.elTab.firstChild).removeClassName("tabActive");
			}
			if (this.elTab) {
				$(this.elTab.firstChild).addClassName("tabActive");
			}
			user.currentTab = this;
			App.setCookie();
			if (App.elTabContent.style.display != "none") {
				this.removeColSizers();
				this.setColSizers();
			}
			
			if (widgets_visible.length > 0)
				new Ajax.Request("/user/open_tab?widgets="+widgets_visible.join("|"),{onComplete : null, onException: DataHandler.handleAjaxException});
    },

    refresh: function(){
    	var ws=this.getWidgets();
    	for(i=0;i<ws.length;i++){
    		ws[i].refresh();
    	}
    },

    renderWidgets: function() {		
        if (this.rendered) {
			return false;
		}
		for (var i = 0; i < this.widgets.length; i++) {
            this.widgets[i].render(true);
        }
        this.rendered = true;
    },


    _getElCol: function(i) {
        //return $("tabCol" + this.id + "_" + i);
        //return this.elTabCols[i];
        return $("webwagCol"+i);
    },

    addWidget: function() {},

    backup: function() {
        this.bak = Object.clone(this);
        this.bak.colsizes = this.colsizes.clone();
    },

    save: function() {
    	dataHandler.saveTabs([this]);
    },

    toXML: function() {
        var i,j,v,xml = "",t,
        props = ["position", "nb_columns", "name", "colsizes"];
        for (i = 0; i < props.length; i++) {
            v = props[i];
            if (v != "colsizes"){
            	if (this.bak[v] != this[v])
                	xml += v + "=\"" + String(this[v]).encodeXML() + "\" ";
            }
            else{
		if (this.colsizes.join("|") != this.bak.colsizes.join("|")){
			for(t=[],j=0;j<this.nb_columns;++j)// limits each columns percent at 6 digits
				t.push(Number(String(this.colsizes[j]).substr(0,7)));
			xml += "colsizes=\""+t.join("|")+"\" ";
		}
            }
        }
        if (xml)
            return "<tab id=\"" + this.id + "\" " + xml + "/>";
        return "";
    },

    remove: function() {
			var w;
			var _this = this;
			if(user.currentTab==this)
				user.tabs[0].show();
				
        /*
        for (w in this.widgets)
            if (typeof this.widgets[w] == "object")
            this.widgets[w].remove();
         */
			if(this.demo && this.elTabZone)
				this.elTabZone.parentNode.removeChild(this.elTabZone);
			if(!this.demo)
				dataHandler.removeTab(this.id);
			if (this.type == "search")
				user.searchTab = null;
				 
			// we don't remove each widget by calling theirs remove methods (tab suppr cause all widgets removed from account)
			// so we try to simulate the removing...
			this.elTab.parentNode.removeChild(this.elTab);
			//this.elTabZone.parentNode.removeChild(this.elTabZone);
    },
// return an array of the widgets' tab 
    getWidgets: function(){
    var w,ind,widgets=[];
		for(ind in global.widgets){
			w = global.widgets[ind];
			if(w.prefs.tab.value==this.id && w.prefs._compatibility.value.indexOf("web")!=-1){
				widgets.push(w);
			}
		}
	return widgets;
    }
    // End methods

};



Renderer.prototype.makeTabsSortable = function() {
	// for avoiding the possibility of dragging the false  tab 'add tab'
	debugEcho("Renderer.prototype.makeTabsSortable: BEGIN");
    App.elAddTab.parentNode.removeChild(App.elAddTab);
    this._dragTabs = 
    Sortable.create(App.elTabs, {
        constraint: false,
        format: /(.*)/, // Sortable needs aa special id format,  this fix permit to makes sortables compatible with our id format.
        tag: "div",
        overlap: "horizontal",
        onUpdate:function(){debugEcho("Sortable.create:  onUpdate");Renderer.onEndDrag();}
    });
    App.elTabs.appendChild(App.elAddTab);
};

Renderer.onEndDrag = function(e) {
    //jQuery.iAutoscroller.stop();
    var tid,t,i,j,n,idx,s,nt = [];
    debugEcho("Renderer.prototype.onEndDrag: this,e", this,e, "-----");
    App.elTabs.appendChild(App.elAddTab);
    s = App.elTabs.childNodes;
    for (i = idx = 0; i < s.length; ++i) {
        t = s[i];
        if (!t.id)
        continue;
        tid = t.id.replace(/[^0-9]/g, "");
        debugEcho(tid);
        for (j = 0; j < user.tabs.length; ++j) {
            if (user.tabs[j].id == tid) {
                user.tabs[j].position = idx++;
                nt.push(user.tabs[j]);
                break;
            }
        }
    }
    debugEcho("new tabs arrangement:",nt);

    user.tabs = nt;
    dataHandler.saveTabs(nt);

    // dirty fix for avoiding activation of edtion mode after dragging
    setTimeout(function(){
    	var t=user.currentTab;
    	if (t.elEditInput)
    		t.evEditQuit();
    	},50);
};


// tab menu
Object.extend(App,{
	tmSetNumCol: function(el){
	 var c=0,i,n=el.value,t=user.currentTab,ws,wl,w,wToMove=[];
	 ws=t.getWidgets();
	 wl=ws.length;
	 	for(j=0;j<wl;j++){
	 		w=ws[j];
	 		c=w.getValue("column")||0;
	 		debugEcho("t.nb_columns="+t.nb_columns+"n="+n+" ===>"+w.src+"\t\t\t c="+c);
	 		if(c>n-1){
	 			debugEcho("tomove:"+w.id+"\t\t"+w.src+"\t\t\tcol="+c);
	 			wToMove.push(w);
	 		}
	 	}
	if(wToMove.length){
 		if(!confirm(_("WIDGETS_NEEDS_DISPLACEMENT")))
 			return;
 		for(i=0;i<wToMove.length;++i){
			t._getElCol(n-1).appendChild(wToMove[i].elWidgetBox);
			wToMove[i].setValue("column",n-1);
 		}
 	}
	t.setColumns(n);
	dataHandler.saveWidgets(global.widgets, true);
	t.show();
	t.save();
	return;	 
	},

	tmAction:function(i){
		user.currentTab._cbContextMenu(i);
		if(i==1)// removing, so delete the tabMenu 
			App.tabMenuClose();
	},
	
	loadSearch : function (el) {
		var doc = el.contentWindow.document;
		el.height = doc.body.scrollHeight;
		doc.forms["gs"].action = "/search/custom";
		var as = doc.getElementsByTagName("a");
		var i = 0;
		var href = "";
		
		for (i; i < as.length; i++) {
			href = as[i].href;
			
			if (as[i].href.match("/custom") == null)
				as[i].setAttribute("target","_blank");
			if (as[i].href.match("/custom") != null) {
				as[i].href = as[i].href.replace("/custom","/search/custom")+"#ap";
			}
			if (as[i].href.match("/aclk") != null) {
				as[i].href = as[i].href.replace("/aclk","/search/aclk");
				as[i].parentNode.onclick = function() {};
			}
		}
	},
	
	tabMenuClose:function(){
		//App.elTransLayer.style.display=App.elTabMenu.style.display='none';
		App.elTransLayer.style.display='none';
		new Effect.BlindUp(App.elTabMenu);
	}
});

