Divo.app.PortalManager = function() {
	// ----------------- private properties ----------------------
	var NewsUrls = new Array();
	NewsUrls[0] = "";
	NewsUrls['news_1'] = "Blocks/newsblock.php?catid=26";
	//NewsUrls[1] = "test.html";

	NewsUrls['news_2'] = "Blocks/newsblock.php?catid=26";
	NewsUrls['news_3'] = "Blocks/newsblock.php?catid=27";
	NewsUrls['news_4'] = "Blocks/newsblock.php?catid=25";

	NewsUrls['lifestyle_1'] = "Blocks/lifestyleblock.php?catid=26";
	NewsUrls['lifestyle_2'] = "Blocks/lifestyleblock.php?catid=26";
	NewsUrls['lifestyle_3'] = "Blocks/lifestyleblock.php?catid=27";
	NewsUrls['lifestyle_4'] = "Blocks/lifestyleblock.php?catid=25";

	var FeaturedUrls = new Array();
	FeaturedUrls[0] = "";
	FeaturedUrls[1] = "Blocks/videoblock.php";

		function addTab(tabid, tabTitle, targetUrl, itemtabs){
			itemtabs.add({
			title:tabTitle,
			id : tabid,
  			 autoWidth:true,
			autoLoad: {url: targetUrl}
		}).show();
		}

		function addTabItem(tabid, tabTitle, targetUrl, itemtabs){
			itemtabs.add({
			title:tabTitle,
			tabTip : tabTitle,
			id : tabid,
			autoWidth:true,
			trackMouse:true,
			autoLoad: {url: targetUrl}
		});
		}
    function onItemCheck(item, checked){
						//Ext.Msg.alert('Message',item.caturl);

		if(checked)
		{
				var myflg = 0;
				for(var i=0;i<eval(item.maintab).items.length;i++)
				{


					var tab = eval(item.maintab).getItem(i);
					if(tab.id == item.id)
					{
						//Ext.Msg.alert('Message',tabs.id);
						myflg = 1;
						break;
					}
				}
					if(myflg == 0)
					{
						addTab(item.id, item.text, item.caturl, eval(item.maintab));
					}

		}
		else
		{


				for(var i=0;i<eval(item.maintab).items.length;i++)
				{


					var tab = eval(item.maintab).getItem(i);
						//Ext.Msg.alert('Message',tab.id);

					if(tab.id == item.id)
					{
						//Ext.Msg.alert('Message',tab.title);
						myflg = 1;
           				 eval(item.maintab).remove(tab, true);
						break;
					}
				}


		}
    }



    var menu = new Ext.menu.Menu({
        id: 'mainMenu',
		//defaultAlign : 'left',
		//subMenuAlign : 'right',
        items: [
            {
				id : 'news_2',
                text: '?IEC? ???',
				maintab : 'tabs',
                checked: true,
                checkHandler: onItemCheck
            },
            {
				id : 'news_3',
                text: '?IEC? ??E?E',
				maintab : 'tabs',
                checked:true,
                checkHandler: onItemCheck
            },
 			{
				id : 'news_4',
				maintab : 'tabs',
                text: '?IEC? ?C???E',
                checked:true,
                checkHandler: onItemCheck
            }
        ]
    })

    var lifestyle_menu = new Ext.menu.Menu({
        id: 'lifestyle_mainMenu',
		//defaultAlign : 'left',
		//subMenuAlign : 'right',
        items: [
            {
				id : 'lifestyle_2',
                text: '?IEC? ???',
				maintab : 'LifeStyleTabs',
                checked: true,
                checkHandler: onItemCheck
            },
            {
				id : 'lifestyle_3',
                text: '?IEC? ??E?E',
				maintab : 'LifeStyleTabs',
                checked:true,
                checkHandler: onItemCheck
            },
 			{
				id : 'lifestyle_4',
				maintab : 'LifeStyleTabs',
                text: '?IEC? ?C???E',
                checked:true,
                checkHandler: onItemCheck
            }
        ]
    })


		Ext.menu.Menu.prototype.load = function( options, tabs ){
			var loader = new Ext.menu.Item({text: 'Loading...'});
			var conn = new Ext.data.Connection();
			
			this.addItem(loader);
			
			conn.on('requestcomplete', function( conn, response ){
				this.remove(loader);
				response = Ext.decode(response.responseText);
				tabs.activeTab = 0;
				tabs.autoWidth = true;
				tabs.resizeTabs = true;
				tabs.minTabWidth = 130;
				//tabs.tbar = [{ text:'E?I??',  menu: menu_test }];
				tabs.frame = false;
				tabs.enableTabScroll = true;
				tabs.autoHeight = true;
				tabs.defaults = {autoHeight: true};
				Ext.each( response.menu, function( item ){ 

					//Ext.MessageBox.alert('my msg', tabs.id);
					item.checkHandler = onItemCheck;
					this.add( item );
					addTabItem(item.id, item.text, item.caturl, tabs);

				}, this);
				var tab = tabs.getItem(tabs.items.length-1);
				tab.show();
			}, this);
			
			conn.on('requestexception', function(){
				this.remove(loader);
				this.add({text: 'Failed to load menu items'});
			}, this);
			
			conn.request( options );
		}

	


 var Blogs_Tabs = new Ext.TabPanel({
		id				: 'blogsTabs',
		text			: '',
		toolbarLocation	: 'left',
        activeTab		: 1,
        autoWidth:true,
        resizeTabs:true, // turn on tab resizing
        minTabWidth: 100,
        frame			: false,
		enableTabScroll	: true,
        defaults		: {autoHeight: true, autoWidth : true},
        items			:[
			{id : 'blog_3', title: '<h2>عائلات مصر</h2>', autoLoad:  {url: 'Blocks/familytreeblocks.php',scripts : true}},
			{id : 'blog_2', title: '<h2>المنتديات</h2>', autoLoad:  {url: 'Blocks/forumblock.php',scripts : true}}
        ]
    }) ;

	var menu_test = new Ext.menu.Menu();
	var tab_test = new Ext.TabPanel({tbar : [{ text:'تعديل',  menu: menu_test }]});

	menu_test.load({ url: 'menus/news_menu.php' }, tab_test );

	var lifestyle_menu = new Ext.menu.Menu();
	var lifestyle_Tabs = new Ext.TabPanel({tbar : [{ text:'تعديل',  menu: lifestyle_menu }]});
	lifestyle_menu.load({ url: 'menus/lifestyle_menu.php' }, lifestyle_Tabs );


	var oldpress_menu = new Ext.menu.Menu();
	var oldpress_Tabs = new Ext.TabPanel({tbar : [{ text:'تعديل',  menu: oldpress_menu }]});
	oldpress_menu.load({ url: 'menus/oldpress_menu.php' }, oldpress_Tabs );


	var history_menu = new Ext.menu.Menu();
	var history_Tabs = new Ext.TabPanel({tbar : [{ text:'تعديل',  menu: history_menu }]});
	history_menu.load({ url: 'menus/history_menu.php' }, history_Tabs );

	Ext.QuickTips.init();

		var myaccordion = new Ext.Panel({
			title : '',
			border : false,
			layout : 'accordion',
			height : 285,
			id : 'myacc',
			moretext : 'المزيد من الأفلام',
			myurl : 'http://aroundtown.egypt.com/index.php?lang=ar&option=com_eventlist&Itemid=2&evcatid=1',
			listeners: {render   : testlayout},
			layoutConfig : {

				activeOnTop : true,
				animate : true,
				collapseFirst : false,
				fill : true
				//hideCollapseTool : flase,
				//titleCollapse : true
			}
		});
		
		var theaterAccordion = new Ext.Panel({
			title : '',
			border : false,
			layout : 'accordion',
			height : 285,
			moretext : 'المزيد من المسارح',
			myurl : 'http://aroundtown.egypt.com/index.php?lang=ar&option=com_eventlist&Itemid=2&evcatid=2',
			listeners: {render   : testlayout},
			id : 'THACC',

			layoutConfig : {

				activeOnTop : true,
				animate : true,
				collapseFirst : false,
				fill : true
				//hideCollapseTool : flase,
				//titleCollapse : true
			}
		});


		var eventsAccordion = new Ext.Panel({
			title : '',
			border : false,
			layout : 'accordion',
			height : 285,
			moretext : 'المزيد من الأحداث',
			myurl : 'http://aroundtown.egypt.com/index.php?option=com_eventing&Itemid=7',
			listeners: {render   : testlayout},
			id : 'EVACC',

			layoutConfig : {

				activeOnTop : true,
				animate : true,
				collapseFirst : false,
				fill : true
				//hideCollapseTool : flase,
				//titleCollapse : true
			}
		});
function getAjaxRequest(accordion, jsonurl) {

		//var jsonurl = 'mydata.php';
		data = Ext.Ajax.request({
			url : jsonurl,
			//params : { action : 'getDate' },
			method : 'GET',
			success : function(result, request) {
				var data = Ext.util.JSON.decode(result.responseText); // convert to object
				showView(data, accordion);

			},
			failure : function(result, request) {
				Ext.MessageBox.alert('Failed', result.responseText);
			},
			scope : this
		});
	}
	
	
	function showView(data, accordion) {

		for (var key in data) {
			var p = new Ext.Panel({
				title : data[key].title,
				html : data[key].html,
				header : true
			});
			if (p.title != undefined) { //getting rid of unwanted items
				if ((p.title).length != 0) { //getting rid of unwanted items
					accordion.add(p).show();
					accordion.doLayout();
				}
			}

		}
			
			//document.getElementById('myacc').innerHTML = document.getElementById('myacc').innerHTML;
								//myaccordion.doLayout();

			//alert(document.getElementById('mytesttabid').innerHTML);
		//	document.getElementById('mytesttabid').style.height = document.getElementById('myacc').style.height;
	//alert(accordion.id)

}
	
	
var MoviesPanel = new Ext.Panel(
			{
					title: '<h2>سينما</h2>',
					id: 'mid1',
					layout:'border',
					footer : true,
					autoWidth : true,
					height : 230,
					listeners: {activate: RefrishTabcontent},
					//listeners: {afterlayout : testtest},
					items: [{
								region:'center',	
								//autoheight : true,
								items : myaccordion
								}]
			});

function RefrishTabcontent()
{
	this.doLayout();
	//MoviesTb.doLayout();
	//alert(myaccordion.getInnerHeight());
		//alert(theaterAccordion.getInnerHeight());
		//alert(document.getElementById(this.id).innerHTML)
	

/*
x = document.getElementById(this.id).firstChild;
	while(x)
	{
		if(x.style)
		{
		  x.style.height = 'auto';
		 alet(x.id);
		}
		x = x.firstChild;
		//alert(x.id);
	}
*/
}


function testlayout()
{
				var tabFooter = "";
			tabFooter += '<div class="blueloop">';
           	tabFooter +=  '<div class="fl"><a href="'+this.myurl+'"><font color="#ffffff">'+this.moretext+'</font></a></div>'; 
 			tabFooter += ' <div class="fl"></div>';
			tabFooter += '<div class="fradv">';
         	tabFooter +=  '<div align="right"><a href="#"><img src="images/advhereleft.jpg" border="0" /></a></div>';
 			tabFooter +=  '</div>';
      		tabFooter +=  ' <div class="fr">';
         	tabFooter +=  '<div align="right"></div>';
        	tabFooter += '</div>';
			tabFooter += '</div>';
			
					//document.getElementById('mytesttabid').style.display = 'none';
			//alert('i am here ');
			if(document.getElementById('myacc') != null)
			{
				document.getElementById(this.id).innerHTML = document.getElementById(this.id).innerHTML+ tabFooter;
			}

}
var TheaterPanel = new Ext.Panel(
			{
					title: '<h2>مسرح</h2>',
					id: 'mid2',
					layout:'border',
					autoWidth : true,
					footer : true,
					height : 230,
					listeners: {activate: RefrishTabcontent},
					items: [{
								region:'center',	
								//autoheight : true,
								items : theaterAccordion
								}]
			});


var EventsPanel = new Ext.Panel(
			{
					title: '<h2>أحداث المدينة</h2>',
					id: 'mid3',
					layout:'border',
					footer : true,
					autoWidth : true,
					height : 230,
					listeners: {activate: RefrishTabcontent},
					items: [{
								region:'center',	
								//autoheight : true,
								items : eventsAccordion
								}]
			});

function testtest()
{
	document.getElementById(this.id).style.height = 'auto'
	//document.getElementById('mytesttabid').style.height = 'auto'
	//document.getElementById('ext-gen291').style.height = 'auto'
	//document.getElementById('ext-gen474').style.height = 'auto'
	//document.getElementById('ext-gen473').style.height = 'auto'
	x = document.getElementById(this.id).firstChild;
	while(x)
	{
		if(x.style)
		{
			x.style.height = 'auto';
		}
		x = x.firstChild;
		//alert("fdfsd");
	}
	//document.getElementById(x).firstChild.style.height = 'auto'
	//alert(document.getElementById(x).firstChild.id);
	//alert(document.getElementById(this.id).innerHTML);


}
var JobsPanel = new Ext.Panel(
			{
					title: '<h2>شغلانة أون لاين</h2>',
					layout:'fit',
					//footer : true,
					listeners: {afterlayout : testtest},
					autoheight : true,
					autoWidth : true,
					id : 'jobspanel',
					autoLoad:{url : 'Blocks/jobsblock.php'}
			});



var classifiedsPanel = new Ext.Panel(
			{
				id : 'classifiedspanel',
				text : 'Classifieds',
				title: '<h2>إعلانات مبوبة</h2>',
				autoWidth : true,
							listeners: {afterlayout : testtest},
					autoheight : true,
				layout:'fit',
				items : {autoLoad:  {url:'Blocks/classifiedsblock.php', scripts:true}}
			});
var	MoviesTb = new Ext.TabPanel(
					
						{
							id : 'mytesttabid',	
							//height : 320,
      						activeTab		: 4,
      			 			autoWidth:true,
							autoheight : true,
	
      			 			resizeTabs:true, // turn on tab resizing
       			 			minTabWidth: 100,
       						frame			: false,
							enableTabScroll	: true,
							// defaults		: {autoHeight: true},

							items : [TheaterPanel, EventsPanel, MoviesPanel,JobsPanel, classifiedsPanel]
						});





MoviesTb.on('notifyDrop', function(){
  alert('i am here');
});




    var ds = new Ext.data.Store({
		//proxy: new Ext.data.HttpProxy({url: 'http://server.egypt.com/egypt/egydirectoryar/collector/searchtest.php',		
		proxy: new Ext.data.HttpProxy({url: 'fromgoogle.php',									
									  
		headers: {
			
			
        'Content-Type': 'application/x-www-form-urlencoded; charset=windows-1256'
		},
		method : 'GET',
		params : {MM:'1'}
		})
	  
	  
	  
	  ,
        reader: new Ext.data.JsonReader({
            root: 'topics',
            totalProperty: 'totalCount',
			//url: 'http://localhost/newegyptcom/examples/egypt/searchtest.php',
            id: 'post_id'
        }, [
            {name: 'title', mapping: 'topic_title'},
            {name: 'topicId', mapping: 'topic_id'},
            {name: 'author', mapping: 'author'},
            {name: 'lastPost', mapping: 'post_time', type: 'date', dateFormat: 'timestamp'},
            {name: 'excerpt', mapping: 'post_text'}
        ])
    });



    var googlrds = new Ext.data.Store({
		//proxy: new Ext.data.HttpProxy({url: 'http://server.egypt.com/egypt/egydirectoryar/collector/fromgoogle.php',		
		proxy: new Ext.data.HttpProxy({url: 'fromgoogle.php',									
									  
		headers: {
			
			
        'Content-Type': 'application/x-www-form-urlencoded; charset=windows-1256'
		},
		method : 'GET',
		params : {MM:'1'}
		})
	  
	  
	  
	  ,
        reader: new Ext.data.JsonReader({
            root: 'topics',
            totalProperty: 'totalCount',
			//url: 'http://localhost/newegyptcom/examples/egypt/searchtest.php',
            id: 'post_id'
        }, [
            {name: 'title', mapping: 'topic_title'},
            {name: 'topicId', mapping: 'topic_id'},
            {name: 'titletosend', mapping: 'titleencoded'},
            {name: 'lastPost', mapping: 'post_time'},
            {name: 'excerpt', mapping: 'post_text'}
        ])
    });


    // Custom rendering Template
    var resultTpl = new Ext.XTemplate(
        '<tpl dir=rtl for="."><div dir=rtl class="search-item">  ',
            '<b>{title}</b>',
        '</div></tpl>'
    );
    
    var resultTpl_google = new Ext.XTemplate(
        '<tpl dir=rtl for="."><div dir=rtl class="search-item22" style="width:100%">  ',
            '<div style="float:right"><b>{title}</b></div><div style="float:left">{lastPost}</div><br>',
        '</div></tpl>'
    );
	
	
    var search = new Ext.form.ComboBox({
        store: ds,
        displayField:'title',
        typeAhead: false,
        loadingText: 'Searching...',
        //width: 570,
        pageSize:10,
        hideTrigger:true,
        tpl: resultTpl,
		mode : 'remote',
        applyTo: 'keyword',
        itemSelector: 'div.search-item',
        onSelect: function(record){ // override default onSelect to do redirect
			document.getElementById('keyword').value = record.data.title;
			document.form_search1.submit();
           // window.location =
             //   String.format('http://extjs.com/forum/showthread.php?t={0}&p={1}', record.data.topicId, record.id);
        }
    });
	
	
    var google_search = new Ext.form.ComboBox({
        store: googlrds,
        displayField:'title',
        typeAhead: false,
        loadingText: 'Searching...',
        //width: 570,
      //  pageSize:20,
        hideTrigger:true,
        tpl: resultTpl_google,
		mode : 'remote',
        applyTo: 'q',
        itemSelector: 'div.search-item22',
        onSelect: function(record){ // override default onSelect to do redirect
			window.location = String.format('http://www.google.com.eg/search?complete=1&hl=en&q={0}&btnG=Google+Search&meta=cr%3DcountryEG&aq=f', record.data.titletosend);
        }	
    });
	
	
	
	var prefs = [{
		id : 'vediopanel',
		text : '<h1>فيديو مصر</h1>',
		draggable:false,
		items : {autoLoad:  {url:'Blocks/videoblock.php', scripts:true}}
	},{
		id : 'p7',
 		text: '<h1>جديد الموقع</h1>',
                	layout: 'fit',
                    collapsible: true,
               items: MoviesTb
			
	},{
		id : 'p4',
 				text: '<h1>المرأة و الأسرة</h1>',
                    items: lifestyle_Tabs
	},{
		id : 'p3',
 				text: '<h1>الأخبار</h1>',
                    items: tab_test	
	},{
		id : 'p6',
 				text: '<h1>مقتطفات تاريخية</h1>',
                    items: history_Tabs
		
	}/*,{
		id : 'blogsblk',
		text : '<h1>مجتمع مصر<h1>',
		items:Blogs_Tabs
	}*/,{
			
		id : 'p5',
 				text: '<h1>صحافة زمان</h1>',
                    items: oldpress_Tabs
	}, {
		id : 'p2',
		text : '<h1>دليل الموقع</h1>',
		items:directory_Tabs
	}]
			;


	var portalState, portal, settingId;
	var checkBoxes = [];
	var me;

	// -----------------  private method ----------------------
	function createCheckbox() {
		var div = Ext.get(settingId);
		div.dom.innerHTML = "";

		var tbl = document.createElement("table");
		tbl.setAttribute("id", "app-portal-demo-tbl-dn-ext");
		var tBody = document.createElement("tBody");
		tbl.appendChild(tBody);
		tbl.cellPadding = 2;
		tbl.cellSpacing = 2;
		var row = document.createElement("tr");
		tBody.appendChild(row);
		var cell = document.createElement("td");
		cell.colSpan = 4;
		cell.innerHTML = "<h2>إختر الخدمات التي تريد إظهارها منفردة:</h2>";
		row.appendChild(cell);

		for (var i = 0;i < prefs.length; i++) {
			var text = prefs[i].text;
			var rowInd = Math.round(i / 2 - 0.1, 0) + 1;
			if (rowInd >= tbl.rows.length - 1) {
				var row = document.createElement("tr");
				tBody.appendChild(row);
			}
			var row = tbl.rows[rowInd];
			var cell = document.createElement("td");
			cell.width = "20px;"
			row.appendChild(cell);
			var chk = document.createElement("input");
			chk.type = "checkbox";
			chk.id = prefs[i].id;
			chk.txt = text;
			cell.appendChild(chk);
			checkBoxes.push(chk);
			chk.onclick = onChkChanged;
			cell = document.createElement("td");
			row.appendChild(cell);
			cell.innerHTML = text;
		}

		div.appendChild(tbl); 
	}

	function onChkChanged(e) {
		var evt = e || window.event;
		var chk = evt.target || evt.srcElement;
		if (!chk.checked) {
			portal.removePortlet(chk.id);
			portal.doLayout();
		} else if (chk.checked) {
			showPortlet( {
				text : chk.txt,
				id : chk.id,
				checked : true
			});
			portal.doLayout();
		}
		portal.doLayout();

		portalState.save();
	}

	function restoreState() {
		var portlets = portalState.getVisiblePortlets();
		if (!portlets)
			{
				for (var i = 0;i < prefs.length && i < 9; i++) {
					var p = prefs[i];
					if (p && p.id) {
						showPortlet(p);
						
						me.setCheckBox(p.id, true);
					}
				}
				
				portal.doLayout();
				//alert(prefs.length);
				return;
			}
	
		portal.removeAllPortlets();
		for (var i = 0;i < portlets.length && i < 9; i++) {
			var p = portlets[i];
			if (p && p.id) {
				showPortlet(p);
				
				me.setCheckBox(p.id, true);
			}
		}
		portal.doLayout();
	}

	function showPortlet(pInfo) {
		var items;
		for (var i = 0;i < prefs.length; i++) {
			if (prefs[i].text==pInfo.text) {
				items = prefs[i].items;
				break;
			}
		};	
		var pTools = [{
			id : 'close',
			handler : function(e, target, panel) {
				panel.ownerCt.remove(panel, true);
				me.setCheckBox(panel.pInfo.id, false);
				portalState.save();
			}
		}];
		var h = portalState.getHeight(pInfo.id);
		var colaps =  portalState.getColapse(pInfo.id);
		var colposs =  portalState.getColposs(pInfo.id);
		var p = portal.addPortlet( {
			id : pInfo.id,
			text : pInfo.text,
			collapsed : colaps,
			colum : colposs,
			height : h || 200
		}, pTools,items);
		p.on("resize", function() {
				portalState.save();
		});

		p.on("collapse", function() {
				portalState.save();
		});
		p.on("expand", function() {
				portalState.save();
		});
	}

	// -------------------- public method -----------------------
	return {
		/**
		 * @param {String}
		 *            sId div id of container of all checkbox
		 * @param {String}
		 *            portId id of portlet
		 * @param {Divo.app.PortalState}
		 *            ps 
		 */
		init : function(sId, portId, ps) {
			settingId = sId;
			portalState = ps;
			me = this;
			portal = Ext.ComponentMgr.get(portId);

			createCheckbox();
			restoreState();
			getAjaxRequest(myaccordion, 'Blocks/moviesblock.php');
			getAjaxRequest(theaterAccordion, 'Blocks/theaterblock.php');
			getAjaxRequest(eventsAccordion, 'Blocks/eventsblock.php');

			document.getElementById('ext-gen11').style.height = 'auto'
			document.getElementById('search_3').style.display = 'none';
    

		},
		setCheckBox : function(ext, checked) {
			for (var i = 0;i < checkBoxes.length; i++) {
				if (checkBoxes[i].id == ext) {
					checkBoxes[i].checked = checked;
					break;
				}
			}
		}

	};
}
// EOP

