var global = {
		checkIfEmpty : function(txt){
			 var reg = /^\s{1,}$/g;
			 if ((txt.length==0) || (txt==null) || ((txt.search(reg)) > -1)) {
				 return true;
			 }else{
				 return false;
		   } 
		},
		// Things called on every page
		init : function() { 
			$(document).ready(function(){
				
				var predictionSearchTimer = null;
				var tabsOpen = 'firstTime';
				
				
				$('#user_not_logged_in, .login_menu_item').click(function(){
					var pg = $(this).attr('param')
					global.showLoginDialog(parseInt(pg));
					tabsOpen = true;
					return false;
				});
				
				// Close the login box
				$("#close_login").click(function(){
					$("#loginBox").dialog('destroy');
					$("#loginboxShell").tabs('destroy');
					tabsOpen = false;
				});
				
				
				
				// Prediction for the search bar
				$('#query').keyup(function(){
					clearTimeout(predictionSearchTimer);
					predictionSearchTimer = setTimeout(function(){
					    url = urlSearch;
				    	global.autoComplete(url, $('#query'),$('#prediction_list_search'), $('#mm_prediction_search'), false, false );	
			     	}, 200);
				});
				
				// Counter for the WHY area on appropriates pages
				$('#why').keyup(function()
						{
							global.counter();
						});
				$('#why').keydown(function()
						{
							global.counter();
						});			
				$('#why').focus(function()
						{
							$('#mm_prediction').hide();
							global.counter();
						});
				$('#why').change(function()
						{
							global.counter();
						});
				$('#why').blur(function()
						{
							global.counter();
						});	
				$('#why').mousedown(function()
						{
							global.counter();
						});			
				$('#why').mouseup(function()
						{
							global.counter();
						});
				
				// Convert all the links in the text
				$('.linkified').each(function(){
					$(this).html(global.linkify_plain($(this).html()));
				});
			});
			
		},
		
		
		// Because it's not existing in jquery
		postJSON : function(url, data, callback) {
			$.post(url, data, callback, "json");
		},
		
		
		showLoginDialog : function(pg){					
			$("#loginboxShell").tabs({
				selected: pg
			});					

			$("#loginBox").dialog({
				modal:true,
				resizable:false,
				dialogClass: 'dialog_box'
			});
		},
		
		autoComplete : function(url, query, prediction_list, prediction_zone, wiki, fromHp){
			// Will not predict if empty input
			var brandStr = query.val();
			if(brandStr.length > 1 && global.checkIfEmpty(brandStr) == false)
			{
				prediction_list.empty();
				prediction_zone.hide();
				// Get typed value
				// Wikipedia removed temporarly
				//urlParameter = (wiki)?'/search/wiki/brand/':'/brand/';
				urlParameter = '/brand/';
				var brand_value = query.val();
				$.getJSON(url+urlParameter+ brand_value, function(data)
						{
							if (data.success)
							{
								prediction_zone.show();
								prediction_list.empty();
								// database entries
								global.feedResults(data.brands, prediction_list,fromHp);
								// wikipedia entries
								if(wiki){
									global.feedResults(data.wiki, prediction_list,fromHp);
								}
							}
								
						});
				}else{
					prediction_zone.hide();
					prediction_list.empty();
				}
		},
		
	
		
		feedResults : function(tab, ulElement,fromHp){
			if($.isArray(tab)){
				$.each(tab, function(i, brand)
					{	
						var li = document.createElement("li");
						$(ulElement).append(li)
						var a = document.createElement("a")
						a.setAttribute("href", "javascript:;")
						a.setAttribute("param", brand.id)
						a.className = "autocomplete"
						a.innerHTML = brand.name
						global.predictionClick(a,brand.name, fromHp)
						$(li).append(a)
					});
			}			
		},
		
		predictionClick : function(obj,brand_name, fromHp){
			obj.onclick = function(){
				if(fromHp){
					fillForm(this,brand_name,false);
				} else {
					$('#query').val(brand_name);
					$('#mm_prediction_search').hide();
					window.location = 'http://www.mattermeter.com/matter/' + brand_name;
				}
			}
		},
		
		floatMessage : function(target,msg,location){
			//Message floater
			
			var floatWrap = document.createElement("div");
			floatWrap.className = "floatMsgWrap";
			$(floatWrap).html(msg);
			
			if (location == 'inside'){
				$(target).prepend(floatWrap);			
			}else{
				$(target).before(floatWrap);
			}
			
			$(floatWrap).fadeIn("slow")
			
			var floatTimeout = setTimeout(function(){
				$(floatWrap).fadeOut("slow", function(){ $(floatWrap).remove(); })
			}, 2000);
			
		},
		
		follow : function(url,usr,func){
					
			$.getJSON(url + usr, function(data){
				
				func(data);
				
			});
			
		},
		
		msgBox : function(msg){
						
			var msgBxOverlay = document.getElementById("msgBoxOverlay");
			
			if (!msgBxOverlay){
				var msgBxOverlay = document.createElement("div")
				msgBxOverlay.className = "msgboxOverlay";
				$("body").append(msgBxOverlay);
			}
			
			var scWidth = 0;
			var scHeight = 0;   
			var scX = 0;
			var scY = 0;
			var docWidth = 0;
			var docHeight = 0;
			   
			if (window.innerHeight && self.innerHeight) {	
					
				scX = document.body.scrollWidth;
				scY = window.innerHeight + window.scrollMaxY;		
				scWidth = self.innerWidth;
			    scHeight = self.innerHeight; 
			         
			} else{ 
				scX = document.body.scrollWidth;
				scY = document.body.scrollHeight;		
				scWidth = document.documentElement.clientWidth;
			    scHeight = document.documentElement.clientHeight; 	
			}	
			
			if(scY < scHeight){
				docHeight = scHeight;	
			}else{
			    docHeight = scY;
			}
				
			if(scX < scWidth){	
				docWidth = scWidth;	
			}else{
				docWidth = scX
			}
				
			$(msgBxOverlay).width(docWidth);	
			$(msgBxOverlay).height(docHeight);

			var dialog_box_wrap = document.createElement("div");
			dialog_box_wrap.className = "dialog_box_wrap";
			$(msgBxOverlay).append(dialog_box_wrap);
			
			var dialog_box = document.createElement("div");
			dialog_box.className = "dialog_box";
			$(dialog_box_wrap).append(dialog_box);
			
			var dialog_box_inner = document.createElement("div");
			dialog_box_inner.className = "dialog_box_inner";
			$(dialog_box).append(dialog_box_inner);
			
			var dialog_box_msg = document.createElement("div");
			dialog_box_msg.className = "dialog_box_msg";
			$(dialog_box_inner).append(dialog_box_msg);
			dialog_box_msg.innerHTML = msg
			
			var YAxis;
		    
		    if (navigator.appName == "Microsoft Internet Explorer"){
		    	YAxis = document.documentElement.scrollTop;
		    }else{
		    	YAxis = window.pageYOffset     
		    }
		    
		    var a = document.createElement("a");
			a.className = "close_dialog";
			a.setAttribute("href", "javascript:;");
			$(dialog_box_inner).append(a);
			
			a.onclick = function(){
				 $(msgBxOverlay).fadeOut("fast", function(){
					 $(msgBxOverlay).remove();
				 });
			}
						
			var img = document.createElement("img");
			img.setAttribute("src", "/images/buttons/close.png");
			$(a).append(img);
						
		    $(msgBxOverlay).fadeIn("fast");
		    $(dialog_box_wrap).width($(dialog_box).width());
	    	$(dialog_box_wrap).height($(dialog_box).height());
	    	$(dialog_box_wrap).css({'top' : (((docHeight / 2) -  $(dialog_box).height() )) + (YAxis / 2) });
	    	$(dialog_box_wrap).css({'left' : ( (docWidth - $(dialog_box).width()) / 2 ) });
	    	
		},
		
		checkForm : function(){
				// Check why text area
				var why_text = jQuery.trim($('#why').val());
				var why = why_text.length;
				if (why == 0)
				{
					//alert('Why area is blank');
					return false;
				}
				else if (why > 160)
				{
					var display_div = $('#why');
					global.floatMessage(display_div, 'Hey, this ain\'t a novel....keep it under 160 characters');
					return false;
				}
				// check brand
				var brand_text = jQuery.trim($('#brand_name').val());
				var brand = brand_text.length;
				if (brand == 0)
				{
					global.msgBox('Your matter isn\'t associated to anything');
					return false;
				}
				
				return true;
		},
		
	
	
		
		counter : function()
		{
			var char_length = $('#why').val().length;
			var remaining = 160 - char_length;
			if (remaining >= 0)
			{
				$('#total_chars').attr('style', 'color: #CFCFCF;');
			}
			else
			{
				$('#total_chars').attr('style', 'color: #CC9999;');
			}
			$('#total_chars').text(remaining);
		},
		
		// To convert http link into a tag
		linkify_plain:function(text)
		{
			if( !text ) return text;
			
			text = text.replace(/((https?\:\/\/|ftp\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,function(url){
				nice = url;
				if( url.match('^https?:\/\/') )
				{
					nice = nice.replace(/^https?:\/\//i,'')
				}
				else
					url = 'http://'+url;
				return '<a target="_blank" rel="nofollow" href="'+ url +'">'+ nice.replace(/^www./i,'') +'</a>';
			});
			return text;
		},
		
		// Follow Unfollow action
		followUsr : function(usr, link, name, url){
			var followFunction = function(data){
				if (data.result == 1){
					if (data.status == 1){
						global.floatMessage(link,"You are now following " + name);
						$(".flwBtn"+usr+" a").html('<img src="/images/buttons/unfollow_button.png"/>');					
					}else{
						global.floatMessage(link,"You are not following " + name + " anymore");									
						$(".flwBtn"+usr+" a").html('<img src="/images/buttons/follow_button.png"/>');					
					}					
				}
			}
			global.follow(url,usr,followFunction);
		},
		
		// for fbconnect login/signup
		loadandredirect : function(fb_connect_url, redirect_url){
				var matter = $('#why').val();
				var does = $('#does_matter').val();
				var name = $('#brand_name').val();
				var clean_name = escape(name);
				window.location=fb_connect_url + '?page=' + redirect_url + '&why='+matter+'&does='+does+'&brand='+ clean_name;	
		},
		
		removeProfileMessage : function(url, div){
			$.getJSON(url, function(data)
					{
						if (data.success)
						{
							$('#' + div).fadeOut('slow');
						}
						else
						{
							global.floatMessage($('#' + div), 'Sorry, an error has occured. Please try again.', 'inside');
						}
					});
		}
		

}

global.init();