function paintAddTabButton()
{
	var tabList = dojo.byId("topTabs_tablist");
	var addDiv1 = createElement("addTab", "div");
	addDiv1.setAttribute('class', 'dijitTab');
	addDiv1.className = 'dijitTab';
	addDiv1.style.margin = "1px";
	var addDiv2 = createElement("addTab2", "div");
	addDiv2.setAttribute('class', 'dijitTabInnerDiv');
	addDiv2.className =  'dijitTabInnerDiv';
	addDiv2.style.padding = "2px";
	var addDiv3 = createElement("addTab3", "div");
	addDiv3.setAttribute('class', 'dijitTabContent tabLabel');
	addDiv3.className = 'dijitTabContent tabLabel';
	addDiv3.innerHTML = "Add More";
	addDiv2.appendChild(addDiv3);
	addDiv1.appendChild(addDiv2);
	tabList.appendChild(addDiv1);
	dojo.connect(addDiv1, 'onclick', "showTabForm");
}

function showTabForm()
{
	showAddTab();
	var categoryBox = dijit.byId('addCategoryDropDown');
	if (!categoryBox)
	{
		categoryBox = new dijit.form.ComboBox({
											id:"addCategoryDropDown",
											name:"addCategoryDropDown",
											autoComplete:true,
											store: categoryStore,
											searchAttr:"title",
											hasDownArrow:false,
											style:"width:250px;"
									}, dojo.byId("addCategoryDropDownDiv"));
	}
	else
	{
		categoryBox.store = categoryStore;
		categoryBox.setValue("");
	}

	var urlBox = dijit.byId('url');
	if (urlBox)
	{
		urlBox.setValue('http://www.');
	}

	var titleBox = dijit.byId('title');
	if (titleBox)
	{
		titleBox.setValue('');
	}

	dojo.byId('addTabErrorMessage').innerHTML = "";
	dojo.byId('addTabErrorMessage').style.display = 'none';
}

function showAddTab()
{
	dijit.byId('optionsDialog').show();
}

function updateTitle()
{
	var text = dojo.byId("url").value;
	var firstDot = text.indexOf(".") + 1;
	text = text.substring(firstDot);
	var secondDot = text.indexOf(".");
	dojo.byId("title").value = text.substring(0, secondDot);
}

function addTab()
{
	dojo.byId('addTabErrorMessage').innerHTML = '<img src="/static/img/loading.gif">';
	dojo.byId('addTabErrorMessage').style.display = 'block';
	var url = dojo.string.trim(dojo.byId('url').value);
	var title = dojo.string.trim(dojo.byId('title').value);
	var addCategoryObj = dijit.byId('addCategoryDropDown');
	var categoryId = "";
	// dojo-1.1 bug: item will be null when user is just typing, and category get filled.
	// in this case we get the displayedValue and make sure that it is not
	// one of the categories already existing.
	var categoryLabel = addCategoryObj.getDisplayedValue();
	var catObj = getCategoryObjByName(categoryLabel);
	if (catObj != null)
	{
		categoryId = catObj.id;
	}

	var categoryTitle = addCategoryObj.getValue();
	if (url == "" || url == "http://www.")
	{
		dojo.byId('addTabErrorMessage').innerHTML = "Please enter URL.";
		dojo.byId('addTabErrorMessage').style.display = 'block';
		return false;
	}

	if (categoryTitle == '')
	{
		dojo.byId('addTabErrorMessage').innerHTML = 'Please select category.';
		dojo.byId('addTabErrorMessage').style.display = 'block';
		return false;
	}

	if (title == '')
	{
		dojo.byId('addTabErrorMessage').innerHTML = 'Please enter title.';
		dojo.byId('addTabErrorMessage').style.display = 'block';
		return false;
	}

	dojo.byId('addUrlTitle').value = title;
	dojo.byId('addUrl').value = url;
	dojo.byId('addUrlCategoryTitle').value = categoryTitle;
	dojo.byId('addUrlCategoryId').value = categoryId;

	if (categoryId == '')
	{
		addDSCategory();
	}
	else
	{
		addDSTab(categoryId, null);
	}

	var addedTabObj = addFrontTab(url, title);
	return true;
}

function addDSCategory()
{
	var urlData = "/cat?s=102&a=a";
	dojo.xhrGet({
		url: urlData,
		handleAs: 'json',
		preventCache: true,
		form: 'addUrlForm',
		load: function(response, ioArgs) {
			var accordian = dijit.byId('leftAccordion');
			dojo.byId('addUrlCategoryId').value = response.id;
			updateCategoryStore(response.id, response.title);
			var category = new Category(response.id, response.title);
			category.paint();
			accordian.startup();
			accordian.resize();
			dijit.byId('left1').resize();
			dijit.byId('left1').startup();
			accordian.selectChild(categoryArray[categoryArray.length - 1].uid);
			setTimeout(function (){addDSTab(response.id, response);}, 2, response);
		},
		error: function(response, ioArgs) {
			dojo.byId('addTabErrorMessage').innerHTML = response.responseText;
			dojo.byId('addTabErrorMessage').style.display = 'block';
			showAddTab();
			return response;
		}
	});
}

function addDSTab(categoryId, categoryResponse)
{
	var urlData = "/tab?s=102&a=a";
	dojo.xhrGet({
		url: urlData,
		handleAs: 'json',
		preventCache: true,
		form: 'addUrlForm',
		load: function(response, ioArgs) {
			setTimeout(function(){reloadCategory(categoryId);}, 2, categoryId);
		},
		error: function(response, ioArgs) {
			dojo.byId('addTabErrorMessage').innerHTML = response.responseText; 
			dojo.byId('addTabErrorMessage').style.display = 'block';
			showAddTab();
			return response;
		}
	}, categoryResponse, categoryId);
}

function reloadCategory(catId)
{
	var catObj = getCategoryObjById(catId);
	if (catObj)
	{
		catObj.reload();
	}
}

function addFrontTab(url, title, isSearchTab)
{
	if (!isSearchTab)
	{
		isSearchTab = false;
	}

	var tabList = dojo.byId("topTabs_tablist");
	var addDiv = dojo.byId("addTab");
	tabList.removeChild(addDiv);
	if (!isSearchTab && url.indexOf("http://") == -1 && url.indexOf("https://") == -1)
	{
		url = "http://" + url;
	}

	var tab_id = "tab" + tabCount;
	var anotherTab = new Tab(tab_id, title, url, true, isSearchTab);
	anotherTab.paint();
	anotherTab.display();
	paintAddTabButton();
	return anotherTab;
}

function openTab(id, title, url, searchUrl)
{
	var parentTab;
	for (var i = 0; i < tabObjArray.length ; i++)
	{
		var tabObj = tabObjArray[i];
		if (tabObj.id == id)
		{
			parentTab = tabObj;
			break;
		}
	}

	if (parentTab)
	{
		id = id + "_" + parentTab.childCount;
		parentTab.childCount++;
	}

	var newTab = new Tab(id, title, url, true);
	if (searchUrl && searchUrl != "")
	{
		newTab.searchUrl = searchUrl;
	}

	var addDiv = dojo.byId("addTab");
	var tabList = dojo.byId("topTabs_tablist");
	tabList.removeChild(addDiv);
	newTab.paint();
	newTab.display();
	paintAddTabButton();

	if (!parentTab)
	{
		newTab.updateDS(true);
	}
}

var gblSearchId = 0;
function Tab(id, title, url, closable, isSearchTab, tabContainer, isVerticalTab)
{
	this.id = id;
	this.title = title;
	this.url = url;
	this.closable = closable;
	this.adData = "";
	this.searchUrl = "";
	this.childCount = 0;
	this.isSearchTab = isSearchTab;
	this.tabContainer = tabContainer;
	this.isVerticalTab = isVerticalTab;
	this.searchId = gblSearchId++;
	this.parentSearchObj = "";

	if (dojo.isIE)
	{
		this.loadedEarlier = true;
	}

	this.paint = function(){

	    var tabContainer;
		if (this.tabContainer)
		{
			tabContainer = this.tabContainer;
		}
		else
		{
			tabContainer = dijit.byId("topTabs");
		}

		this.tabObj = new dijit.layout.ContentPane({id:this.id, title:this.title, closable:this.closable, style:"overflow:hidden;"});
		
		this.tabTable = dojo.doc.createElement('table');
		this.tabTable.style.width = "100%";
		this.tabTable.style.height = "100%";
		if (dojo.isIE)
		{
			this.tabHead = dojo.doc.createElement('thead');
			this.tabTable.appendChild(this.tabHead);
		}
		else
		{
			this.tabHead = this.tabTable;
		}

		this.tr1 = dojo.doc.createElement('tr');
		this.td1 = dojo.doc.createElement('td');
		this.tr1.appendChild(this.td1);
		this.tabHead.appendChild(this.tr1);

		this.tr2 = dojo.doc.createElement('tr');
		this.td2 = dojo.doc.createElement('td');
		this.td2.style.width = "100%";
		this.td2.style.height = "100%";
		this.tr2.appendChild(this.td2);
		this.tabHead.appendChild(this.tr2);
		
		this.adDivObj = createElement(this.id + "_ad_div", "div");
		this.adDivObj.innerHTML = ""; //"Ads Here.............";
		this.td1.appendChild(this.adDivObj);

		this.divObj = createElement(this.id + "_div", "div");
		this.divObj.style.width="100%";
		this.divObj.style.height="100%";
		this.divObj.style.border = "0";
		this.divObj.style.overflow = "hidden";

		//adding divObj to table
		this.td2.appendChild(this.divObj);

		this.tabObj.setContent(this.tabTable);
		tabContainer.addChild(this.tabObj);
		if (this.tabObj.controlButton)
		{
			dojo.connect(this.tabObj.controlButton.domNode, 'onclick', this, 'selected')
		}
		if (this.closable && !this.isSearchTab)
		{
			dojo.connect(this.tabObj, 'onClose', this, 'close')
		}
		//adding tab to tab container
		tabObjArray[tabObjArray.length] = this;
		tabCount++;
		tabContainer.resize();
		dojo.connect(dojo.byId(this.id), 'onmouseover', this, 'mouseOver');
		dojo.connect(dojo.byId(this.id), 'onmouseout', this, 'mouseOut');
		if (!this.isVerticalTab && !this.isSearchTab)
		{
			this.searchBox = new SearchBox(this);
			this.searchBox.paint();
		}
	}

	this.mouseOver = function (){
		message = this.title + message2;
	}

	this.mouseOut = function (){
		message = "";
	}

	this.close = function (event){
		this.updateDS(false);
	}

	this.updateDS = function(isOpen){
		if (this.tabContainer)
		{
			return;
		}

		var a = "";
		if (isOpen)
		{
			a = "open";
		}
		else
		{
			a = "close";
		}

		var urlData = "/tab?s=104&a=" + a + "&t=" + this.id;
		dojo.xhrGet({
			url: urlData,
			handleAs: 'json',
			preventCache: true,
			load: function(response, ioArgs) {
				return response
			},
			error: function(response, ioArgs) {
				// show error only if user is trying to open a new tab.
				if (isOpen)
				{
					alert("Oops!!! Our server is bad and didn't like what you were trying to do.\n Please let us know to make server good enough to serve you well.");
				}
				return response;
			}
		}, isOpen);
	}

	this.selected = function (event){
		if (this.parentSearchObj)
		{
			this.parentSearchObj.bkToResDivSpan.style.display = "none";
		}

		if (this.bkConnectObj)
		{
			this.backConnectAndShow();
		}

		// creating iframe for the div within the tab.
		if (this.iframeObj || this.isSearchTab)
		{
			return;
		}
		
		this.iframeObj = createElement(this.id + "_iframe", "iframe");
		this.mouseOver();
		if (this.isVerticalTab)
		{
			this.iframeObj.setAttribute("src", this.searchUrl);
		}
		else
		{
			this.iframeObj.setAttribute("src", this.url);
		}

		this.iframeObj.style.width="100%";
		this.iframeObj.style.height="100%";
		this.iframeObj.style.border = "0";
		this.iframeObj.frameBorder = "0";
		//this.iframeObj.onreadystatechange = stateChanged;
		this.divObj.appendChild(this.iframeObj);
		if (this.isVerticalTab)
		{
			if (dojo.isIE)
			{
				dojo.connect(this.iframeObj, 'onreadystatechange', this, 'onLoadIE');
			}
			else
			{
				dojo.connect(this.iframeObj, 'onload', this, 'onLoad');
			}
			
			//dojo.connect(this.newSearchDivSpan, 'onclick', this, 'backToNewSearch');
		}
		// selecting tab to show up.
		//tabContainer.selectChild(tab1);
	}

	this.reloadUrl = function (){
		this.loadedEarlier = false;
		dojo.disconnect(this.bkConnectObj);
		this.bkConnectObj = null;
		this.parentSearchObj.bkToResDivSpan.style.display = "none";
		this.iframeObj.setAttribute("src", this.searchUrl);
	}

	this.backToNewSearch = function (){
		dijit.byId('dtabKeyword').setValue('');
		dijit.byId("topTabs").selectChild(dijit.byId('centerPane'));
	}

	this.onLoadIE = function (event){
		if (this.iframeObj.readyState == 'loading')
		{
			if (this.loadedEarlier)
			{
				this.backConnectAndShow();
			}
			else
			{
				this.loadedEarlier = true;
			}
		}
	}

	this.onLoad = function (event){
		if (this.loadedEarlier)
		{
			this.backConnectAndShow()
		}
		else
		{
			this.loadedEarlier = true;
		}
	}

	this.backConnectAndShow = function (){
		if (this.parentSearchObj.bkConnect)
		{
			dojo.disconnect(this.parentSearchObj.bkConnect);
		}

		this.bkConnectObj = dojo.connect(this.parentSearchObj.bkToResDivSpan, 'onclick', this, 'reloadUrl');
		this.parentSearchObj.bkConnect = this.bkConnectObj;
		this.parentSearchObj.bkToResDivSpan.style.display = "block";
	}

	this.display = function(){
	    var tabContainer;
		if (this.tabContainer)
		{
			tabContainer = this.tabContainer;
		}
		else
		{
			tabContainer = dijit.byId("topTabs");		
		}

		tabContainer.selectChild(this.tabObj);
		this.selected();

	}

	this.checkUrlChange = function (){
		var iObj = this.iframeObj;
		var t = 1;
		//alert("check url: " + this.iframeObj.src);
		//setTimeout("checkUrlChange('" + this.id +"')",5000);
	}

	this.destroy = function (){
		if (this.tabContainer)
		{
			this.tabContainer.removeChild(this.tabObj);
		}
		else
		{
			dijit.byId("topTabs").removeChild(this.tabObj);
		}
	}
}

function deleteAllTabs()
{
	for (var i =0; i < tabObjArray.length; i++)
	{
		tabObjArray[i].destroy();
	}

	var tabList = dojo.byId("topTabs_tablist");
	var addDiv = dojo.byId("addTab");
	if (addDiv)
	{
		tabList.removeChild(addDiv);
	}
}

function checkUrlChange(id)
{
	for (var i = 0; i < tabObjArray.length; i++)
	{
		var tabObj = tabObjArray[i];
		if ( tabObj.id == id)
		{
			tabObj.checkUrlChange();
		}
	}
}

function getTabObjById(id)
{
	for (var i = 0; i < tabObjArray.length; i++)
	{
		var id1 = tabObjArray[i].id;
		var catId = id1.toString();
		if (catId == id)
		{
			return tabObjArray[i];
		}
	}
}

function createElement(id, type)
{
	if (type == 'div')
	{
		var obj = document.createElement('div'); // create dynamically div tag
		obj.setAttribute('id',id);       //give id to it
		return obj;
	}
	else if (type == 'iframe')
	{
		var obj = document.createElement('iframe'); // create dynamically div tag
		obj.setAttribute('id',id);       //give id to it
		return obj;
	}
	else if (type == 'table')
	{
		var obj = document.createElement('table'); // create dynamically div tag
		obj.setAttribute('id',id);       //give id to it
		return obj;
	}
}
