// hattrick heaven copyright 2009 www.hattrickheaven.com
// Strictly Software Development  www.strictly-software.com

// Contains global objects used for site and visitor settings and objects to aid in transaltions etc

var H = Hattrick = {
		
	version: "1.01",
	
	createDate: "2009-May-23",	
	
	EnhanceCSSDoc: true, //if on then if browser supports enhanced CSS whether to run the enhance function that modifies CSS classes
	
	FlashMaxCurVersion : 10, //the latest current version of flash available to download on web. Needed to check that user has flash installed
	
	FlashMinVersion: [6,65], //when using flash and checking for user version the min version they must have (will link to download page) [major,major+min] (eg 8.3 would be [8,83])

	ForceCustomDebug: true, // when debugging force debug in my own little DIV appended to bottom of screen e.g for chrome/safari/IE may want to do this

	SkipDuplicates : true, // when loading various pieces of content then store the links and don't allow dupes

	ContentURL : [], // holds urls of content to help skip dupes

	ConvertLanguage : function(lan){  // converts english variants to "en"
		ShowDebug("IN ConvertLanguge = " + lan);			
		var r = "";
		if(!S.isEmpty(lan)){
			if(lan.substring(0,2)=="en"){
				r = "en"; //for English variants we use "en" only instead of "en-gb" "en-us" etc
			}else{
				r = lan;
			}
		}
		ShowDebug("return " + r);
		return r;
	},

	// Main football feeds to use on main page
	MainNewsFeeds : ["http://rss.soccernet.com/c/668/f/8493/index.rss","http://mf.feeds.reuters.com/reuters/UKWorldFootballNews","http://www.skysports.com/rss/0,20514,11095,00.xml","http://www.premierleague.com/rss/ptv/page/ArticleIndex/0,,12306~2233528,00.xml","http://www.4thegame.com/rss/news.d/fap","http://newsrss.bbc.co.uk/rss/sportonline_world_edition/football/eng_prem/rss.xml","http://www.soccer365.com/soccer365_news.xml"]

};

// code used on each page in hattrick heaven to determine the current users location in the world and language
// we can use this to then select content for videos, blogs, news and search options


(function(){

	V = H.Visitor = {
		
		sysDefLanguage : "en", // the language I wrote the system in that transalations will be done from en=English

		//userLocation : google.loader.ClientLocation,

		Latitude : google.loader.ClientLocation.latitude,

		Longitude : google.loader.ClientLocation.longitude,

		CountryCode : google.loader.ClientLocation.address.country_code,

		Country : google.loader.ClientLocation.address.country,

		Region : google.loader.ClientLocation.address.region,

		City : google.loader.ClientLocation.address.city,

		BrowserLanguage : (navigator.language || navigator.browserLanguage || this.sysDefLanguage), // the language currently set in users browser
		
		Language : "",

		LocalLeague : "",  //the nearest gradeA league to the country code that the visitor comes from

		isEnglish : false,


		GetLeagueTitle : function(geoCode){
		
			ShowDebug("IN GetLeagueTitle");

			ShowDebug("visitor country = " + V.Country + " - Code = " + V.CountryCode);

			var league = "";

			geoCode = geoCode || V.CountryCode;

			ShowDebug("geoCode = " + geoCode);

			switch (geoCode)
			{
				case 'AF': 
				league = "Afghanistan"; break;
				case 'AL': 
				league = "Kampionati Kombëtare"; break;
				case 'DZ': 
				league = "Algeria"; break;
				case 'AD': 
				league = "Lliga Nacional"; break;
				case 'AO': 
				league = "Girabola"; break;
				case 'AI': 
				league = "Anguilla"; break;
				case 'AR': 
				league = "Primera A"; break;
				case 'AM': 
				league = "STAR Premier League"; break;
				case 'AW': 
				league = "Division di Honor"; break;
				case 'AU': 
				league = "Australia"; break;
				case 'AT': 
				league = "Austria"; break;
				case 'AZ': 
				league = "Yuksak Liqa"; break;
				case 'BS': 
				league = "BFA Senior League"; break;
				case 'BH': 
				league = "Bahrain League"; break;
				case 'BD': 
				league = "Citycell B League"; break;
				case 'BB': 
				league = "Digicel Premiere League"; break;
				case 'BY': 
				league = "Vysshaya Liga"; break;
				case 'BE': 
				league = "Jupiler Pro League"; break;
				case 'BZ': 
				league = "RFG Insurance Cup Tournament"; break;
				case 'BJ': 
				league = "Championnat National du Bénin"; break;
				case 'BM': 
				league = "Premier Division"; break;
				case 'BT': 
				league = "Bhutan"; break;
				case 'BO': 
				league = "Nacional"; break;
				case 'BW': 
				league = "BeMobile Premier League"; break;
				case 'BR': 
				league = "Série A"; break;
				case 'BG': 
				league = "A PFG"; break;
				case 'BI': 
				league = "Burundi"; break;
				case 'KH': 
				league = "Cambodian Premier League"; break;
				case 'CM': 
				league = "MTN Elite One"; break;
				case 'CA': 
				league = "Canadian Soccer League"; break;
				case 'TD': 
				league = "Chad"; break;
				case 'CL': 
				league = "Primera División"; break;
				case 'CO': 
				league = "Copa Mustang"; break;
				case 'KM': 
				league = "Championnat des Comores"; break;
				case 'CG': 
				league = "Linafoot"; break;
				case 'HR': 
				league = "Croatia"; break;
				case 'CU': 
				league = "Campeonato Nacional de Fútbol"; break;
				case 'CY': 
				league = "Marfin Laiki League"; break;
				case 'DK': 
				league = "SAS Ligaen"; break;
				case 'DJ': 
				league = "Djibouti"; break;
				case 'DM': 
				league = "Dominica"; break;
				case 'EC': 
				league = "Ecuador"; break;
				case 'EG': 
				league = "Egyptian League"; break;
				case 'GB': 
					// The country seems to always be United Kingdom however it may change??
					if(V.Country == "England"){
						league = "Barclays Premier League"; 
					}else if(V.Country == "Scotland"){
						league = "Clydesdale Bank Premier League";
					}else if (V.Country == "Wales"){
						league = "Welsh Premier League";
					// work ou long/lat by using towns on borders
					}else{
						ShowDebug("Check Longitude = " + V.Longitude + " and latitude = " +V.Latitude);
						if(V.Latitude > 55.7704){ 
							league = "Clydesdale Bank Premier League";
						}else if(V.Longitude< -2.7175){
							league = "Welsh Premier League";
						}else{
							league = "Barclays Premier League"; 
						}
					}
					break;
				case 'ER': 
				league = "Eritrea"; break;
				case 'EE': 
				league = "Meistriliiga"; break;
				case 'ET': 
				league = "Ethiopian Premier League"; break;
				case 'FJ': 
				league = "NewWorld National Football League"; break;
				case 'FI': 
				league = "Veikkausliiga"; break;
				case 'FR': 
				league = "Ligue 1"; break;
				case 'GA': 
				league = "Championnat National de Division 1"; break;
				case 'GM': 
				league = "GFA League First Division"; break;
				case 'GE': 
				league = "Umaglesi Liga"; break;
				case 'DE': 
				league = "Bundesliga"; break;
				case 'GH': 
				league = "Glo Premier League"; break;
				case 'GR': 
				league = "Super League"; break;
				case 'GD': 
				league = "GFA Premier Division"; break;
				case 'GU': 
				league = "Guam"; break;
				case 'GT': 
				league = "Liga Nacional de Guatemala"; break;
				case 'GN': 
				league = "Guinea"; break;
				case 'GY': 
				league = "Guyana"; break;
				case 'HT': 
				league = "Digicel Première Division"; break;
				case 'HN': 
				league = "Primera División"; break;
				case 'HU': 
				league = "Soproni Liga"; break;
				case 'IS': 
				league = "Landsbankadeildin"; break;
				case 'IN': 
				league = "I League"; break;
				case 'ID': 
				league = "Liga Super"; break;
				case 'IR': 
				league = "Iran Pro League"; break;
				case 'IQ': 
				league = "Iraqi League"; break;
				case 'IL': 
				league = "Israel"; break;
				case 'IT': 
				league = "Serie A TIM"; break;
				case 'JM': 
				league = "Digicel Premier League"; break;
				case 'JP': 
				league = "Japan"; break;
				case 'JO': 
				league = "Jordan League"; break;
				case 'KZ': 
				league = "Super league"; break;
				case 'KE': 
				league = "Kenyan Premier League"; break;
				case 'KW': 
				league = "Kuwait League"; break;
				case 'KG': 
				league = "Vysshaja Liga"; break;
				case 'LA': 
				league = "Laos"; break;
				case 'LV': 
				league = "LMT Virsliga"; break;
				case 'LB': 
				league = "Lebanese League"; break;
				case 'LS': 
				league = "Buddie Premier League"; break;
				case 'LR': 
				league = "Liberia"; break;
				case 'LY': 
				league = "League Division 1"; break;
				case 'LI': 
				league = "Liechtenstein"; break;
				case 'LT': 
				league = "A Lyga"; break;
				case 'LU': 
				league = "BGL League"; break;
				case 'MO': 
				league = "Macau"; break;
				case 'MG': 
				league = "THB Ligue des Champions"; break;
				case 'MW': 
				league = "tnm Super League"; break;
				case 'MY': 
				league = "Super League"; break;
				case 'MV': 
				league = "Presidents Cup"; break;
				case 'ML': 
				league = "Mali"; break;
				case 'MT': 
				league = "BOV Premier League"; break;
				case 'MR': 
				league = "Première Division"; break;
				case 'MU': 
				league = "Barclays League"; break;
				case 'MX': 
				league = "1a División"; break;
				case 'MD': 
				league = "Divizia Nationala"; break;
				case 'MN': 
				league = "Mongolian Championship"; break;
				case 'ME': 
				league = "Prva crnogorska liga"; break;
				case 'MS': 
				league = "Montserrat"; break;
				case 'MA': 
				league = "Championnat National Botola"; break;
				case 'MZ': 
				league = "Moçambola"; break;
				case 'MM': 
				league = "Myanmar"; break;
				case 'NA': 
				league = "MTC Namibia Premier League"; break;
				case 'NP': 
				league = "Nepal"; break;
				case 'NL': 
				league = "Eredivisie"; break;
				case 'NI': 
				league = "Campeonato Nacional"; break;
				case 'NE': 
				league = "Première Division"; break;
				case 'NG': 
				league = "Nigerian Premier League"; break;
				case 'NO': 
				league = "Tippeligaen"; break;
				case 'OM': 
				league = "OFA Oman Mobile League"; break;
				case 'PK': 
				league = "Pakistan Premier League"; break;
				case 'PS': 
				league = "Palestine League"; break;
				case 'PA': 
				league = "Torneo ANAPROF"; break;
				case 'PY': 
				league = "Division de Honor"; break;
				case 'PE': 
				league = "Primera División"; break;
				case 'PH': 
				league = "Filipino Premier League"; break;
				case 'PL': 
				league = "Orange Ekstraklasa"; break;
				case 'PT': 
				league = "Liga Sagres"; break;
				case 'QA': 
				league = "Qatar League"; break;
				case 'RO': 
				league = "Liga I"; break;
				case 'RU': 
				league = "Russian Football Premier League"; break;
				case 'RW': 
				league = "Primus National Football League"; break;
				case 'WS': 
				league = "Samoa"; break;			
				case 'SN': 
				league = "Championnat National"; break;
				case 'RS': 
				league = "Jelen SuperLiga"; break;
				case 'SC': 
				league = "Division One"; break;
				case 'SG': 
				league = "Singapore"; break;
				case 'SK': 
				league = "Corgon Liga"; break;
				case 'SI': 
				league = "Prva liga Telekom Slovenije"; break;
				case 'SO': 
				league = "Somalia"; break;
				case 'ES': 
				league = "Liga BBVA"; break;
				case 'SD': 
				league = "Sudanese League"; break;
				case 'SR': 
				league = "Hoofdklasse SVB"; break;
				case 'SZ': 
				league = "MTN Premier League"; break;
				case 'SE': 
				league = "Allsvenskan"; break;
				case 'CH': 
				league = "Axpo Super League"; break;
				case 'SY': 
				league = "Syrian League"; break;
				case 'TJ': 
				league = "Tajik League"; break;
				case 'TZ': 
				league = "Premier League"; break;
				case 'TH': 
				league = "Thailand League"; break;
				case 'TG': 
				league = "Togo"; break;
				case 'TO': 
				league = "Tonga"; break;
				case 'TN': 
				league = "Ligue 1"; break;
				case 'TR': 
				league = "Turkcell Süper Lig"; break;
				case 'TM': 
				league = "Ýokary Liga"; break;
				case 'UG': 
				league = "Super League"; break;
				case 'UA': 
				league = "UPL"; break;
				case 'UY': 
				league = "Primera División Profesional"; break;
				case 'US': 
				league = "MLS"; break;
				case 'UZ': 
				league = "Oliy Liga"; break;
				case 'VU': 
				league = "Port Vila Football League"; break;
				case 'VE': 
				league = "Primera Division"; break;
				case 'VN': 
				league = "VDQG Petro Vietnam Gas"; break;			
				case 'YE': 
				league = "Yemen League"; break;
				case 'ZM': 
				league = "FAZ Super Division"; break;
				case 'ZW': 
				league = "Premier Soccer League"; break;
				default:
				league = V.Country;
			}

			ShowDebug("league = " + league);

			return league;

			ShowDebug("RETURN");

		}

		
	}

	
	ShowDebug("V.BrowserLanguage = " + V.BrowserLanguage);
	ShowDebug("V.Region = "+V.Region);

	 // set visitors language making sure "en-gb", "en-us" is converted to "en"
	V.Language = H.ConvertLanguage(V.BrowserLanguage);

	V.isEnglish = (V.Language=="en") ? true : false; //check for english variant e.g en-gb, en-us

	V.LocalLeague = V.GetLeagueTitle();

	//S.enumObj(google.loader.ClientLocation);
	//S.enumObj(google.loader.ClientLocation.address);

	ShowDebug("V.Language = " + V.Language);
	ShowDebug("V.isEnglish = " + V.isEnglish);
	ShowDebug("V.LocalLeague = "+V.LocalLeague);
})();

ShowDebug("V.sysDefLanguage = " + V.sysDefLanguage);

// object to handle search terms for blogs, news and other feeds with transaltion
SR = H.Search = function(){

	// use English instead of country code GB or UK as we get more results!!!
	this.defaultQuery = "Premiership Football";  // use when no other terms available and translate if we need to??

	this.searchTerms = ""; // the search terms set for a search
	
	this.LastTranslated = "";  // last translated piece of text

	this.TranslateOutput = ""; // destination to put a translated piece of text

	this.NeedsTranslation = false;

	this.SearchType = "blogs"; // type of search to look for e.g blog, news, video or anything

	// default to system language I wrote in otherwise override per page
	this.ContentLanguage = V.sysDefLanguage; // this is set per page as we output each page in each language if the users language differs we translate

}

H.Search.prototype = {


	// if called we use the defaults set in this object for searching for football related content
	// (set when building the page server-side! e.g for Spannish set to a spannish term)
	SetUpSearch : function(){
		var self = this;

		ShowDebug("IN SetUpSearch");
		ShowDebug("SR.SearchType = " + self.SearchType + " OR " + self.SearchType);
		ShowDebug("visitor language =  " + V.Language + " isEnglish = " + V.isEnglish + " BrowserLanguage = " + V.BrowserLanguage);
		ShowDebug("page langugage = " + self.ContentLanguage);
	
		// Create default search terms if none have been provided
		ShowDebug("current search terms = " + self.searchTerms);

		if(S.isEmpty(self.searchTerms)){
			ShowDebug("Build search terms");
			

			if(V.CountryCode == "GB"){
				ShowDebug("user is based in UK so try and locate nearest big club by matching visitors city = " +V.City);

				var c = new Array("London","Liverpool","Manchester","Newcastle","Glasgow","Birmingham","Bristol","Edinburgh")
				if(!S.isEmpty(V.City)){
					ShowDebug("user has city so try to match array = " + c.toString());
					var r = S.posArray(V.City,c);
					ShowDebug("did we find visitor city " + V.City + " in array = " + r);
					if(r>-1){
						ShowDebug("yes so return clubs");
						var clubs = "", town = c[r];
						ShowDebug("looks like users city " + V.City + " is a major football city so customise terms for town = " + town);					
						switch (town)
						{
							case "London":
								clubs = "Arsenal, Tottenham, Spurs, Chelsea, Fulham, West Ham, Brentford, Gooners, Hammers, QPR, Queens Park Rangers"; break;
							case "Liverpool" : 
								clubs = "Liverpool, Everton"; break;
							case "Manchester":
								clubs = "Manchester United, Manchester City, Man UTD, Man City"; break;
							case "Glasgow": 
								clubs = "Glasgow Rangers, Celtic"; break; 
							case "Edinburgh":
								clubs = "Hearts, Hibernian";break;
							case "Birmingham":
								clubs = "Birmingham City, Aston Villa"; break;
							case "Bristol":
								clubs = "Bristol City, Bristol Rovers"; break;
							default:
								clubs = V.City;					
						}
						ShowDebug("clubs to search for = " + clubs);
						self.searchTerms = S.RTrim(clubs + " football " + self.SearchType);
					}
				}
			}
		}

		ShowDebug("Search Terms currently = " + self.searchTerms);

		// if blank use local country league
		if(S.isEmpty(self.searchTerms)){
			if(!S.isEmpty(V.LocalLeague)){
				ShowDebug("is blank so use local league");
				self.searchTerms = S.RTrim(V.LocalLeague + " "+ self.SearchType);
			}else{
				ShowDebug("is blank so use use default = " + self.defaultQuery + " AND " + self.SearchType)
				self.searchTerms = S.RTrim(self.defaultQuery + " " + self.SearchType);
			}
			ShowDebug("now its = " + self.searchTerms);
		}

		ShowDebug("Search Terms currently = " + self.searchTerms);
		
		return self.searchTerms;
	},

	// Translate method
	Translate : function(txt,langTo,langFrom,outputTo,destFunc){
		
		ShowDebug("IN Translate "+ txt + ", langTo = " + langTo + ", langFrom = " + langFrom + ", " + outputTo + ", " + destFunc);

		var self = this;
		var result = "";
		
		// if no language passed in then use system default
		langFrom = (langFrom||V.sysDefLanguage);

		ShowDebug("langFrom = " + langFrom + " translate to " + langTo);
		
		// if both the same no need to translate
		if(langTo===langFrom){
			ShowDebug("no need to translate");
			// create dummy result function so we can share it with an actual translation
			var result = {error:false,translation:txt}
			// run the function we always run when a translation is complete
			self.TranslateComplete(result, destFunc, outputTo);
		}else{

			// reset last translation
			this.LastTranslated = "";

			ShowDebug("Run Google.Language.Translate txt = " + txt)

			google.language.translate(txt, langFrom, langTo, function(result){
				ShowDebug("google transaltion finished");
				
				self.TranslateComplete(result, destFunc, outputTo);

			});
		}	
		
	},

	TranslateComplete : function(result, func, outputTo){
		ShowDebug("IN Translated result = " + result +" - " + func + ", " + outputTo);
		
		var self = this;
		var el,text = ""; //translated text
		if (!result.error)
		{
			text = result.translation;
			ShowDebug("translated = " + text);
			
			// store last translated term for reference
			self.LastTranslated = text;

			if(outputTo){

				if(S.isString(outputTo)){
					ShowDebug("outputTo is string so get element by id")
					el = G(outputTo);
					el.innerHTML = text;
				}else if(S.isDOMobj(outputTo)){
					ShowDebug("outputTo is DOM object")
					el = outputTo;
					el.innerHTML = text;
				}else if(S.isObject(outputTo)){
					ShowDebug("outputTo is object - jquery")
					el = outputTo.html(text);
				}
				
				ShowDebug("element should be set to = " + text);
			}

			// if we had a function to run on complete then do so
			ShowDebug("do we have a function to run? = " + typeof(func))
			if(typeof(func)=="function"){
				//call function passing the translated term as a parameter
				func.call(this,text);
			}
		}else{
			ShowDebug("error in translation = " + result.error.toString());
		}
	},
		
	TranslateContents : function(contents){
		var self = this;
		ShowDebug("IN TranslateContents = " + contents.toString());
		if(contents){
			for(var x=0,i=contents.length;x<i;x++){
				(function(){
					ShowDebug("get content of " + contents[x]);
					var cur = G(contents[x]).innerHTML;
					ShowDebug("translate " + cur);
					self.Translate(cur,V.Language,V.sysDefLanguage,contents[x],"");
				})()
			}
		}
	}
}

// Object to handle loading feeds from Googles APIs
F = H.Feeder = function(){

	this.searchQuery = "";

	this.translateTo = ""; // use user default

	this.FeedType = "blogs"; // type of feed

	this.FeedOutputElement = ""; // ID of div to output feed data

	this.OutputNo = 10; // no of items from feeds to show

	this.ShowSnippet = false; // whether to show the content snippet under the title

	this.FeedItemFunction = null; // contains the function used to add the feed item into the DOM

	this.ClickEventFunction = null; // contains a reference to any function that needs to be bound to the link

	// I default both of these to true as if we convert a search term "Russian Football" from en to ru we should
	// get russian results only but we may not. Therefore translating the results as well to russian may help plus
	// if the content is already russian it shouldn't mess up. In theory though we should only need to translate the search.
	this.TranslateSearch = true; // if visitors language is different from content do we translate the search query

	this.TranslateResults = false; // if visitors language is different from content do we translate results from feed searches

	this.Keywords = ""; // pass in words that must be in the content of the feed for it to be displayed use || to separate items

	this.TranslatedKeywords = ""; // holds the translated version of the keywords if supplied (see above)

	this.KeywordType = "AND"; // either OR or AND if its AND then all keywords must match OR only one

	this.ItemsPerFeed = 2; // no of items per feed to return when outputting results, OutputNo is the total no to show from all feeds

	this.AttachContentLoader = false, // if true adds my content loader function so user doesnt go off page

	this.FeedIDPrefix = 0; // set to unique value when looping through feeds manually so that translations don't go over existing ones
}

H.Feeder.prototype = {

	findFeeds : function(){
		ShowDebug("In FindFeeds for type = "+this.FeedType)
		ShowDebug("translateTo = " + this.translateTo + " searchQuery = "+ this.searchQuery);
		var self = this;
		var trans = self.translateTo;
		var searchObj = new H.Search(); //create new instance of my search object to handle any translation

		// set up languages and check whether a transaltion is required

		// if no specific language set for translation use visitors language
		var lanTo = (S.isEmpty(self.translateTo)) ? V.Language : self.translateTo;

		// if no specific content language set use sys default e.g if not specified that content is in XX use default of XX
		var lanFrom = (searchObj.ContentLanguage != V.sysDefLanguage) ? searchObj.ContentLanguage : V.sysDefLanguage;

		// if no specific query passed in get default
		var query = self.searchQuery;
		if(S.isEmpty(query)){
			ShowDebug("set Search.SearchType to " + self.FeedType);
			searchObj.SearchType = self.FeedType;
			ShowDebug("check = " +searchObj.SearchType);
			query = searchObj.SetUpSearch(); //get search terms
		}

		// if languages match no need for translation however we may want to do the search in English and then
		// translate each result rather than translate the search query in the hope of just getting results in the desired language
		if(lanFrom == lanTo){
			ShowDebug("content language is same as required language (visitors OR supplied value)");
			searchObj.NeedsTranslation = false; //reset
		}else{			
			ShowDebug("content language is different from user language so translate");
			searchObj.NeedsTranslation = true;
		}

		ShowDebug("query = " + query + " - needs translating = " + S.convertFromBool(searchObj.NeedsTranslation));
		var el = self.getFeedOutputElement;
		ShowDebug("output results to "+ el);
		
		// now we may need a translation due to languages not matching (content vs visitor) but do we translate the search query
		// or just the results or both OR neither!!
		if(searchObj.NeedsTranslation && (self.TranslateSearch || self.TranslateResults)){
			ShowDebug("Translate either search query or results or both")
				
			if(self.TranslateSearch){
				// do we also need to translate results?
				if(self.TranslateResults){
					ShowDebug("translate search query and the results");

					if(this.Keywords != ""){
						ShowDebug("translate keywords as well")
						searchObj.Translate(self.Keywords,lanTo,lanFrom,"",
							function(transKey){
								ShowDebug("set translated keywords = " + transKey);
								self.TranslatedKeywords = transKey;	
								searchObj.Translate(query,lanTo,lanFrom,"",
								function(transSearch){							
									ShowDebug("in function called when translation done transSearch = "+ transSearch + " H.Search.LastTranslated = "+ searchObj.LastTranslated);
									google.feeds.findFeeds(transSearch, function(result){  self.loadFeedContent(result,el,true,lanTo,lanFrom); });
								});
							})
					}else{
						searchObj.Translate(query,lanTo,lanFrom,"",
							function(transSearch){							
								ShowDebug("in function called when translation done transSearch = "+ transSearch + " H.Search.LastTranslated = "+ searchObj.LastTranslated);
								google.feeds.findFeeds(transSearch, function(result){  self.loadFeedContent(result,el,true,lanTo,lanFrom); });
							});
					}
				}else{
					ShowDebug("just translate search query but leave results in the language of the feed result");
					
					if(this.Keywords != ""){
						ShowDebug("translate keywords as well")
						searchObj.Translate(self.Keywords,lanTo,lanFrom,"",
							function(transKey){
								ShowDebug("set translated keywords = " + transKey);
								self.TranslatedKeywords = transKey;								
								searchObj.Translate(query,lanTo,lanFrom,"",
									function(transSearch){							
										ShowDebug("in function called when translation done transSearch = "+ transSearch + " H.Search.LastTranslated = "+ searchObj.LastTranslated);
										google.feeds.findFeeds(transSearch, function(result){  self.loadFeedContent(result,el,false); });
									});

							})
					}else{
						// if we need to do a translation then we do that and once complete we get the feeds
						searchObj.Translate(query,lanTo,lanFrom,"",
							function(transSearch){							
								ShowDebug("in function called when translation done transSearch = "+ transSearch + " H.Search.LastTranslated = "+ searchObj.LastTranslated);
								google.feeds.findFeeds(transSearch, function(result){  self.loadFeedContent(result,el,false); });
							});
					}
				}
			}else{ // need to translate results
				ShowDebug("no translation of query just translate feed results");
				// do keywords
				if(this.Keywords != ""){
					ShowDebug("translate keywords as well")
					searchObj.Translate(self.Keywords,lanTo,lanFrom,"",
						function(transSearch){
							ShowDebug("set translated keywords = " + transSearch);
							self.TranslatedKeywords = transSearch;
							google.feeds.findFeeds(query, function(result){ self.loadFeedContent(result,el,true,lanTo,lanFrom);} );
						})
				}else{
					ShowDebug("set translated keywords = " + transSearch);
					self.TranslatedKeywords = transSearch;
					google.feeds.findFeeds(query, function(result){ self.loadFeedContent(result,el,true,lanTo,lanFrom);} );
				}
			}
		}else{
			ShowDebug("no translation just load feeds")
			self.TranslatedKeywords = self.Keywords;
			google.feeds.findFeeds(query, function(result){ self.loadFeedContent(result,el);} );
		}
		ShowDebug("finished in findFeeds")
		return;
	},

	loadFeed : function(url){
		ShowDebug("in loadFeed from url = " + url);

		var self = this;		
		var translate,trans = self.translateTo;
		var searchObj = new H.Search(); //create new instance of my search object to handle any translation

		ShowDebug("output results to "+ self.getFeedOutputElement);
		
		var el = G(self.getFeedOutputElement); 
		var results,show = {}; //store URLs we show to prevent dupes
		if(!el) return;
		
		// set up languages and check whether a transaltion is required

		// if no specific language set for translation use visitors language
		var lanTo = (S.isEmpty(self.translateTo)) ? V.Language : self.translateTo;

		// if no specific content language set use sys default e.g if not specified that content is in XX use default of XX
		var lanFrom = (searchObj.ContentLanguage != V.sysDefLanguage) ? searchObj.ContentLanguage : V.sysDefLanguage;
				
		if(lanTo == lanFrom){
			ShowDebug("content language is same as page content language");
			translate = false; //reset
		}else{
			ShowDebug("content language is different from user language so translate");
			translate = true;
		}		
		
		// set then number of items from this feed to return
		var max = self.OutputNo || 20;
		var shown = 0;
		ShowDebug("want to show " + self.OutputNo + " but set max to get to " + max);

		var feed = new google.feeds.Feed(url);
		//feed.setResultFormat(google.feeds.Feed.MIXED_FORMAT);
		feed.setNumEntries(max); //sets number of items
		feed.includeHistoricalEntries();
		feed.load(function(result){			
			//D.debug=true;
			ShowDebug("loaded result = " + result)			
			if (result.error){
				ShowDebug("result.error!! ")
				S.enumObj(result.error);
				el.innerHTML = 'No Results Found'; 
				return; 
			}else{
				ShowDebug("there are " + result.feed.entries.length + " entries in feed");				
				//items = result.xmlDocument.getElementsByTagName("item");
				for (var i = 0,z= (result.feed.entries.length); i<z; i++) {           
					var entry = result.feed.entries[i];            
					ShowDebug("do entry " + i);
					if(entry){
						S.enumObj(entry);
						// skip null entries which do happen
						//ShowDebug("check entry.title !== null its " + entry.title + " - " + typeof(entry.title))
						if(!S.isEmptyVal(entry.title) && !S.isEmptyVal(entry.contentSnippet) && !S.isEmptyVal(entry.link)){
							ShowDebug("this entry.link = " + entry.link + " check it doesn't already exist show[entry.link] = " + show[entry.link] + " and not in global array = " + S.inArray(entry.link,H.ContentURL) + " which has a length of " + H.ContentURL.length);
							if(!show[entry.link] && !show[entry.contentSnippet] && !S.inArray(entry.link,H.ContentURL)){														
								show[entry.link]=true; //flag to prevent dupes
								show[entry.contentSnippet]=true;
								shown++;
								// do we skip dupe links on same page from multiple feeds
								if(H.SkipDuplicates){
									// store in global object so that other feeds on same page don't load the same link
									ShowDebug("Store in global array to prevent dupes");
									H.ContentURL.push(entry.link);
									ShowDebug("now length of global array = " + H.ContentURL.length + " shown = " + shown);
									if(shown===1){
										ShowDebug("look at array")
										for(var m=0,l=H.ContentURL.length;m<l;m++){
											ShowDebug("array item " + H.ContentURL[m] + " does it match == " + entry.link + " ??");
										}
									}
								}
								
								//ShowDebug("show["+entry.link+"] = " + show[entry.link]);
								
								self.createFeedItem(el,entry,self.FeedType,shown,translate,lanTo,lanFrom);
								
							}
						}
					}
				}
			}
		});
		
		ShowDebug("finished in loadFeed");
	},


	loadFeedContent : function(result,elOutput,translate,tranTo,tranFrom){
		ShowDebug("IN loadFeedContent elOutput = "+ elOutput + ", translate = " + translate+ ", tranTo = " + tranTo + ", tranFrom = " + tranFrom);
		var el = G(elOutput); 
		var results,show = {}; //store URLs we show to prevent dupes
		if(!el) return;
		if (result.error || result.entries.length <= 0) {
			el.innerHTML = 'No Results Found'; 
			return; 
		}else{
			results = result.entries.length;	
		}
		var self = this;
		self.OutputNo = self.OutputNo || 10; //default to 10
		var lnk = self.FeedType + "_lnk", para = self.FeedType + "_para";

		// to make sure we get X items we look at that number * 2 and get 2 items per feed
		var max = self.OutputNo * 2, shown = 0;
		if(max>results){ max=results; } //cannot loop through more feeds than we have
		ShowDebug("there are " + results + " feeds to iterate through");
		ShowDebug("want to show " + self.OutputNo + " but set max to get to " + max);

		if(self.TranslatedKeywords!=""){								
			var a = self.TranslatedKeywords.split(",");
		}

		//for (var i = 0; i < 4; i++) { 
		for (var i = 0; i < max; i++) { 
			ShowDebug("load feed  "+  result.entries[i].url)
			var feed = new google.feeds.Feed(result.entries[i].url);      
			feed.load(function(result) {       
			if (!result.error) {          
				ShowDebug("we have shown " + shown + " is it > " + self.OutputNo + "??");
				// if we have reached our limit exit
				if(shown >= self.OutputNo){
					ShowDebug("reached output limit of " +self.OutputNo);
					return;
				}
				for (var i = 0; i < (self.ItemsPerFeed||result.feed.entries.length); i++) {           
					var entry = result.feed.entries[i];            
					if(entry){						
						ShowDebug("this entry.link = " + entry.link + " check it doesn't already exist show[entry.link] = " + show[entry.link] + " and not in global array = " + S.inArray(entry.link,H.ContentURL) + " which has a length of " + H.ContentURL.length);
						if(!S.isEmptyVal(entry.title) && !S.isEmptyVal(entry.contentSnippet) && !S.isEmptyVal(entry.link)){
							if(!show[entry.link] && !show[entry.contentSnippet] && !S.inArray(entry.link,H.ContentURL)){
								ShowDebug("its empty so set flag to prevent dupes from same feed")
								show[entry.link]=true; //flag to prevent dupes
								show[entry.contentSnippet]=true;							
								// do we skip dupe links on same page from multiple feeds
								if(H.SkipDuplicates){
									// store in global object so that other feeds on same page don't load the same link
									ShowDebug("Store in global array to prevent dupes");
									H.ContentURL.push(entry.link);
									ShowDebug("now length of global array = " + H.ContentURL.length + " shown = " + shown);
									if(shown===1){
										ShowDebug("look at array")
										for(var m=0,l=H.ContentURL.length;m<l;m++){
											ShowDebug("array item " + H.ContentURL[m] + " does it match == " + entry.link + " ??");
										}
									}
								}
								//ShowDebug("show["+entry.link+"] = " + show[entry.link]);
								if(self.TranslatedKeywords!=""){								
									var f=0,k;
									for(var x=0;x<a.length;x++){
										k = S.Trim(a[x]);
										ShowDebug("look for keyword = " + k);
										if(entry.title.indexOf(k)>-1){
											f++;
										}
										if(!f && entry.content.indexOf(k)>-1){
											f++;
										}
										ShowDebug("found = " + f);
										if(self.KeywordType == "OR"){
											if(f>0){
												self.createFeedItem(el,entry,self.FeedType,shown,translate,tranTo,tranFrom);
												shown++;
												break;
											}
										}
									}
									if(self.KeywordType == "AND"){
										// if all keywords were found
										if(f==a.length){
											self.createFeedItem(el,entry,self.FeedType,shown,translate,tranTo,tranFrom);
											shown++;
										}
									}
								}else{
									self.createFeedItem(el,entry,self.FeedType,shown,translate,tranTo,tranFrom);
									shown++;
								}

							}
						}
					}
				} 
			}})
			
		}	

	},	

	// the default function for adding feed items to the DOM
	createFeedItem : function(el,entry,id,shown,translate,tranTo,tranFrom){
		var self = this;

		ShowDebug("IN createFeedItem id="+id+",shown="+shown+",translate = " + translate + ", tranTo = " + tranTo + ", tranFrom = " + tranFrom);
		el = S.getObj(el); // make sure we have an element

		var li = _d.createElement("LI");								
		var anc = _d.createElement("A");
		// make sure IDs are unqiue
		self.FeedIDPrefix ++;
		var lnk = id+"_lnk"+self.FeedIDPrefix+shown, para = id+"_para"+self.FeedIDPrefix+shown;

		var atts = {id:lnk,href:entry.link,title:entry.title,target:"blank"};
		S.setAttributes(anc,atts);

		ShowDebug("entry content = " + entry.content);
		ShowDebug("entry content = " + entry.contentSnippet);

		if(entry.content == entry.contentSnippet){
			ShowDebug("content is same as snippet so blank it");
			content = null;
		}else{
			content = entry.content;
		}

		anc.appendChild(_d.createTextNode(self.reformat(entry.title)));
		li.appendChild(anc);
		if(self.ShowSnippet){
			var p = _d.createElement("P");
			p.setAttribute("id",para);
			var snippet = self.reformat(entry.contentSnippet); //reformat to HTML decode etc
			p.appendChild(_d.createTextNode(snippet));
			li.appendChild(p);
		}							
		el.appendChild(li);
		
		//D.debug = true
		if(self.AttachContentLoader){
			ShowDebug("bind content loader function");
			addEvent(anc,"click",function(event,content){ContentLoader(event,this,content)});				
		//	$(anc).bind("click",function(event,content){ShowDebug("anc = " + anc +" - this = " + this + " - content = "+ content);ContentLoader(event,anc,content)});				
			
		// do we need to bind any custom click event to the object
		}else if(typeof(self.ClickEventFunction) == "function"){
			ShowDebug("add this function to link = " + self.ClickEventFunction);
			addEvent(anc,"click",self.ClickEventFunction);
		}
		//D.debug = false;
		// if translating then set up functions to change content
		if(translate){
			//ShowDebug("want to translate this content for " + lnk+shown + " and " + para+shown);
			var searchObj = new H.Search();
			searchObj.TranslateOutput = lnk;
			//ShowDebug("convert link = " + searchObj.TranslateOutput);
			// set function to convert text
			ShowDebug("translate link call searchObj.Translate title= " + entry.title +" langTo = " + tranTo + " from = " + tranFrom + " OUTPUT = " + searchObj.TranslateOutput);
			searchObj.Translate(entry.title,tranTo,tranFrom,searchObj.TranslateOutput,"");
			
			// also convert paragraph 
			if(self.ShowSnippet){
				var searchObj2 = new H.Search();
				searchObj.TranslateOutput = para;
				//ShowDebug("convert paragraph = " + searchObj.TranslateOutput);
				ShowDebug("tanslate paragraph call searchObj.Translate title= " + entry.title +" langTo = " + tranTo + " from = " + tranFrom + " OUTPUT = " + searchObj.TranslateOutput);
				searchObj.Translate(snippet,tranTo,tranFrom,searchObj.TranslateOutput,"");
			}
		}
		ShowDebug("RETURN");
	},



	// do some simple reformatting to handle double encoding etc
	reformat : function(c){
		ShowDebug("In reformat = " + c);
		if(S.isEmpty(c)) return "";
		// resolve some double encoding
		n = S.correctEncoding(c);
		n = S.htmlDecode(n);
		n = n.replace(/<!\-\-.*?-->/,"");
		n = S.Trim(n.replace(/[ .;:]+$/,"").replace(/^[ .;:]+/,"")); // remove trailing space, periods or other guff
		// now add period if last char not quotes
		if(/[^\"\']$/.test(n)) n+=".";
		ShowDebug("after reformat = " + n);
		return n;
	},

	getFeedOutputElement : function(){
		ShowDebug("In getFeedOutputElement")
		if(!S.isEmpty(this.FeedOutputElement)){
			ShowDebug("Not empty use " + this.FeedOutputElement);
			return this.FeedOutputElement;
		}
		// work out from feed type
		if(this.FeedType == "blogs"){
			this.FeedOutputElement = "blogs";
		}else if(this.FeedType == "videos"){
			this.FeedOutputElement = "videos";
		}else if(this.FeedType == "news"){
			this.FeedOutputElement = "news";
		}			
		
		ShowDebug("Use " + this.FeedOutputElement);
		return this.FeedOutputElement;

	}
}

// Object to handle search controls from Googles APIs
 
SC = H.SearchControl = function(){
	this.searchQuery = "";

	this.translateTo = ""; // use user default

	this.searchControl = null;

	this.controlType = ""; // the type of search control to output e.g videos, news, blogs etc

	this.getFeedOutputElement = ""; // where to output the content
	
	this.showAllResults = true; // once loaded do we toggle the class to show all results
}

H.SearchControl.prototype = {

	searchSetup : function(){
		ShowDebug("in searchSetup")
		var self = this;

		if(S.isEmpty(self.controlType)){
			ShowDebug("no controlType specified do a web search");
			self.controlType = "web";
		}
		// Create a search control
		self.searchControl = new google.search.SearchControl();
		
		
		ShowDebug("set up a search control of type = " + self.controlType);

		switch (self.controlType)
		{
			case "videos" :
				self.searchControl.addSearcher(new google.search.VideoSearch());
				break;
			case "web" :
				self.searchControl.addSearcher(new google.search.WebSearch());
				break;
			case "blogs" :
				self.searchControl.addSearcher(new google.search.BlogSearch());
				break;
			case "news" :
				self.searchControl.addSearcher(new google.search.NewsSearch());
				break;
			default:
				self.searchControl.addSearcher(new google.search.WebSearch());
				break;
		}
	
		ShowDebug("translateTo = " + self.translateTo + " searchQuery = "+ self.searchQuery);
		var trans = self.translateTo;
		// if no specific language set for translation use visitors
		if(S.isEmpty(self.translateTo)){
			trans = V.Language;
		}
		// if no specific query passed in get default
		var query = self.searchQuery;
		ShowDebug("current video search query = " + query);
		
		var searchObj = new H.Search();

		if(S.isEmpty(query)){
			ShowDebug("get a search query using default and checks against usser location");
			searchObj.searchTerms = ""; // reset
			searchObj.NeedsTranslation = false; //reset
			searchObj.SearchType = "";
			ShowDebug("set search type to = " + searchObj.SearchType);
			ShowDebug("set search terms to = " + searchObj.searchTerms);			
			query = searchObj.SetUpSearch();			
		}

		if(searchObj.ContentLanguage == V.Language){
			ShowDebug("content language is same as page content language");
			searchObj.NeedsTranslation = false; //reset
		}else{
			ShowDebug("content language is different from user language so translate");
			searchObj.NeedsTranslation = true;
		}

		ShowDebug("query = " + query + " - needs translating = " + S.convertFromBool(searchObj.NeedsTranslation));
		ShowDebug("now search type to = " + searchObj.SearchType);
		
		var el = self.getFeedOutputElement;
		ShowDebug("output results to "+ el);

		if(self.showAllResults){
			self.searchControl.setSearchCompleteCallback(this, function(){
				ShowDebug("show all search results");
				$('.gsc-expansionArea').css("display","block");
				ShowDebug("All results on display");
				ShowDebug("do we translate = " + searchObj.NeedsTranslation);
				if(searchObj.NeedsTranslation){
					ShowDebug("translate all results");
					//var s = document.getElementsByClassName('gs-snippet');
					jQuery.each($(".gs-snippet"), function(){
						ShowDebug("JQUERY SNIPPET IN EACH");
						searchObj.Translate($(this).html(),V.Language,V.sysDefLanguage,$(this),"");
					});
					jQuery.each($(".gs-title"), function(){
						ShowDebug("JQUERY SNIPPET IN EACH");
						searchObj.Translate($(this).html(),V.Language,V.sysDefLanguage,$(this),"");
					});					
				}
			});
		}


		if(searchObj.NeedsTranslation){
			ShowDebug("translate first")
			// if we need to do a translation then we do that and once complete we get the feeds
			searchObj.Translate(query,V.Language,V.sysDefLanguage,"",function(query){ self.ExecSearch(query,el,true);} );
		}else{
			ShowDebug("no translation just load videos now execute!!");
			self.ExecSearch(query,el,false);
			ShowDebug("run search with = " + query + ", " + el + " should have been done")
		}
		ShowDebug("finished in searchSetup")
		return;

	},

	ExecSearch : function(query,outputEl,translate){
		ShowDebug("IN ExecSearch query = " + query + ", outputEl = " + outputEl);
		var self = this;

		if(!G(outputEl)){
			ShowDebug("Cannot find element = " + outputEl + " to put results");
			return;
		}else{
			ShowDebug("found " + outputEl+ " for results");
		}
		// tell the searcher to draw itself and tell it where to attach
		self.searchControl.draw(G(outputEl));
 
		// execute an inital search
		// searchControl.execute("English Football Videos");
		ShowDebug("set search for = "+ query);
	
		ShowDebug("searchControl = " + self.searchControl);
			
		self.searchControl.execute(query);
	 
		ShowDebug("execute search");
    }    
    
}


