var Core = {
		
	global: {
		engines: {},
		isMenu: true
	},

	search: function()
	{
		this.updateUrl();
		this.notifyEngines();
	},
	
	updateUrl:function()
	{
		setTimeout(function(){
			var menu = 'on';
			if(!Core.global.isMenu) menu = 'off';
			
			var state = {
					'keywords':$keywords.val(),
					'engines':Core.getEnginesStr(),
					'menu': menu
				};
			
			SimpleAjaxUrl.update(state);
			SimpleCookie.create('state',state,365);
		},800);
	},
	
	getEnginesStr:function()
	{
		var engines = '';
		
		//for(var e in Core.global.engines)
		//{
		//	if(Core.global.engines[e].active) engines += e+' ';
		//}
		
		$('.engine_skin:not(:hidden)').each(function(){
			engines += $(this).attr('id')+' ';
		});
		
		engines = engines.substr(0,engines.length-1);		
		return engines;
	},
	
	getWindowWidth:function()
	{
		if(Core.global.isMenu) return $(window).width()-230;
		else return $(window).width()-20;
	},
	
	getDocumentInnerHeight:function()
	{
		var myWidth = 0, myHeight = 0;
		  if( typeof( window.innerHeight ) == 'number' ) 
			  return window.innerHeight;
		  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight )) 
			  return document.documentElement.clientHeight;
		  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) 
			  return document.body.clientHeight;
	},
	
	toggleMenu:function(close)
	{
		if(close)
		{
			$('#menu').hide();
			$('#menu_toggle').css({left:5}).html('show menu &raquo;');
			Core.global.isMenu = false;
			$('#menu_toggle').attr('rel','show'); 
			
			$('#engines').width(Core.getWindowWidth());
			//Core.updateUrl();
			
			return false;
		}
		
		$('#menu_toggle').click(function(){
			
			if($(this).attr('rel') == 'hide')
			{
				$('#menu').hide();
				$('#menu_toggle').css({left:5}).html('show menu &raquo;');
				Core.global.isMenu = false;
				$(this).attr('rel','show'); 
			}
			else
			{
				$('#menu').show();
				$('#menu_toggle').css({left:-75}).html('&laquo; hide menu');
				Core.global.isMenu = true;
				$(this).attr('rel','hide'); 
			}
			
			
			$('#engines').width(Core.getWindowWidth());
			Core.updateUrl();
			return false;
		});
	},
	
	notifyEngines: function()
	{
		//document.title = ucwords($keywords.val())+' jobs in '+ucwords($location.val());
		
		for(var e in Core.global.engines) 
		{
			if(Core.global.engines[e].active) 
				Engine.search(e);
		}
	},
	
	getEngineHeight: function()
	{
		return $(window).height()-136;
	},
	
	getEngineBodyHeight: function()
	{
		return $(window).height()-169;
	},
	
	initScrolls:function()
	{
		$('.engine_body').jScrollPane({
			scrollbarWidth:10,
			scrollbarMargin:1,
			maintainPosition:true,
			animateTo:true,
			wheelSpeed: 48
		});
	},
	
	initSaveButtons:function()
	{
		$('a.save').live('click',function(){
			
			if(!Core.logged)
			{
				var obj_head = $('<div>Please SignIn with Twitter in order to use save function. &nbsp;&nbsp;&nbsp;&nbsp; <a href="#" onclick="SimpleBox.close(); return false;"><img src="/images/fbcancel.png" /></a></div>');
				obj_head.css({fontWeight:'bold',background:'#6bd0dd',color:'#357ea6',padding:5});
				
				var obj_body = $('<a href="/oauth/login" class="login_button" rel="connect"><img src="/images/signin_twitter_off.png" alt="Connect" ></a>')
				obj_body.css({margin:'20px auto 15px auto',width:169,height:29,display:'block'});
				
				var cont = $('<div></div>').html(obj_head).append(obj_body);
				
				SimpleBox.open(cont, {
					directInput:true,
					bodyCss:{padding:0,background:'#e5e5e5'},
					fbStyle:{borderColor:'transparent url(/images/fbbg.png)'}
				});
				
				return false;
			}
			
			var id				= $(this).attr('rel');
			
			var title 			= $('.'+id+' > div > div > h3').html();
			var description 	= $.trim($('.'+id+' > div > div > p').html());
			var link			= $('.'+id+' > .adds > .more > a').attr('href');
			
			if(link == undefined)
				link = '';
				
			var image_link		= $('.'+id+' > div > img.avatar').attr('src');
			if(image_link == undefined) image_link = '';
			
			var optional_link	= $('.'+id+' > .adds > .optional > a').attr('href');
			var created_at		= $('.'+id+' > .adds > .date').html();
			
			var data = 'id='+id+'&created_at='+encodeURIComponent(created_at)+'&title='+encodeURIComponent(title)+'&description='+encodeURIComponent(description)+'&link='+encodeURIComponent(link)+'&optional_link='+encodeURIComponent(optional_link)+'&image_link='+encodeURIComponent(image_link);
			$.post('/save/do',data,function(json){
				if(json.result) 
				{
					$('.'+id+':has(a.save)').addClass('saved');
					Engine.refresh('saved');
				}
			},'json');
			return false;
		});
	},
	
	initUnSaveButtons:function()
	{
		$('a.unsave').live('click',function(){
			
			var id				= $(this).attr('rel');
			var data = 'id='+id;
			
			$.post('/save/undo',data,function(json){
				if(json.result) 
				{
					$('.'+id+':has(a.unsave)').remove();
					$('.'+id+':has(a.save)').removeClass('saved');
				}
			},'json');
			
			//Engine.refresh('saved');
			return false;
		});
	},
	
	initFilters:function()
	{
		$('a.filter').live('click',function(){
			
			var paramValue 	= $(this).attr('rev');
			var param		= $(this).attr('title');
			var engineName	= $(this).attr('rel');
			
			$('a.filter[title=\''+param+'\'][rel=\''+engineName+'\']').removeClass('selected');
			$(this).addClass('selected');
			
			Engine.toggleFilter(engineName,param,paramValue);
			Engine.search(engineName, true);
			return false;
		});
	},
	
	addEngineInit:function(engineName,title,id)
	{
		if(!id)
		{
			id = '';
			var cl = 'init';
		}
		else 
		{
			id 		= 'id="'+id+'"';
			var cl 	= id;
		}
			
		var $c = $('#container > ul');
		var li = '<li id="fbFeedInit"><a '+id+' class="'+cl+'" rel="'+engineName+'" href="#">'+title+'</a></li>';
		$c.append(li);
	},
	
	initSortable:function()
	{
		$("#engines_container").sortable({
			opacity: 0.6,
			zIndex: 9,
			revert: true,
			cursor: 'move',
			handle: $('.engine_head')
		});
	},
	
	updateSortable:function()
	{	
		$("#engines_container").sortable('destroy');
		$("#engines_container").sortable({
			opacity: 0.6,
			zIndex: 9,
			revert: true,
			cursor: 'move',
			handle: $('.engine_head')
		});
	},
	
	restoreState:function(keywords,location,engines,menu)
	{		
		$keywords.val(keywords);
		$location.val(location);
	
		var engines = engines.split(' ');
		
		if(menu == 'off') 
		{
			Core.toggleMenu(true);
		}
		
		for(var i=0; i<engines.length; i++)
		{
			var $elem = $('a.init[rel=\''+engines[i]+'\']');
			if($elem.html() == null) break;
			
			//displaying not active engines
			if(!Engine.isActive(engines[i])) 
			{
				Engine.toggle(engines[i],$elem.html(),true);
			}
		}
		
		//hiding if active but not in the state
		var keep = true;
		for(var e in Core.global.engines) 
		{
			if(Core.global.engines[e].active)
			{
				for(var i=0; i<engines.length; i++)
				{
					keep = false;
					if(e == engines[i]) 
					{
						keep=true;
						break;
					}
				}
				
				if(!keep) Engine.toggle(e);
			}
		}
		
		setTimeout(function(){
			var firstEngine = false;
			$('.engine_skin:not(:hidden)').each(function(){
				if(!firstEngine) firstEngine = $(this).attr('id');
			});
			
			if(firstEngine)
			{
				for(var i=0; i<engines.length; i++)
				{
					if(engines[i] != firstEngine && i==0)
					{
						$('#'+engines[i]).insertBefore('#'+firstEngine);
					}
					else
					{
						$('#'+engines[i]).insertAfter('#'+engines[i-1]);
					}
				}
			}
		},750);
		
		Core.notifyEngines();
	},
	
	tooltip:function()
	{
		$("a").tooltip({
			showBody: ' - ',
			showURL: false,
			track: true,
			fade: 150
		});
	},
	
	initRefreshButtons:function()
	{
		$('.refresh').live('click',function(){
			Engine.refresh($(this).attr('rel'));
			return false;
		});
	},
	
	showStatusBox:function()
	{
		var obj_head = $('<div>What are you doing? <a href="#" style="float:right" id="closeBox"><img src="/images/fbcancel.png" /></a></div>');
		obj_head.css({fontWeight:'bold',background:'#3390a3',color:'#ffffff',padding:5});
					
		var obj_body = $('<div></div>');
		obj_body.css({padding:'15px 10px 15px 10px',width:351,height:84,display:'block',textAlign:'left'});
		obj_body.html('<textarea id="statusbox" style="width: 348px; clear:left;height: 50px;float:left;"></textarea><div class="button" style="margin-top:5px;width: 65px;float:left;clear:left;"><button style="width: 60px" id="update" type="button">Update</button><div></div></div><div style="float:left;margin-top:11px;margin-left:5px;font-weight:bold;" id="stcounter">140</div>');
							
		var cont = $('<div></div>').html(obj_head).append(obj_body);
		
					
		SimpleBox.open(cont, {
			directInput:true,
			bodyCss:{padding:0,background:'#e5e5e5'},
			fbStyle:{borderColor:'transparent url(/images/fbbg.png)'}
		});
		
		$('#statusbox').keyup(function(){
			var val = 140-$(this).val().length;
			$('#stcounter').html(val);
			
			if(val < 1)
				$('#stcounter').css({color:'red'})
			else
				$('#stcounter').css({color:'#333'})
		});
		
		$('#update').click(function(){
			
			if ($('#statusbox').val().length < 3) 
			{
				$('#stcounter').css({color: 'red'}).html('Ooops. Your status is too short.');
				return 0;
			}
			
			var data = 'status='+encodeURIComponent($('#statusbox').val());
			
			var uurl = '/oauth/update-status';
			$(this).html('Updating...');
			
			$.post(uurl,data,function(json){
				if (json.status) 
				{
					$('#update').html('Update');
					$('#stcounter').html('<a href="#" id="updated_status">status updated, click here to see it.</a>');
					
					$('#updated_status').click(function(){
						window.open(json.link,'twitterstatus','height=500,width=840,scrollbars=1');
					});
					$('#statusbox').val('');
				}
			},'json');
		});
		
		$('#closeBox').click(function(){SimpleBox.close(); return false;});
	}
}


function ucwords (str) {
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase( ); } );
}