/**
 * Wimgo Web Content
 * Global 'webContent' object for utility functions
 */
	
var wimgoWebContent = {
  cfg: {
	googleApiKey: 'ABQIAAAAvVmlKHPXsw0lhbu1-EynThSbkjobD21MEKsM69eGjSIGfheRbxQDFvr17xKFAqzoVVlCnr3RfNiF8Q',
	_googleApiLoaded: false
  },
  init: function() {
	if(this.cfg.googleApiKey && this.cfg._googleApiLoaded === false) {
	  this.googleApiLoad();
	}
  },
  prepText: function(text) {
	  text = this.prepUrl(text);
	  text = this.prepUname(text);
	  return text;
  },
  prepUname: function(text) {
	  var re = /@([-_a-zA-Z0-9]+)/g;
	  return text.replace(re, "<a rel=\"nofollow\" target=\"blank\" href=\"http://www.twitter.com/$1\">@$1</a>");
  },
  prepUrl: function(text) {
	  var re = /(http:\/\/[-_\.\/a-zA-Z0-9\?]+)/gi;
	  return text.replace(re,"<a rel=\"nofollow\" target=\"blank\" href=\"$1\">$1</a>");
  },
  googleApiLoad: function() {
	if(typeof(google) != 'undefined') { return true; }
	// Load Google API if not already loaded
	var script = document.createElement("script");
	script.src = "http://www.google.com/jsapi?key="+this.cfg.googleApiKey+"&callback=wimgoWebContent.googleApiLoaded";
	script.type = "text/javascript";
	document.getElementsByTagName("head")[0].appendChild(script);
  },
  googleApiLoaded: function() {
	this.cfg._googleApiLoaded = true;
  },
  // Cache for callback situation... Hard to explain... meh.
  googleSearchCache: {
	jqSelection: false,
	search: '',
	cfg: {}
  }
};
wimgoWebContent.init();


/**
 * jQuery plugins for loading in widget content
 */
(function($) {  
  /**
   * TWITTER SEARCH
   */
  $.fn.wimgoTwitterSearch = function(query, settings) {
	// Default config settings
	var cfg = {
	  'apiUrl': '/api/',
	  'callback': '?', // '?' lets jQuery handle it automatically with the second argument on the 'getJSON' function below
	  'excludeUser': '',
	  'limit': 20,
	  'header': '',
	  'hideHeader': true //hides the header if no results are returned if the header tag id is given
	};
	if (settings) $.extend(cfg, settings);
	
	// Alias selected elements
	var jqEl = this;
	
	// Build API URL to call
	fullApiUrl = cfg.apiUrl + '?method=Twitter.searchTimeline&callback='+cfg.callback+'&'+'excludeUser='+cfg.excludeUser+'&count='+cfg.limit+'&query='+query;
	$.ajaxSettings.cache = true;
	$.getJSON(fullApiUrl, function(data) {
	  // Display content for each element in selector
	  jqEl.each(function() {
		html = "<ul>";
		if (data.twitter.length) {		
			for(i=0; i<data.twitter.length; i++) {
			  html += "<li><a rel='nofollow' href='http://www.twitter.com/"+data.twitter[i].from_user+"'><img width='48' align='left' src="+data.twitter[i].profile_image_url+" /></a><a rel='nofollow' href='http://www.twitter.com/"+data.twitter[i].from_user+"'><b>"+data.twitter[i].from_user+"</b></a> "+wimgoWebContent.prepText(data.twitter[i].text)+ "<br class='clear'/></li>";
			}
			html += "</ul>";
			$(this).html(html);
		} else {
			$(this).parents('.drawer').remove();  //removing the twitter li because it is not linked to a real twitter account
		    //since we have removed the twitter li we need to reinit the accordion to account for the new height and widths
		    $('ul.drawers').accordion( "destroy" ).accordion({collapsible: true,autoHeight: false});
		}
	  });
	});
	$.ajaxSettings.cache = false;
	return this;
  };
  
  
  /**
   * TWITTER USER TIMELINE
   */
  $.fn.wimgoTwitterUserTimeline = function(user, settings) {
	// Default config settings
	var cfg = {
	  'apiUrl': '/api/',
	  'callback': '?', // '?' lets jQuery handle it automatically with the second argument on the 'getJSON' function below
	  'excludeUser': '',
	  'limit': 20
	};
	if (settings) $.extend(cfg, settings);
	
	// Alias selected elements
	var jqEl = this;
	
	// Build API URL to call
	fullApiUrl = cfg.apiUrl + '?method=Twitter.userTimeline&callback='+cfg.callback+'&'+'excludeUser='+cfg.excludeUser+'&count='+cfg.limit+'&userid='+user;
	$.ajaxSettings.cache = true;
	$.getJSON(fullApiUrl, function(data) {
	  // Display content for each element in selector
	  jqEl.each(function() {
		html = "<ul>";
		for(i=0; i<data.twitter.length; i++) {
		  html += "<li><a rel='nofollow' href='http://www.twitter.com/"+data.twitter[i].user.screen_name+"'><img width='48' align='left' src="+data.twitter[i].user.profile_image_url+" /></a>"+wimgoWebContent.prepText(data.twitter[i].text)+ "<br class='clear'/></li>";
		}
		html += "</ul>";
		$(this).html(html);
	  });
	});
	$.ajaxSettings.cache = false;
	return this;
  };
  
  
  /**
   * FLICKR IMAGE SEARCH
   */
  $.fn.wimgoFlickrSearch = function(query, settings) {
	// Default config settings
	var cfg = {
	  name                  : 'flickrSearchFeed',
	  containerId           : '',
	  apiUrl                : '/api/',
	  method                : 'flickr.photos.search',
	  callback				: '?', // '?' == Let jQuery handle it,
	  limit					: 20,
	  header				: '',
	  hideHeader			: true, //hides the header if no results are returned if the header tag id is given
	  args:{
		api_key               : '0336020d0c4d0348f95e2b6fe4783f62',
		user_id               : '',
		tags                  : '',
		tag_mode              : 'any',
		text                  : '',
		min_upload_date       : '',
		max_upload_date       : '',
		min_taken_date        : '',
		max_taken_date        : '',
		license               : '',
		sort                  : '',
		privacy_filter        : '',
		bbox                  : '',
		accuracy              : '',
		safe_search           : '',
		content_type          : '',
		machine_tags          : '',
		machine_tag_mode      : '',
		group_id              : '',
		contacts              : '',
		woe_id                : '',
		place_id              : '',
		media                 : '',
		has_geo               : '',
		geo_context           : '',
		lat                   : '',
		lon                   : '',
		radius                : '',
		radius_units          : '',
		is_commons            : '',
		extras                : '',
		per_page              : '20',
		page                  : '1'
	  }
	};
	if (settings) $.extend(cfg, settings);
	cfg.args.text = query;
	cfg.args.per_page = cfg.limit;
	
	// Alias selected elements
	var jqEl = this;
	
	// Build API URL to call
	var qstring = "method=Flickr.apiCall&api="+cfg.method;
	for(var key in cfg.args){
		if(typeof cfg.args[key] != 'function' && typeof cfg.args[key] != 'object' && cfg.args[key] != ''){
			qstring+="&a["+key+"]="+escape(cfg.args[key]);
		}
	}
	fullApiUrl = cfg.apiUrl + '?'+qstring;
	
	$.getJSON(fullApiUrl, function(data) {
	  // Display content for each element in selector
	  jqEl.each(function() {
	  
		if (data.photos.photo.length){
			html = "<div class='flickrPhotos'>";
	        for(var i=0; i<data.photos.photo.length; i++){
	            var p = data.photos.photo[i];
	            html += "<a rel='nofollow' href='http://farm"+p.farm+".static.flickr.com/"+p.server+"/"+p.id+"_"+p.secret+".jpg' title='Flickr image' class='thickbox'><img src='http://farm"+p.farm+".static.flickr.com/"+p.server+"/"+p.id+"_"+p.secret+"_t.jpg' width='90'/></a>";
	        }
	        html += "</div><div class='clear'></div></div>";
			$(this).html(html);
		} else {
			$(this).parents('drawer').remove();
		}
	  });
	});
	return this;
  };
  
  /**
   * GOOGLE SEARCH
   */
  $.fn.wimgoGoogleSearch = function(query, settings) {
	// Default config settings
	var cfg = {
	  'location': false, // Set a value for local search
	  'limit': 20
	};
	if (settings) $.extend(cfg, settings);
	
	// Setup cache - the callback has to know the selected elements and config settings
	wimgoWebContent.googleSearchCache.jqSelection = this;
	wimgoWebContent.googleSearchCache.search = query;
	wimgoWebContent.googleSearchCache.cfg = cfg;
	
	// Load script and set callback
	google.load('search', '1', {'callback': $.wimgoGoogleSearchCallback});
	
	return this;
  };
  // Public callback for the Google JSAPI
  $.wimgoGoogleSearchCallback = function() {
	// Create a search control
	  var searchControl = new google.search.SearchControl();
	  var cfg = wimgoWebContent.googleSearchCache.cfg;
	  
	  // Location-based search
	  if(cfg.location !== false) {
		var localSearch = new google.search.LocalSearch();
		// Set the Local Search center point
		localSearch.setCenterPoint(cfg.location);
		searchControl.addSearcher(localSearch);
	  }
	  
	  var webSearch = new google.search.WebSearch();
	  webSearch.setNoHtmlGeneration();
	  webSearchOptions = new google.search.SearcherOptions();
	  webSearchOptions.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
	  searchControl.addSearcher(webSearch, webSearchOptions);
	  /*
	  // OPTIONAL other searches in the future...
	  searchControl.addSearcher(new google.search.VideoSearch());
	  searchControl.addSearcher(new google.search.BlogSearch());
	  searchControl.addSearcher(new google.search.NewsSearch());
	  searchControl.addSearcher(new google.search.ImageSearch());
	  searchControl.addSearcher(new google.search.BookSearch());
	  searchControl.addSearcher(new google.search.PatentSearch());
	  */
	  
	  
	  wimgoWebContent.googleSearchCache.jqSelection.each(function() {
		searchControl.draw(this);
	  });
	  
	  //searchControl.setSearchCompleteCallback(this, $.wimgoGoogleSearchComplete, [webSearch]);
	
	  // Execute search
	  searchControl.execute(wimgoWebContent.googleSearchCache.search);
  };
  // Public callback for the Google JSAPI
  /*
  $.wimgoGoogleSearchComplete = function(searcher) {
	  alert("GOT GOOGLE RESULTS!\n\nLength: "+searcher.results.length+"\n\n"+searcher.results);
	  
	  // Display content for each element in selector
	  wimgoWebContent.googleSearchCache.jqSelection.each(function() {
		$(this).append('<b>TEST</b>');
		
		for (var i=0; i < searcher.results.length; i++) {
		  var result = searcher.results[i];
		  searcher.createResultHtml(result);
		  if(result.html) {
			  child = result.html.cloneNode(true);
			  $(this).append(child);
		  } 
		}
	  });
  };
  */
})(jQuery);

 /*Yahoo Analytics - Track Drawer open/close //comenting yahoo stuff
$(document).ready(function(){
	
	$(".web-content .drawer-handle").click(function(){  
		ywa_onclick("Related: from " + $(this).attr("id"), yahoo_document_group, "INTERNAL_SEARCH");
	});
});*/
