// search loader

// You can disable shortcuts at the page level by setting the variable: 
// var deactivateSearchShortcuts = true;

var geoMap = {
	US: {code: "",
			noResults: "No Shortcut found. Try a full search of apple.com.",
			viewAll: "View all search results",
			searchText: "Search"},
	ASIA: {code: "asia"},
	AT: {code: "at",
			viewAll: "Alle Suchergebnisse",
			searchText: "Suchen"},
	AU: {code: "au"},
	BE_FR: {code: "bf",
				viewAll: "Afficher tous les résultats",
				noResults: "Pas de résultat. Essayez une recherche apple.com",
				searchText: "Rechercher"},
	BE_NL: {code: "bl",
			viewAll: "Toon alle zoekresultaten",
			noResults: "Niets gevonden. Zoek opnieuw binnen www.apple.com.",
			searchText: "Zoek"},
	BR: {code: "br",
			noResults: "No Shortcut found. Try a full search of apple.com.",
			viewAll: "View all search results",
			searchText: "Search"},
	CA_EN: {code: "ca",
				directory: "/ca"},
	CA_FR: {code:"ca",
				directory: "/ca/fr",
				viewAll: "Afficher tous les résultats",
				searchText: "Recherche"},
	CH_DE: {code: "ce",
				viewAll: "Alle Suchergebnisse",
				noResults: "Kein Treffer in Kurzsuche. Vollsuche auf apple.com",
				searchText: "Suchen"},
	CH_FR: {code: "cr",
				viewAll: "Afficher tous les résultats",
				noResults: "Pas de résultat. Essayez une recherche apple.com",
				searchText: "Rechercher"},
	CN: null,
	DE: {code: "de",
			viewAll: "Alle Suchergebnisse",
			noResults: "Kein Treffer in Kurzsuche. Vollsuche auf apple.com",
			searchText: "Suchen"},
	DK: {code: "dk",
			noResults: "Ingen genvej fundet. Prøv at søge på hele apple.com.",
			viewAll: "Vis alle søgeresultater",
			searchText: "Søg"},
	ES: {code: "es",
			viewAll: "Ver todos los resultados de búsqueda",
			noResults: "Ningún atajo. Búsqueda completa en apple.com",
			searchText: "Buscar"},
	FI: {code: "fi",
			noResults: "Ei oikotietä. Etsi koko apple.com.",
			viewAll: "Katso hakutulokset",
			searchText: "Etsi"},
	FR: {code: "fr",
			viewAll: "Afficher tous les résultats",
			noResults: "Pas de résultat. Essayez une recherche apple.com",
			searchText: "Rechercher"},
	HK: {code: "hk",
				noResults: "找不到快速搜尋結果，請試試 apple.com 的完整搜尋",
				viewAll: "檢視所有搜尋結果",
				searchText: "搜尋"},
	HK_EN: {code: "hk",
				directory: "/hk/en"},
	ID: {code: "id"},
	IE: {code: "ie"},
	IN: {code: "in"},
	IT: {code: "it",
			noResults: "Nessuna scorciatoia trovata. Provate su apple.com",
			viewAll: "Mostra tutti i risultati",
			searchText: "Cerca"},
	JP: {code: "jp",
			noResults: "ショートカットは見つかりませんでした。検索はこちら。",
			viewAll: "すべての検索結果を見る",
			searchText: "Search"},
	KR: {code: "kr",
			noResults: "일치하는 검색결과가 없습니다. 다시 검색하기.",
			viewAll: "검색 결과 전체 보기."},
	LA: {code: "la",
			noResults: "No se encontraron resultados. Intenta en apple.com.",
			viewAll: "Ver todos los resultados de la búsqueda",
			searchText: "Buscar"},
	MX: {code: "mx",
			noResults: "No se encontraron resultados. Intenta en apple.com.",
			viewAll: "Ver todos los resultados de la búsqueda",
			searchText: "Buscar"},
	MY: {code: "my"},
	NL: {code: "nl",
			viewAll: "Toon alle zoekresultaten",
			noResults: "Niets gevonden. Zoek opnieuw binnen www.apple.com.",
			searchText: "Zoek"},
	NO: {code: "no",
			noResults: "Fant ingen snarvei. Søk på hele apple.com.",
			viewAll: "Vis alle søkeresultater",
			searchText: "Søk"},
	NZ: {code: "nz"},
	PH: {code: "ph"},
	PL: {code: "pl",
			noResults: "Fraza nie została odnaleziona. Użyj apple.com.",
			viewAll: "Przeglądaj wszystkie wyniki",
			searchText: "Szukaj"},
	PT: {code: "pt",
			noResults: "Nenhum resultado. Tente pesquisar em apple.com.",
			viewAll: "Ver todos os resultados de pesquisa",
			searchText: "Procurar"},
	RU: {code: "ru",
			noResults: "Ссылок нет. Попробуйте расширенный поиск.",
			viewAll: "Показать все результаты поиска",
			searchText: "Поиск"},
	SE: {code: "se",
			noResults: "Ingen genväg hittad. Sök i hela apple.com.",
			viewAll: "Visa alla sökresultat",
			searchText: "Sök"},
	SG: {code: "sg"},
	TH: {code: "th"},
	TW: {code: "tw",
			noResults: "快速搜尋找不到，試試 apple.com 完整搜尋",
			viewAll: "瀏覽搜索結果",
			searchText: "搜尋"},
	UK: {code: "uk"},
	VN: {code: "vn"},
	ZA: {code: "za"},
	
	PO: null,
	TR: null,
	UA: null,
	RO: null,
	CZ: null,
	HU: null,
	BG: null,
	HR: null,
	GR: null,
	IS: null
};

/**
 * Enhance the global search to direct the new javascript search app 
 * when possible
 */
var enhanceSearch = function(actionUrl) {
	
	var removeElement = function(elementId) {
		
		var element = document.getElementById(elementId);
		element.parentNode.removeChild(element);
	}
	
	document.getElementById('g-search').setAttribute('action', actionUrl);
	document.getElementById('g-search').setAttribute('method', 'GET');
	
	removeElement('search-oe');
	removeElement('search-access');
	removeElement('search-site');
	removeElement('search-lr');
	
}

function loadShortcuts() {
	decorateGlobalSearchInput();
	
	if (typeof(searchCountry) == 'undefined' ) {
		searchCountry = 'us';
	}
	
	if (geoMap[searchCountry.toUpperCase()].directory) {
		//use specified country directory
		var countryDirectory = geoMap[searchCountry.toUpperCase()].directory
	} else if (searchCountry != 'us') {
		//use /countrycode logic 
		var countryDirectory = '/' + searchCountry.replace(/_/, '');
	} else {
		//assume us, which has no coutnry code in path
		countryDirectory = '';
	}
	
	var actionUrls = {
		'global': 'http://www.apple.com' + countryDirectory + '/search/',
		'downloads': 'http://www.apple.com' + countryDirectory + '/search/downloads/',
		'iphone': 'http://www.apple.com' + countryDirectory + '/search/iphone/',
		'ipoditunes': 'http://www.apple.com' + countryDirectory + '/search/ipoditunes/',
		'mac': 'http://www.apple.com' + countryDirectory + '/search/mac/',
		'store': 'http://www.apple.com' + countryDirectory + '/search/store/',
		'support': 'http://www.apple.com' + countryDirectory + '/search/support/'
	}
	
	var actionUrl = actionUrls[searchSection] || 'http://www.apple.com/search/';
	
	enhanceSearch(actionUrl);
	
	var mobile = navigator.userAgent.match(/AppleWebKit/i) && navigator.userAgent.match(/Mobile/i);
	
	if (!mobile && (typeof(deactivateSearchShortcuts) == "undefined" || !deactivateSearchShortcuts)) {
		SearchShortcut.load();
	}
}

function shortcutsPageLoader(newOnload) {
    var currentOnloads = window.onload;
    if (typeof window.onload != 'function') window.onload = newOnload;
    else window.onload = function() { currentOnloads(); newOnload(); };
}

shortcutsPageLoader(loadShortcuts); // run the window onload


var SearchShortcut = {
	///////////////////////////////////////////////////////////////////////////////////
	// Specific Deployment configuration
	///////////////////////////////////////////////////////////////////////////////////

	baseUrl: "http://www.apple.com/global/nav/scripts/shortcuts.php", // path to the php to run against
	minimumCharactersForSearch: 0, // required number of characters to run a search
	entryDelay: 150, // how many miliseconds after a key press to wait to search

	///////////////////////////////////////////////////////////////////////////////////
	// END Deployment configuration
	// DON'T CHANGE ANYTHING BELOW THIS LINE
	///////////////////////////////////////////////////////////////////////////////////
	
	currentRequest: false,
	descriptionCharacters: 90,
	titleCharacters: 39,
	isIe: false,
	init: function() {
		//allow the fullSearchUrl to be overridden during init
		this.fullSearchUrl = document.getElementById('globalsearch').getElementsByTagName('form')[0].getAttribute('action'); 

		this.noResults = geoMap['US'].noResults;
		this.viewAll = geoMap['US'].viewAll;

		if (typeof(searchCountry) != 'undefined' && searchCountry) {
			this.noResults = geoMap[searchCountry.toUpperCase()].noResults || this.noResults;
			this.viewAll = geoMap[searchCountry.toUpperCase()].viewAll || this.viewAll;
		}

		this.html = {
			results: document.getElementById('sp-results').getElementsByTagName('div')[0],
			input: document.getElementById('sp-searchtext')
		};
		
		// some IE 6 fixes:
		if (navigator.userAgent.toLowerCase().indexOf("msie 6.")!=-1) {
			document.getElementById('sp-results').style.left = "171px";
			this.isIe = true;
		}
		this.pausedControllers = []; //TODO may need to clear this out on unload..
	},
	
	track: function(term, destination) {
		if (typeof(s_gi) == 'undefined' || !s_gi) {
			return;
		}

		var globalSuite = "appleglobal";
		var searchSuite = "appleussearch";
		
		var countryCode = null;
		if (typeof(searchCountry) != 'undefined' && searchCountry && searchCountry != "US") {
			countryCode = geoMap[searchCountry.toUpperCase()].code;
		}
		
		if (countryCode) {
			globalSuite = "apple" + countryCode + "global";
			searchSuite = "apple" + countryCode + "search";
		}
		
		if(typeof(s_account) != 'undefined' && s_account.indexOf('appleussearch') == -1) {
			s = s_gi(s_account + "," + searchSuite);
			// alert("Found S_Account:   " + s_account + "," + searchSuite);
		} else {
			s = s_gi(globalSuite + "," + searchSuite);
			// alert("No S_Account:      " + globalSuite + "," + searchSuite);
		}
		
		s.prop4 = "";
		s.g_prop4 = "";
		s.prop6 = "";
		s.g_prop6 = "";
		s.pageName = "";
		s.g_pageName = "";
		s.pageURL = "";
		s.g_pageURL = "";
		s.g_channel = "";
		s.linkTrackVars="eVar2,eVar4,prop7,prop10";
		s.eVar2 = "WWW-sc: " + term.toLowerCase();
		s.prop7 = "WWW-sc: " + term.toLowerCase();
		s.eVar4 = destination;
		s.prop10 = destination;
		s.tl(this,'o','Shortcut Search');
		
	},
	
	go: function(location) {
		SearchShortcut.track(SearchShortcut.searchText, location);
		document.location = location;
	},
	
	search: function(term) {
		
		var url = this.baseUrl + "?q=" + encodeURIComponent(term);
		
		// check for section flag, this should be set in the embedding page
		if (typeof(searchSection) != "undefined" && searchSection) {
			url += "&section="+searchSection;
		}
		
		// check for geo flag, this should be set in the embedding page
		if (typeof(searchCountry) != 'undefined' && searchCountry) {
			url += "&geo=" + searchCountry.toLowerCase();
		}
		
		this.spin();
		
		url += "&transport=js";
		var head = document.getElementsByTagName("head")[0];
		script = document.createElement('script');
		script.id = 'xdShortcutContainer';
		script.type = 'text/javascript';
		script.src = url;
		head.appendChild(script);
		SearchShortcut.scriptLoadTest();

	},
	
	scriptLoadTest: function() {
		// test for the presence of the shortcutXml vaiable from the PHP return
		var loops = 0;
		var t = window.setInterval(function() {
			loops++;
			if (typeof(shortcutXml) != 'undefined') { // we're loaded
				window.clearInterval(t);
			}
			else if(loops > 20) {  // give up testing after 1 second
				window.clearInterval(t);
				document.getElementById('sp-search-spinner').style.display = 'none';
			} 
		}, 50);
	},
	
	loadXmlToDoc: function(text) {
		var xmlDoc;
			
		if (window.ActiveXObject)	{
		  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		  xmlDoc.async = "false";
		  xmlDoc.loadXML(text);
		}	
		else {
		  var dp = new DOMParser();
		  xmlDoc = dp.parseFromString(text,"text/xml");
		}
				
		if (!this.html || !this.html.results) this.init();
		document.getElementById('sp-search-spinner').style.display = 'none';

		this.term = xmlDoc.getElementsByTagName('term')[0].firstChild.nodeValue;
		this.xml = xmlDoc.getElementsByTagName('search_results')[0];
		this.parseResults(this.xml);
		
		if (this.results) {
			this.results.length > 0 ? this.renderResults() : this.renderNoResults();
		}
	},
	
	spin: function() {
		document.getElementById('sp-search-spinner').style.display = 'block';
	},
	
	parseResults: function(xml) {
		// Check for ERROR code in XML, bail if we find it
		var error = xml.getElementsByTagName('error');
		if(error.length > 0) {
			SearchShortcut.hideResults();
			return;
		}
		else {
			var xmlResults = xml.getElementsByTagName('match');
		
			// Results are stored as an array of objects inside this.results
			this.results = new Array();
			for(var i=0; i < (xmlResults.length); i++) {
				var result = xmlResults[i];
				var resultItem = {
					title: result.getAttribute('title'),
					url: result.getAttribute('url'),
					desc: result.getAttribute('copy'),
					category: result.getAttribute('category'),
					priority: result.getAttribute('priority'),
					image: result.getAttribute('image')
				};
				resultItem.url = decodeURIComponent(resultItem.url);
				this.results.push(resultItem);	
			}
		}
	},
	
	renderNoResults: function() {
		var noResultsCopy = this.noResults;
		this.html.results.innerHTML = "";
		var list = document.createElement('ul');
		list.className = 'sp-results';
		listResult = document.createElement('li');
		listResult.className = 'firstCat resultCat';
		list.appendChild(listResult);
		listResult = document.createElement('li');
		listResult.id = 'sp-result-none';
		listResult.className = 'viewall';
		
		var dv = document.createElement('div');
		dv.className = 'hoverbox';
		var lk = document.createElement('a');
		lk.href = this.fullSearchUrl + '?q=' + encodeURIComponent(this.term);
		lk.innerHTML = noResultsCopy;
		
		listResult.appendChild(dv);
		listResult.appendChild(lk);
		
		listResult.url = this.fullSearchUrl + '?q=' + encodeURIComponent(this.term);
		listResult.num = this.results.length;
		listResult.onclick = function() {
			SearchShortcut.go(this.url);
		}
		listResult.onmouseover = function() {
			SearchShortcut.itemSelected = true;
		}
		listResult.onmouseout = function() {
			SearchShortcut.itemSelected = false;
		}
		list.appendChild(listResult);
		this.html.results.appendChild(list);
		document.getElementById('globalsearch').className = 'active';
	},
	
	// selecting only affected movies by screen position is still TBD
	hideAllQuicktimeMovies: function() {
		if (typeof(AC) != 'undefined' && 
			typeof(AC.Quicktime) != 'undefined' && 
			typeof(AC.Quicktime.controllers) != 'undefined') {
				
			//thx qm
			function findPos(obj) {
				var curleft = curtop = 0;
				if (obj.offsetParent) {
					curleft = obj.offsetLeft
					curtop = obj.offsetTop
					while (obj = obj.offsetParent) {
						curleft += obj.offsetLeft
						curtop += obj.offsetTop
					}
				}
				return [curleft,curtop];
			}

			function intersect(xUpLeftA,yUpLeftA,wA,hA, xUpLeftB,yUpLeftB,wB,hB) {

				var xLowRightA = xUpLeftA + wA;
				var yLowRightA = yUpLeftA + hA;

				var xLowRightB = xUpLeftB + wB;
				var yLowRightB = yUpLeftB + hB;

				var left = Math.max(xUpLeftA, xUpLeftB)
				var top = Math.max(yUpLeftA, yUpLeftB)
				var right = Math.min(xLowRightA, xLowRightB)
				var bottom = Math.min(yLowRightA, yLowRightB)

				return right > left && bottom > top;
			}	
			
			var controllers = AC.Quicktime.controllers;


			var dropdown = $('sp-results');
			var dropDimensions = {width: 328, height: 448} //TODO not hardcode this...
			var dropPosition = findPos(dropdown);
		
			var dropX = dropPosition[0] - 328; //when finding the position it's not dispalyed so not in the right spot
			var dropY = dropPosition[1];
		
			var dropRightX = x + dropDimensions.width;
			var dropRightY = y + dropDimensions.height;
		
		
			for (var i = controllers.length - 1; i >= 0; i--){
			
				var movie = controllers[i].movie;
				var movieDimensions = Element.getDimensions(movie);
				var position = findPos(movie);
				
				var x = position[0];
				var y = position[1];
				
				if(intersect(
					x ,y, movieDimensions.width, movieDimensions.height,
					dropX, dropY, dropDimensions.width, dropDimensions.height)) {
						
						this.pausedControllers.push(controllers[i]);
						
						controllers[i].Stop();
						controllers[i].movie.style.visibility = "hidden";
				}
			}

				
		}
		else { // no ac.quicktime, retro-rockit
			var qtm = document.getElementsByTagName('object');
			for (i=0; i<qtm.length; i++) {
				if(typeof(qtm[i].Stop) != 'undefined') qtm[i].Stop();
				try{ // ie dies on this
					if(typeof(qtm[i].getElementsByTagName('embed')[0].Stop) != 'undefined') qtm[i].getElementsByTagName('embed')[0].Stop();
				} catch(er) {}
				qtm[i].style.visibility = "hidden";
			}
		}
	},
	
	showAllQuicktimeMovies: function() {
		if (typeof(AC) != 'undefined' && 
			typeof(AC.Quicktime) != 'undefined' && 
			typeof(AC.Quicktime.controllers) != 'undefined') {
				
			for (var i = this.pausedControllers.length - 1; i >= 0; i--){
				this.pausedControllers[i].movie.style.visibility = "visible";
				
				// FF needs some time to breathe before plugin interaction
				if (navigator.userAgent.match(/Firefox/i)) {
					this.pausedControllers[i].movie.style.zIndex = "100"; //bump to paint repaint
					setTimeout(this.pausedControllers[i].Play.bind(this.pausedControllers[i]), 100);
				} else {
					this.pausedControllers[i].Play();
				}
				
			}
			
			this.pausedControllers = [];
			
		}
		else { // no ac.quicktime, retro-rockit
			var qtm = document.getElementsByTagName('object');
			for (i=0; i<qtm.length; i++) {
				qtm[i].style.visibility = "visible";
				if(typeof(qtm[i].Play) != 'undefined') qtm[i].Play();
				try { // ie dies on this
					if(typeof(qtm[i].getElementsByTagName('embed')[0].Play) != 'undefined') qtm[i].getElementsByTagName('embed')[0].Play();
				} catch(er) {}
			}
		}
	},
	
	startFlashFixTimer: function() {
		var count = 0;
		var i = setInterval(function() {
			SearchShortcut.flashDomRender();
			count++;
			if (count > 50) {
				clearInterval(i);
			}
		}, 10);
	},
	border: 5,
	flashDomFix: function() {
		document.getElementById('sp-results').firstChild.firstChild.style.border = "5px none red";
		document.getElementById('globalsearch').onmousemove = function() {
			SearchShortcut.flashDomRender();
		}		
	},
	
	flashDomRender: function() {
		SearchShortcut.border % 2 == 0 ? 	SearchShortcut.border++ : SearchShortcut.border--;
		var elem = document.getElementById('sp-results').firstChild.firstChild;
		if (elem) elem.style.border = SearchShortcut.border + "px none red";
	},
	
	itemSelected: false,
	
	renderResults: function() {		
		this.html.results.innerHTML = ''; // clear out the current results
		
		var list = document.createElement('ul')
		list.className = 'sp-results';
		
		var resultsByCat = {};
		
		for(var i=0; i<this.results.length; i++) {
			var result = this.results[i];
			
			// truncate the results so they don't overrun the formatting
			var descriptionCopy = unescape(result.desc);
			var titleCopy = "";
			if (descriptionCopy.length > this.descriptionCharacters ) {
				descriptionCopy = descriptionCopy.substring(0, descriptionCopy.lastIndexOf(" ", this.descriptionCharacters-11 )) + "&hellip;";
				titleCopy = unescape(result.desc);
			}
			
			var cleanTitle = unescape(result.title);
			if (cleanTitle.length > this.titleCharacters) cleanTitle = cleanTitle.substring(0, cleanTitle.lastIndexOf(" ", 30)) + "&hellip;";
			
			var listResult = document.createElement('li');
			listResult.id = 'sp-result-' + i;
			listResult.className = 'category-' + unescape(result.category).toLowerCase().replace(/\s+/g, "-");
			
			var dv = document.createElement("div");
			dv.className = "hoverbox";
			
			var image = document.createElement("img");
			image.src = result.image;
			image.title = titleCopy;
			
			var span = document.createElement("span");
			span.className = "text";
			var header = document.createElement("h4");
			
			var link = document.createElement("a");
			var copy = document.createElement("p");
			
			link.href = decodeURIComponent(result.url);
			link.title = titleCopy;
			link.onclick = function() {
				SearchShortcut.go(decodeURIComponent(result.url));
			}
			link.innerHTML = cleanTitle;
			
			copy.innerHTML = descriptionCopy;
			copy.title = titleCopy;
			
			header.appendChild(link);
			span.appendChild(header);
			span.appendChild(copy);
			
			listResult.appendChild(dv);
			listResult.appendChild(image);
			listResult.appendChild(span);

			listResult.url = result.url;
			listResult.num = i;
			
			listResult.onmouseover = function() {
				SearchShortcut.itemSelected = true;
				SearchShortcut.highlight(this);
			}
			listResult.onmouseup = function() {
				SearchShortcut.itemSelected = true;
				SearchShortcut.go(this.url);
			}
			
			// sticking in the hover state in ie - strong arm it out
			listResult.onmouseout = function() {
				SearchShortcut.itemSelected = false;
				SearchShortcut.unhighlight(this);
			}
			
			listResult.priority = parseInt(result.priority);
			
			if (! resultsByCat[result.category]) resultsByCat[result.category] = new Array();
			resultsByCat[result.category].push(listResult);
		}
		
		// mark the first category as the TOP
		var catClass = 'firstCat resultCat'; // as opposed to just 'resultCat'
		
		for (var cat in resultsByCat) { 
			// sanity check cat in case Object has been extended 
			if (!resultsByCat.hasOwnProperty(cat))
				continue;
			
			listResult = document.createElement('li');
			listResult.className = catClass;
			listResult.innerHTML = unescape(cat);
			catClass = 'resultCat'; // back to normal
			list.appendChild(listResult);
			
			for(var r=0; r<resultsByCat[cat].length; r++) { 
				list.appendChild(resultsByCat[cat][r]);
			}	
		}
		
		// View all row
		listResult = document.createElement('li');
		listResult.id = 'sp-result-' + this.results.length;
		listResult.className = "viewall";
	
		var dv = document.createElement('div');
		dv.className = 'hoverbox';
		
		var link = document.createElement('a');
		link.href = this.fullSearchUrl + '?q=' + encodeURIComponent(this.term);
		link.innerHTML = this.viewAll;
	
		listResult.appendChild(dv);
		listResult.appendChild(link);
		
		listResult.url = this.fullSearchUrl + '?q=' + encodeURIComponent(this.term);
		listResult.num = this.results.length;

		listResult.onclick = function() {
			SearchShortcut.go(this.url);
		}
		listResult.onmouseover = function() {
			SearchShortcut.itemSelected = true;
		}
		listResult.onmouseout = function() {
			SearchShortcut.itemSelected = false;
		}
		document.getElementById('globalsearch').className = 'active';
		list.appendChild(listResult);
		
		this.html.results.appendChild(list);
		
		// apply rich media fixes
		this.hideAllQuicktimeMovies();
		if (typeof(flashOnPage) != "undefined" && flashOnPage) {
			this.flashDomFix();	
			this.startFlashFixTimer();
		}
	},

	startKeystrokeTimer: function() {
		if (this.timeoutId) {
			window.clearTimeout(this.timeoutId);
		}
		this.timeoutId = window.setTimeout("SearchShortcut.commitKeystroke()", this.entryDelay);
	},

	commitKeystroke: function() {
		this.search(this.searchText);
	},
	
	hideResults: function(keepTerm, pause) {
		
		//return;  //makes the results stick around for testing purposes
		
		if (!this.html) this.init();
		
		this.selected = null;	// Unselect any divs
		
		document.getElementById('globalsearch').className = "";
		this.html.results.innerHTML = ''; // Shrink it up
		this.showAllQuicktimeMovies(); // start QT back up
				
	},
	
	highlight: function(resultLi) {
		resultLi.className = 'hoverli';
	},
	
	keyHighlight: function(resultLi) {
		if (this.selected) this.selected.className = "";
		this.selected = resultLi;
		resultLi.className = 'hoverli';
	},
	
	unhighlight: function(resultLi) {
		resultLi.className = '';
	},
	
	load: function() {  // hooks in observers for the text field
		
		// add in spinner
		var spinner = document.createElement('img');
		
		if (location.protocol.match(/https/)) {
            spinner.src = "https://ssl.apple.com/global/nav/images/spinner.gif";
		} else {
		    spinner.src = "http://images.apple.com/global/nav/images/spinner.gif";
		}
		
		spinner.width = "11";
		spinner.height = "11";
		spinner.border = "0";
		spinner.alt = "*";
		spinner.id = "sp-search-spinner";
		spinner.style.display = "none";
		document.getElementById('globalsearch').appendChild(spinner);
		
		document.getElementById('g-search').onsubmit = function(evt) {
			return false;
		}
		
		if (navigator.userAgent.match(/AppleWebKit/i)) {
			document.getElementById('sp-searchtext').onkeydown = function(evt) {
				var keyCode = typeof(event) != "undefined" ? event["keyCode"] : evt.keyCode;
				if (! evt) evt = event;

				// ENTER, without option key: if they're holding option 
				//they're probably translating text e.g. romanji to katakana
				if (keyCode == 13 && !evt.altKey) {
					
					if (evt.target.value.length === 0) {
						return false;
					}

					// check for selected element
					if (SearchShortcut.selected) {
						SearchShortcut.go(SearchShortcut.selected.url);
					}
					// if we can't find one, hide results and submit the form
					else {
						SearchShortcut.hideResults();
						document.getElementById('g-search').submit();
					}				
				}
				
			}
		}

		
		
		document.getElementById('sp-searchtext').onkeyup = function(evt) { 
			// special key listeners	
			var keyCode = typeof(event) != "undefined" ? event["keyCode"] : evt.keyCode;
			if (! evt) evt = event;
			
			// DOWN
			if (keyCode == 40 && SearchShortcut.results) {
				try {
					evt.preventDefault();
					evt.stopPropagation();
				} catch(er){ }
			
				if (SearchShortcut.selected && (SearchShortcut.results.length > SearchShortcut.selected.num + 1)) {
					SearchShortcut.keyHighlight(document.getElementById('sp-result-' + (SearchShortcut.selected.num + 1)));
				}
				if (!SearchShortcut.selected && SearchShortcut.results.length > 0) {
					SearchShortcut.keyHighlight(document.getElementById('sp-result-0'));
				}
				SearchShortcut.flashDomRender();
			}
			// UP
			// there is a bug / feature when we listen on key up
			// where the cursor in the text box goes back to the start
			// of the box, the only way to prevent it is to capture the key down
			// but that messes with everything else, still working on a graceful fix.
			else if (keyCode == 38 && SearchShortcut.results) {
				try {
					evt.preventDefault();
					evt.stopPropagation();
				} catch(er){ }
				if (SearchShortcut.selected && SearchShortcut.selected.num > 0) {
					SearchShortcut.keyHighlight(document.getElementById('sp-result-' + (SearchShortcut.selected.num - 1)))
				}
				SearchShortcut.flashDomRender();
			
			}
			// ESCAPE
			else if (keyCode == 27) {
				SearchShortcut.hideResults();
				document.getElementById('sp-searchtext').value = "";
			}
		
			else {
				SearchShortcut.selected = false;
				var q = document.getElementById('sp-searchtext').value;
				q = q.replace(/[%\^\?\!\*\/<>\$]/ig, ''); // remove potentially dangerous character
				q = q.replace(/^\s+/g, '').replace(/\s+$/g, ''); // trim white space before and after
				
				if (q.length < 1 && SearchShortcut.html) {
					SearchShortcut.html.results.innerHTML = '';
					document.getElementById('sp-search-spinner').style.display = 'none';  // no, just change the class here
					SearchShortcut.hideResults();
				} 

				else if (q.length > SearchShortcut.minimumCharactersForSearch) {
					SearchShortcut.searchText = q;
					SearchShortcut.startKeystrokeTimer();
				}
			}
		};
		
	} // end load
}; // END ShortcutSearch

function decorateGlobalSearchInput() {
	var searchField = document.getElementById('sp-searchtext');
	var standIn = null;

	var results = 0;
	
	var placeholder = 'Search';
	if (typeof(searchCountry) == 'undefined' ) {
		searchCountry = 'us';
	}
	if (geoMap[searchCountry.toUpperCase()].searchText) {
		placeholder = geoMap[searchCountry.toUpperCase()].searchText
	}

	var autosave = '';
	
	if(navigator.userAgent.match(/AppleWebKit/i)) {

        if (navigator.userAgent.match(/win/i)) {
            searchField.className += ' not-round';
        }

		searchField.setAttribute('type', 'search');
		if(!searchField.getAttribute('results')) {
			searchField.setAttribute('results', results);
		}
		
		if(null != placeholder) {
			searchField.setAttribute('placeholder', placeholder);
			searchField.setAttribute('autosave', autosave);
		}
		
		searchField.onblur = function() {
			
			if (!SearchShortcut.itemSelected) {
				SearchShortcut.hideResults();
			}
		}
		
	} else {
		
		//prevent browser from doing its own autocomplete, threw odd xul 
		//error on reset sometimes, although this feels a little
		//heavy handed
		searchField.setAttribute('autocomplete', 'off');
		
		//replace the field with a standin while we create the wrapper
		//we can't lose the reference to this field as other objects may
		//have already registered listeners on this field
		
		standIn = document.createElement('input');
		searchField.parentNode.replaceChild(standIn, searchField)

		var left = document.createElement('span');
		left.className = 'left';
	
		var right = document.createElement('span');
		right.className = 'right';
		
		var reset = document.createElement('div');
		reset.className = 'reset';
		
		var wrapper = document.createElement('div');
		wrapper.className = 'search-wrapper';
		
		var alreadyHasPlaceholder = searchField.value == placeholder;
		var isEmpty = searchField.value.length == 0;
		
		if (alreadyHasPlaceholder || isEmpty) {
			searchField.value = placeholder;
			wrapper.className += ' blurred empty';
		}
	
		wrapper.appendChild(left);
		wrapper.appendChild(searchField);
		wrapper.appendChild(right);
		wrapper.appendChild(reset);

		searchField.onfocus = function() { 
		
			var blurred = wrapper.className.indexOf('blurred') > -1;

			//need to check for flag AND placeholder lest somebody need to 
			//search for the placeholder text itself
			if(searchField.value == placeholder && blurred) {
				searchField.value = '';
			}
			
			wrapper.className = wrapper.className.replace('blurred', '');
		}

		searchField.onblur = function() {
			
			if (!SearchShortcut.itemSelected) {
				SearchShortcut.hideResults();
			}
			
			if(searchField.value == '') {
				wrapper.className += ' empty';
				searchField.value = placeholder;
			}
			
			wrapper.className += ' blurred';
		}
		
		searchField.onkeydown = function(evt) {
			

			var keyCode = typeof(event) != "undefined" ? event["keyCode"] : evt.keyCode;
			if (! evt) evt = event;

			// ENTER, without option key: if they're holding option 
			//they're probably translating text e.g. romanji to katakana
			if (keyCode == 13 && !evt.altKey) {
				
				var target = null;
				if (evt.target) {
					target = evt.target;
				} else if (evt.srcElement) {
					target = evt.srcElement;
				}

				if (target.value.length === 0) {
					return false;
				}

				// check for selected element
				if (SearchShortcut.selected) {
					SearchShortcut.go(SearchShortcut.selected.url);
				}
				// if we can't find one, hide results and submit the form
				else {
					SearchShortcut.hideResults();
					document.getElementById('g-search').submit();
				}				
				return;
			}

			
			if(searchField.value.length >= 0) {
				wrapper.className = wrapper.className.replace('empty', '');
			}
			
			resetField();
			
		}
	
		var resetField = function() {
			return( function(evt) {
				
				var escaped = false;
				
				if (!evt) {
					evt = window.event;
				}
				
				if(evt.type == 'keydown') {
					
					if(evt.keyCode != 27) {
						return; //if it's not escape ignore it
					} else {
						escaped = true;
					}
				}
				
				searchField.blur(); //can't change value while in field
				searchField.value = '';
				wrapper.className += ' empty';
				searchField.focus();

			})
		}
		reset.onmousedown = resetField();
	
		if (standIn) {
			standIn.parentNode.replaceChild(wrapper, standIn);
		}
	}
}

