var ACSpecSearch = {

	'specs' : {},
	'pageNumber': 1,
	'locale': 'en_US',
	'akamaiUrl': 'http://km.support.apple.com',
	// Object for retaining search state between AJAX calls - instantiated with defaults
 	'searchState' : { state: "browse", searchTerm: "", facet: "all", sort: "alphabetical", category: "", offset: 0, results: 0 },
 	'pageNamePrefix':'acs::kb::sp',
 	
 	// getting set up!
 	'initialize': function() {
		// defining the function that is called after there has been a change in the product browser
		ACProductBrowser.callbackTrigger = function(strID) {
			ACSpecSearch.searchState.facet = 'all';
			ACSpecSearch.searchAJAX(0, 'recency', strID, 'state_browse');
		};
		
		ACProductBrowser.searchObject = ACSpecSearch;
		ACRecentProducts.searchObject = ACSpecSearch;
		
		ACProductBrowser.unitDimensions = $('pb-listing').getDimensions();
		ACProductBrowser.doctype = 'SPECIFICATIONS';
		
		// get first level no matter what
		ACProductBrowser.displayProducts(ACProductBrowser.rootProduct, undefined, function() {
		
			var locationString = new String(document.location);
			if(locationString[locationString.length-1]=='/') {
				// means there is a trailing /
				locationString = locationString.substring(0, locationString.length-1);
			}
			var locationParts = locationString.split('/');
		
			// support for anchor URLs
			if(locationString.indexOf("#")!=-1) {
				locationAnchorParts = locationString.split('#');
				if(locationParts[3].indexOf("_")==-1) {
					locationParts[4] = locationAnchorParts[1];
				}
				else {
					locationParts[5] = locationAnchorParts[1];
				}
			}
			
			// load product specific browser and search results if one is specified in the URL
			if(locationString.indexOf("index?page=")==-1 && 
				((locationParts[3].indexOf("_")==-1 && locationParts.length>4) || (locationParts[3].indexOf("_")!=-1 && locationParts.length>5)) && locationParts[locationParts.length-1]!='') {
				
				var prodName = locationParts[locationParts.length-1].toLowerCase();
				
				ACProductBrowser.checkAndLoadProduct(prodName, function() {
					ACSpecSearch.searchAJAX(0, 'recency', ACProductBrowser.currentID, 'state_browse');
				});
			}
			else {
				ACProductBrowser.displayProducts(ACProductBrowser.rootProduct);
				ACSpecSearch.searchAJAX(0, 'recency', ACProductBrowser.rootProduct, 'state_browse');
			}
		
		}, false);
		
	},
 	
	'searchAJAX' : function(offset, sorting, category, filterName) {
		
		if(filterName!==undefined) {
			var filterType = filterName.substr(0, filterName.indexOf("_"));
			var filterValue = filterName.substr(filterName.indexOf("_")+1, 35);
			ACSpecSearch.searchState[filterType] = filterValue;
		}
		
		// make sure to redirect any non English query to the old Google search
		if(ACSpecSearch.searchState.state=='search' && ACSpecSearch.locales.indexOf(ACSpecSearch.locale)==-1) {
			var multiCodedGSALangs = ['zh_CN','zh_TW','pt_PT','pt_BR'];
			var lang = (multiCodedGSALangs.indexOf(ACSpecSearch.locale)>-1) ? ACSpecSearch.locale.replace("_","-") : ACSpecSearch.locale.substring(0,2);
			window.location = 'http://search.info.apple.com/index.html?lr=lang_' + lang + '&q=' + ACSpecSearch.searchState.searchTerm + '&type=kspec&search=Go';
			return;
		}
		
		// hide all elements first
		$('results-Support-ul').hide();
		$('filter').hide();
		$('sortbar').hide();
		$('results_none').hide();
		$('pagination_top').hide();
		$('pagination_bottom').hide();
		$('query').hide();
		
		$('query').innerHTML = '';
		
		$('loading').style.display='block';
		
		if(offset!=undefined) {
			if(offset==0) {
				ACSpecSearch.searchState.offset = 0;
			}
			else {
				ACSpecSearch.searchState.offset = ACSpecSearch.searchState.offset+offset;
				if(ACSpecSearch.searchState.offset<0) {
					ACSpecSearch.searchState.offset = 0;
				}
			}
			
		}
		if(sorting!=undefined) {
			ACSpecSearch.searchState.sort = sorting;
			if(sorting=='alphabetically') {
				ACSpecSearch.activateSortingAlphabetically();
			}
			else {
				ACSpecSearch.activateSortingRecency();
			}
		}
		
		if(category!=undefined && category==ACProductBrowser.rootProduct) {
			ACSpecSearch.searchState.category = '';
		}
		else if(category!=undefined) {
			ACSpecSearch.searchState.category = category;
		}
		
		getUrl = '/kb/index?page=specs_' + ACSpecSearch.searchState.state;
		getUrl += '&offset=' + ACSpecSearch.searchState.offset;
		getUrl += '&sort=' + ACSpecSearch.searchState.sort;
		getUrl += '&facet=' + ACSpecSearch.searchState.facet;
		
		// if serial number search, send all three levels and make it non hierarchical
		if(typeof ACSpecSearch.searchState.category == 'object') {
			getUrl += '&category=' + escape(ACSpecSearch.searchState.category.join(" "));
			getUrl += '&hierarchicalcategories=false';
		}
		else {
			getUrl += '&category=' + ACSpecSearch.searchState.category;
		}
		
		if(ACSpecSearch.searchState.state=="search") {
			ACProductBrowser.displayRows(0);
			getUrl += '&q=' + unescape(ACSpecSearch.searchState.searchTerm);
			
			if(ACUtil.readCookie('s_vi')!==null) {
				// pass site catalyst session ID for reporting
				getUrl += '&sitecatalystid=' + escape(ACUtil.readCookie('s_vi'));
			}
		}
		else {
			// use akamai
			getUrl = ACSpecSearch.akamaiUrl + getUrl;
		}
		
		getUrl += '&locale=' + ACSpecSearch.locale;
		
		var dynamicScript = new JSONscriptRequest(getUrl + '&callback=ACSpecSearch.showResults');
		
		if(dynamicScript.headLoc) {
		
			try{
				dynamicScript.buildScriptTag();
				dynamicScript.addScriptTag();
			}
			catch(ex) {
				// IE 5 for Mac will throw an exception here.
			}
		}
		
		if(ACSpecSearch.searchState.state=="browse") {
		
			var reportProduct = ACProductBrowser.getProduct(ACSpecSearch.searchState.category);
			
			var productTitle = reportProduct!==undefined ? reportProduct.name : undefined;
			if(reportProduct!==undefined && reportProduct.parentid!=ACProductBrowser.rootProduct) { 
				productTitle = ACProductBrowser.getProductName(reportProduct.parentid) + "::" + productTitle;
			}
			
			if (productTitle!=undefined){
				window.setTimeout("ACUtil.clickTracking(\"" + ACSpecSearch.pageNamePrefix+"::"+productTitle + "\");", 800);
			}
		}
		
	},
	
	'showResults': function(json) {
		specs = json;
		$('loading').style.display='none';
		$('results_none').hide();
		
		// display title
		if(ACSpecSearch.searchState.state=='browse' && ACSpecSearch.searchState.category!="") {
			// if level is lower then what exists in product browser, use the ID that is shown in product browser
			var specsName = ACProductBrowser.getProductName(ACSpecSearch.searchState.category);
			specs.name = specsName ? specsName : ACProductBrowser.getProductName(ACProductBrowser.currentID);
		}
		
		if(specs.name) {
			$('query').innerHTML = "<h3>" + specs.name + "</h3>";
			$('query').show();
		}
		else {
			$('query').hide();
		}
		
		var numSpecs = specs.specs.length;
		
		if(numSpecs>0) {
			$('results_total').innerHTML = specs.totalresults;
			$('results_from').innerHTML = ACSpecSearch.searchState.offset+1;
			
			//console.log(specs.totalresults + "--" + ACSpecSearch.pageNumber*10);
			if(specs.totalresults > ACSpecSearch.searchState.offset+10) {
				$('results_until').innerHTML = ACSpecSearch.searchState.offset+10;
			}
			else {
				$('results_until').innerHTML = specs.totalresults;
			}
			
			if(specs.totalresults>10) {
				var paginationDirection = "";
				if(specs.totalresults > ACSpecSearch.searchState.offset+10 && ACSpecSearch.searchState.offset>0) {
					paginationDirection = "both";
				}
				else if(specs.totalresults > ACSpecSearch.searchState.offset+10) {
					paginationDirection = "next";
				}
				else {
					paginationDirection = "previous";
				}
				ACSpecSearch.activatePagination($('pagination_top'), paginationDirection);
				ACSpecSearch.activatePagination($('pagination_bottom'), paginationDirection);
				
				$('pagination_top').show();
				$('pagination_bottom').show();
			}
			else {
				$('pagination_top').hide();
				$('pagination_bottom').hide();
			}
			
			var resultList = "";
			for(i=0;i<numSpecs;i++) {
				var aHref = "<a onclick=\"ACRecentProducts.add('" + specs.specs[i].productname + "', '" + specs.specs[i].parent + "');\" href=\"" + (specs.specs[i].answerurl ? specs.specs[i].answerurl : specs.specs[i].url) + "\">";
				resultList += "<li class=\"top-results dt-thumbnail\"><div class=\"thumbnail\">" + aHref + "<img src=\"" + ACSpecSearch.akamaiUrl + specs.specs[i].thumbnail + "\"></a></div>";
				resultList += "<h3>" + aHref + specs.specs[i].title + "</a></h3>";
				
				if(ACSpecSearch.searchState.state=="browse") {
					resultList += "<div class=\"meta\">" + specs.specs[i].lastmodified + "</div></li>\n";
				}
				else {
					resultList += "<div class=\"desc\">" + specs.specs[i].excerpt + "</div>";
					resultList += "<div class=\"meta\">" + specs.specs[i].url + "</div></li>\n";
				}
			}
			
			$('filter').show();
			
			if(ACSpecSearch.searchState.state=='search') {
				$('sortbar').hide();
			}
			else {
				$('sortbar').show();
			}
			
			$('results-Support-ul').innerHTML = resultList;
			$('results-Support-ul').show();
		}
		else {
			$('results_none').show();
		}
		
	},
	
	'resultsNone': function() {
		$('loading').hide();
		$('results-Support-ul').hide();
		$('filter').hide();
		$('sortbar').hide();
		$('pagination_top').hide();
		$('pagination_bottom').hide();
		$('query').hide();
		
		$('results_none').show();
	},
	
	'searchWithTerm': function() {
		
		if($F('searchsupport')!="") {
			window.location = "#" + $F('searchsupport');
			ACSpecSearch.searchState.searchTerm = ACUtil.trim($F('searchsupport'));
			
			if(ACSpecSearch.searchState.searchTerm.match(/^[a-zA-Z]{2,3}\d{1,6}$/)) {
				window.location.assign('/kb/' + ACSpecSearch.searchState.searchTerm);
			}
			else if(ACUtil.validateSerialNumber(ACSpecSearch.searchState.searchTerm)) {
				// now check if we can find a product id based on serial number
				new Ajax.Request("/kb/index?page=categorydata&serialnumber=" + ACSpecSearch.searchState.searchTerm, {
					method:'get',
					onSuccess: function(transport) {
						var category = transport.responseText.evalJSON();
						ACSpecSearch.searchState.category = [category.id, category.parent, category.grandparent];
						if(category && category.parent && ACProductBrowser.productExists(category.parent)) {
							ACProductBrowser.changeLevel(category.parent, ACSpecSearch.searchState.category);
						}
						else if(category && category.grandparent && ACProductBrowser.productExists(category.grandparent)) {
							ACProductBrowser.changeLevel(category.grandparent, ACSpecSearch.searchState.category);
						}
						else {
							ACSpecSearch.resultsNone();
						}	
						// make sure serial number stays in box
						$('searchsupport').value = ACSpecSearch.searchState.searchTerm;
					},
					onFailure: function() { 
						if(typeof console != 'undefined') console.log('Could not receive data from category API. Please try again.');
						ACSpecSearch.resultsNone();
					}
				});
			}
			else {
				ACSpecSearch.searchAJAX(0, 'relevancy', '', 'state_search');
			}
			
		}
		
	},

	'removeCategorySelection' : function(element){
		 var lis = $(element).getElementsByTagName('li');
		 for(var i=0;i<lis.length;i++){
			var li = lis[i];
			Element.removeClassName(li.getElementsByTagName('a')[0], 'selected');
		 }
	},
	
	'sortingToggle': function(type) {
		if(type=="recency") {
			ACSpecSearch.activateSortingRecency();
			ACSpecSearch.searchAJAX(0, 'recency');
		}
		else if(type=="alphabetically") {
			ACSpecSearch.activateSortingAlphabetically();
			ACSpecSearch.searchAJAX(0, 'alphabetically');
		}
	},
	
	'activateSortingRecency' : function() {
		var sortbarRecent = $('sortbar').getElementsByTagName('div')[1];
		
		var localizedRecentString = sortbarRecent.childNodes[0].innerHTML;
		sortbarRecent.innerHTML = "<span>" + localizedRecentString + "</span>";
		
		var sortbarAlphabetically = $('sortbar').getElementsByTagName('div')[2];
		
		var localizedAlphabeticallyString = sortbarAlphabetically.childNodes[0].innerHTML;
		sortbarAlphabetically.innerHTML = "<a href=\"javascript:ACSpecSearch.sortingToggle('alphabetically');\">" + localizedAlphabeticallyString + "</a>";

		sortbarRecent.className = "button-selected";
		sortbarAlphabetically.className = "button-unselected";
	},
	
	'activateSortingAlphabetically' : function() {
		var sortbarAlphabetically = $('sortbar').getElementsByTagName('div')[2];
		
		var localizedAlphabeticallyString = sortbarAlphabetically.childNodes[0].innerHTML;
		sortbarAlphabetically.innerHTML = "<span>" + localizedAlphabeticallyString + "</span>";
		
		var sortbarRecent = $('sortbar').getElementsByTagName('div')[1];
		
		var localizedRecentString = sortbarRecent.childNodes[0].innerHTML;
		sortbarRecent.innerHTML = "<a href=\"#\" onclick=\"ACSpecSearch.sortingToggle('recency');\">" + localizedRecentString + "</a>";
		
		sortbarAlphabetically.className = "button-selected";
		sortbarRecent.className = "button-unselected";
		
	},
	
	'activatePagination' : function(element, direction) {
		
		var localizedNextString = (element.getElementsByClassName('next')[0]!=undefined) ? element.getElementsByClassName('next')[0].innerHTML : '';
		var localizedPreviousString = (element.getElementsByClassName('previous')[0]!=undefined) ? element.getElementsByClassName('previous')[0].innerHTML : '';
		element.innerHTML = '';
		if(direction=="previous" || direction=="both") {
			element.innerHTML += "<a class=\"previous\" href=\"#\" onclick=\"ACSpecSearch.searchAJAX(-10);return false;\">" + localizedPreviousString + "</a> | ";
		}
		else {
			element.innerHTML += "<span class=\"previous\">" + localizedPreviousString + "</span> | ";
		}
		
		if(direction=="next" || direction=="both") {
			element.innerHTML += "<a class=\"next\" href=\"#\" onclick=\"ACSpecSearch.searchAJAX(10);return false;\">" + localizedNextString + "</a>";
		}
		else {
			element.innerHTML += "<span class=\"next\">" + localizedNextString + "</span>";
		}
		
	}
	
};

