﻿if (typeof(MenuSlider) == 'undefined') { var MenuSlider = {}; }

MenuSlider = Class.create({
	'attempts': {},
	'container': null,
	'data': {
		'name_by_key': {},
		'solution_by_id': {},
		'subtopic_id_by_key': {},
		'subtopic_key_by_id': {},
		'subtopic_name_by_id': {},
		'subtopic_solutions_by_id': {},
		'topic_id_by_key': {},
		'topic_key_by_id': {},
		'topic_name_by_id': {},
		'topic_solutions_by_id': {}
	},
	'hastopicbeenrequested': {},
	'more_link': {},
	'results': {},
	'solutions_built': 0,
	'topics_requested': {},
	
	'buildMoreLink': function(topic_id, div_collection) {
		var more_link = this.more_link[topic_id];
		if (more_link != undefined && more_link.enabled == true) {
			var morelink_text = more_link.name;
			var morelink_p = new Element('p').addClassName('see_all');
			var morelink_ahref = new Element('a', { 
				'href': more_link.url,
				'target': '_blank'	
			});
			morelink_ahref.update(morelink_text);
			morelink_p.insert(morelink_ahref);
			div_collection.insert(morelink_p);
		}
	},
	
	'buildSolutions': function(solution_id, container, topic_id, subtopic_id) {
		var solution = this.data.solution_by_id[solution_id];
		var solution_key = (solution.type != 'page') ? solution.article : solution.key;
		var attempt = 0;
		var max_attempts = 100;
		if (this.results[solution_key] != undefined) {
			this.buildSolutionElement(solution_key, container, topic_id, subtopic_id);
			this.solutions_built++;
		}
		else {
			new PeriodicalExecuter(function(pe) {
				if (this.results[solution_key] != undefined) {
					this.buildSolutionElement(solution_key, container, topic_id, subtopic_id);
					this.solutions_built++;
					pe.stop();
				}
				else if (attempt >= max_attempts) {
					pe.stop();
				}
				attempt++;
			}.bind(this), 0.3);
		}
	},
	
	'buildSolutionElement': function(solution_key, container, topic_id, subtopic_id) {
		var result = this.results[solution_key];
		var h4 = new Element('h4');
		var result_title = result.title.replace(/'/g, '\\\'');
		var trackclick = [result.key, result.type, result_title, result.url].join('\',\'');
		var ahref = new Element('a', {
			'href': result.url,
			'target': '_blank'
		});
		ahref.update(result.title);
		ahref.observe('click', function(evt) {
			eval('MenuSlider.prototype.trackClick(\'' + trackclick + '\')');
		});
		h4.insert(ahref);
		var p = new Element('p');
		var solution_excerpt = result.excerpt;
		p.update(solution_excerpt);
		container.insert(h4);
		container.insert(p);
		if ($('haveyoutried').hasClassName('loading')) {
			$('haveyoutried').removeClassName('loading');
		}
	},
	
	'buildSubtopicsNavElement': function(topic_id, subtopic_id) {
		var subtopic_key = this.data.subtopic_key_by_id[subtopic_id];
		var span_1 = new Element('span');
		var span_2 = new Element('span').update(this.data.name_by_key[subtopic_key]);
		var li = new Element('li', {'id': 'subtopic_' + subtopic_id});
		span_1.insert(span_2);
		li.observe('click', this.clickSubtopic.bindAsEventListener(this, topic_id, subtopic_id));
		li.insert(span_1);
		return li;
	},
	
	'buildTopicNavElement': function(topic_id, ul) {
		var topic_key = this.data.topic_key_by_id[topic_id];
		var div_topic = new Element('div', {'id': 'topic_' + topic_id});
		div_topic.addClassName('topic').addClassName('category');
		var div_subtopic = new Element('div', {'id': 'subtopics_' + topic_id});
		div_subtopic.addClassName('subtopics').addClassName('drawer').hide();
		var h3 = new Element('h3');
		h3.update(this.data.name_by_key[topic_key]);
		h3.observe('click', this.clickTopic.bindAsEventListener(this, topic_id));
		div_subtopic.insert(ul);
		div_topic.insert(h3);
		div_topic.insert(div_subtopic);
		this.container.insert(div_topic);
	},
	
	'clickSubtopic': function(e) {
		var args = Array.prototype.slice.call(arguments);
		var topic_id = args[1];
		var topic_key = this.data.topic_key_by_id[topic_id];
		var subtopic_id = args[2];
		var subtopic_solutions = this.data.subtopic_solutions_by_id[subtopic_id];
		
		/* handle topic nav */
		$$('div.topic.selected').each(function(div_topic) {
			div_topic.removeClassName('selected');
		}.bind(this));
		$$('div.subtopics li.selected').each(function(div_subtopic) {
			if (div_subtopic.identify() != 'subtopic_' + subtopic_id) {
				div_subtopic.removeClassName('selected');
			}
		}.bind(this));
		if (!$('subtopic_' + subtopic_id).hasClassName('selected')) {
			$('subtopic_' + subtopic_id).addClassName('selected')
		}
		
		/* clear out right panel */
		$('articles').descendants().invoke('remove');
		
		/* build solutions / article links and excerpt */
		var div_collection = new Element('div').addClassName('collection selected');
		$('articles').insert(div_collection);
		this.solutions_built = 0;
		for (var i = 0; i < subtopic_solutions.length; i++) {
			this.buildSolutions(subtopic_solutions[i], div_collection, topic_id, subtopic_id);
		}
						
		/* add more link */
		var attempt = 0;
		if (this.solutions_built == subtopic_solutions.length) {
			this.buildMoreLink(topic_id, div_collection);
		}
		else {
			var max_attempts = 100;
			new PeriodicalExecuter(function(pe) {
				if (this.solutions_built == subtopic_solutions.length) {
					this.buildMoreLink(topic_id, div_collection);
					pe.stop();
				}
				else if (attempt >= max_attempts) {
					pe.stop();
				}
				attempt++;
			}.bind(this), 0.3);
		}
		
		/* display */
		$('articles').show();
		$('haveyoutried').show();
		$('select-category').removeClassName('selected');
		$('select-topic').removeClassName('selected');
		$('select-article').addClassName('selected');
		
		/* sitecatalyst click tracking */
		var track_click_title = this.data.topic_name_by_id[topic_id] + ' - ' + this.data.subtopic_name_by_id[subtopic_id];
		this.trackClick(undefined, undefined, track_click_title, undefined);
	},
	
	'clickTopic': function(e) {
		var args = Array.prototype.slice.call(arguments);
		var topic_id = args[1];
		var topic_key = this.data.topic_key_by_id[topic_id];
		var topic_solutions = this.data.topic_solutions_by_id[topic_id];
		var click_action = 'open';
		
		if (!$('haveyoutried').hasClassName('loading')) {
			$('haveyoutried').addClassName('loading');
		}
		
		if (topic_solutions != undefined) {
			this.sendRequest(topic_id, topic_solutions);
		}
		
		var div_topic_id = 'topic_' + topic_id;
		var div_subtopics_id = 'subtopics_' + topic_id;
		
		$$('div.subtopics li.selected').each(function(div_subtopic) {
			div_subtopic.removeClassName('selected');
		});
		
		if ($(div_topic_id).hasClassName('selected')) {
			$(div_topic_id).removeClassName('selected');
			Effect.BlindUp($(div_subtopics_id), {duration: 0.3});
			click_action = 'close';
		}
		else {
			if ($(div_subtopics_id).visible()) {
				$(div_topic_id).removeClassName('selected');
				Effect.BlindUp($(div_subtopics_id), {duration: 0.3});
				click_action = 'close';
			}
			else {
				$$('div.topic').each(function(div_topic) {
					if (div_topic.identify() != div_topic_id) {
						div_topic.removeClassName('selected');
						Effect.BlindUp(div_topic.select('div.subtopics').first(), {duration: 0.3});
					}
				});
				$(div_topic_id).addClassName('selected');
				Effect.BlindDown($(div_subtopics_id), {duration: 0.3});
				click_action = 'open';
			}
		}
		
		if ($(div_topic_id).hasClassName('selected')) {
			$('select-category').removeClassName('selected');
			$('select-topic').addClassName('selected');
			$('select-article').removeClassName('selected');
		}
		else {
			$('select-category').addClassName('selected');
			$('select-topic').removeClassName('selected');
			$('select-article').removeClassName('selected');
		}
		$('haveyoutried').hide();
		
		/* sitecatalyst click tracking */
		if (click_action == 'open') {
			var track_click_title = this.data.topic_name_by_id[topic_id];
			this.trackClick(undefined, undefined, track_click_title, undefined);
		}
	},
	
	'convertLocaleForKmLoader': function(locale) {
		if (locale == 'es_US') {
			return 'es_ES';
		}
		else {
			return locale;
		}
	},
	
	'doesOnlyListExist': function(item) {
		return (item.getAttribute('only') != null) ? true : false;
	},
	
	'extractName': function(item, tag) {
		var name = null;
		if (item != undefined && tag != undefined) {
			var langs = [this.getPageLocale(), this.getPageLang()];
			for (i = 0; i < langs.length; i++) {
				var subitem = item.getElementsByTagName(tag);
				for (var j = 0; j < subitem.length; j++) {
					if (name == null) {
						if (subitem[j].getAttribute('lang') != null && subitem[j].getAttribute('lang') == langs[i]) {
							name = this.getValue(subitem[j]);
						}
						else if (subitem[j].getAttribute('lang') == null) {
							name = this.getValue(subitem[j]);
						}
					}
				}
			}
		}
		return name;
	},
	
	'getHelpPath': function(url) {
		return url.replace(/http\:\/\/docs\.info\.apple\.com\/article.html\?path\=/, '');
	},
	
	'getHostForKmLoader': function() {
		return KmLoader.akamaiUrl;
	},
	
	'getLangDir': function() {
		if (this.getPageLocale() == 'pt_BR') { return 'pt-br'; }
		else if (this.getPageLocale() == 'pt_PT') { return 'pt-pt'; }
		else if (this.getPageLocale() == 'zh_CN') { return 'zh-cn'; }
		else if (this.getPageLocale() == 'zh_TW') { return 'zh-tw'; }
		else { return this.getPageLang(); }
	},
	
	'getLocaleForKmLoader': function() {
		if (this.getPageLang() == 'de') { return 'de_DE'; }
		else if (this.getPageLang() == 'en') { return 'en_US'; }
		else if (this.getPageLang() == 'es') { return 'es_ES'; }
		else if (this.getPageLang() == 'fr') { return 'fr_FR'; }
		else if (this.getPageLang() == 'nl') { return 'nl_NL'; }
		else { return this.getPageLocale(); }
	},
	
	'getPageCountry': function() {
		return ACWPod.getCountry();
	},
	
	'getPageLang': function() {
		return ACWPod.getLang();
	},
	
	'getPageLocale': function() {
		if (ACWPod.getLocale() == 'zh_HK') {
			return 'zh_TW';
		}
		else {
			return ACWPod.getLocale();
		}
	},
	
	'getValue': function(xmlnode) {
		return xmlnode.textContent || xmlnode.text || xmlnode.innerText;
	},
	
	'hasTopicBeenRequested': function(topic_id) {
		if (this.topics_requested[topic_id] == undefined) {
			this.topics_requested[topic_id] = topic_id;
			return false;
		}
		else {
			return true;
		}
	},
	
	'initialize': function(container) {
		if (!container) { return false; }
		this.container = container;
		this.loadSolutionsAndTopics();
		
		/* hide solution elements */
		$('haveyoutried').hide();
	},
	
	'isExcludeListMember': function(item) {
		var exclude = item.getAttribute('exclude');
		if (exclude != null) {
			exclude = exclude.replace(/\s+/g, '');
			var locales = exclude.split(',');
			var locale_match = false;
			for (var i = 0; i < locales.length; i++) {
				if (locales[i] == this.getPageLocale()) {
					locale_match = true;
				}
			}
			return locale_match;
		}
		else {
			return false;
		}
	},
	
	'isOnlyListMember': function(item) {
		var only = item.getAttribute('only');
		if (only != null) {
			only = only.replace(/\s+/g, '');
			var locales = only.split(',');
			var locale_match = false;
			for (var i = 0; i < locales.length; i++) {
				if (locales[i] == this.getPageLocale()) {
					locale_match = true;
				}
			}
			return locale_match;
		}
		else {
			return false;
		}
	},
	
	'isShowable': function(item) {
		if (this.doesOnlyListExist(item)) {
			return (this.isOnlyListMember(item)) ? true : false;
		}
		else if (this.isExcludeListMember(item)) {
			return false;
		}
		else {
			return true;
		}
	},
	
	'loadScript': function(url) {
		$$('head').first().insert(new Element('script', {'src': url, 'type': 'text/javascript', 'charset': 'utf-8' }));
	},
	
	'loadSolutionsAndTopics': function() {
		var topic_names_en = null;
		var topic_names = null;
		var solutions = null;
		var feedroot = (location.pathname.indexOf('/support/snowleopardserver/') != -1) ? '/support/snowleopardserver/' : '/support/snowleopard/';
		new Ajax.Request(feedroot + 'feeds/en/topic_names.xml', {
			method: 'get',
			onSuccess: function(transport) {
				topic_names_en = transport.responseXML;
			}
		});
		if (this.getPageLang() != 'en') {
			new Ajax.Request(feedroot + 'feeds/' + this.getLangDir() + '/topic_names.xml', {
				method: 'get',
				onSuccess: function(transport) {
					topic_names = transport.responseXML;
				},
				onFailure: function() {
					topic_names = 'noxml';
				}
			});
		}
		new Ajax.Request(feedroot + 'feeds/solutions.xml', {
			method: 'get',
			onSuccess: function(transport) {
				solutions = transport.responseXML;
			}
		});
		new PeriodicalExecuter(function(pe) {
			if (topic_names_en != null && solutions != null) {
				if (this.getPageLang() != 'en' && topic_names != null && topic_names != 'noxml') {
					this.parseTopicNames(topic_names_en);
					this.parseTopicNames(topic_names);
					this.parseSolutions(solutions);
					pe.stop();
				}
				else if (this.getPageLang() != 'en' && topic_names != null && topic_names == 'noxml') {
					this.parseTopicNames(topic_names_en);
					this.parseSolutions(solutions);
					pe.stop();
				}
				else if (this.getPageLang() == 'en') {
					this.parseTopicNames(topic_names_en);
					this.parseSolutions(solutions);
					pe.stop();
				}
			}
		}.bind(this), 0.1);

	},
	
	'parseResults': function(json, requestId) {
		for (var i = 0 ; i < json.results.length; i++) {
			var result = json.results[i];
			var result_key = '';
			var result_type = '';
			var result_url = '';
			/* kb article result */
			if (result.documentid != undefined) {
				result_key = result.documentid;
				result_type = 'kb';
				result_url = result.url;
			}
			/* help article result */
			else if (result.url != undefined) {
				result_key = this.getHelpPath(result.url);
				result_key = result_key.replace(/^(.+\/)[^\/]+(\/[^\/]+)$/, '$1' + 'locale' + '$2');
				result_type = 'help';
				result_url = result.url;
			}
			this.storeResult(result_key, result_type, result.title, result_url, result.excerpt);
		}
	},
	
	'parseSolutions': function(xml) {
		var topic_id = 0;
		var subtopic_id = 0;
		var solution_id = 0;
		
		/* topics */
		var topics = xml.getElementsByTagName('topic');
		for (var i = 0; i < topics.length; i++) {
			var topic = topics[i];
			
			if (this.isShowable(topic)) {
				var topic_key = topic.getAttribute('key');
				this.data.topic_id_by_key[topic_key] = topic_id;
				this.data.topic_key_by_id[topic_id] = topic_key;
				this.data.topic_name_by_id[topic_id] = this.data.name_by_key[topic_key];
				this.data.topic_solutions_by_id[topic_id] = [];
				
				var ul = new Element('ul');
				
				/* subtopics */
				var subtopics = topic.getElementsByTagName('subtopic');
				for (var j = 0; j < subtopics.length; j++) {
					var subtopic = subtopics[j];
					
					if (this.isShowable(subtopic)) {
						var subtopic_key = subtopic.getAttribute('key');
						this.data.subtopic_id_by_key[subtopic_key] = subtopic_id;
						this.data.subtopic_key_by_id[subtopic_id] = subtopic_key;
						this.data.subtopic_name_by_id[subtopic_id] = this.data.name_by_key[subtopic_key];
						this.data.subtopic_solutions_by_id[subtopic_id] = [];
														
						/* solutions */
						var solutions = subtopic.getElementsByTagName('solution');
						for (var k = 0; k < solutions.length; k++) {
							var solution = solutions[k];
							
							if (this.isShowable(solution)) {
								var solution_article = this.getValue(solution);
								this.data.solution_by_id[solution_id] = {
									'key': solution.getAttribute('key'),
									'type': solution.getAttribute('type'),
									'article': solution_article,
									'excerpt': solution.getAttribute('excerpt')
								};
								this.data.topic_solutions_by_id[topic_id].push(solution_id);
								this.data.subtopic_solutions_by_id[subtopic_id].push(solution_id);
								solution_id++;
							}
						}
						
						/* builds and inserts dom elements for subtopic nav */
						ul.insert(this.buildSubtopicsNavElement(topic_id, subtopic_id));
						
						subtopic_id++;
					}
				}
				
				/* more link */
				this.storeMoreLink(topic, topic_id);
				
				/* builds and inserts dom elements for topic nav */
				this.buildTopicNavElement(topic_id, ul);

				topic_id++;
			}
		}
		
		this.container.removeClassName('loading');
		
		/* show right panel description at startup */
		$('select-category').addClassName('selected');
		
		/* expand topic if specified in url */
		var urlhash = window.location.hash.replace(/\#/,'');
		if (this.data.topic_id_by_key[urlhash] != undefined) {
			this.clickTopic(this, this.data.topic_id_by_key[urlhash]);
		}
	},
	
	'parseTopicNames': function(topic_names) {
		var topics = topic_names.getElementsByTagName('topic_name');
		for (var i = 0; i < topics.length; i++) {
			this.storeName(topics[i], 'topic');
			var subtopics = topics[i].getElementsByTagName('subtopic_name');
			for (var j = 0; j < subtopics.length; j++) {
				this.storeName(subtopics[j], 'subtopic');
				var solutions = subtopics[j].getElementsByTagName('solution_name');
				for (var k = 0; k < solutions.length; k++) {
					this.storeName(solutions[k], 'solution');
					var excerpts = solutions[k].getElementsByTagName('excerpt_name');
					for (var l = 0; l < excerpts.length; l++) {
						this.storeName(excerpts[l], 'excerpt', solutions[k].getAttribute('key') + '_excerpt');
					}
				}
			}
			var more_links = topics[i].getElementsByTagName('more_link_name');
			for (var j = 0; j < more_links.length; j++) {
				this.storeName(more_links[j], 'more_link', topics[i].getAttribute('key') + '_more_link');
			}
		}
	},
	
	'receiveSuccess': function(json, requestId) {
		if (json != undefined && json != null && json.results) {
			var loadingImages = $('haveyoutried').getElementsBySelector('img.loading');
			loadingImages.each(function(image) {
				image.remove();
			});
			this.parseResults(json, requestId);
		}
	},
	
	'requestHelpArticles': function(requestid, helpids) {
		this.loadScript(this.getHostForKmLoader() + '/docs/kmdata.html?requestid=' + requestid + '&locale=' + this.getLocaleForKmLoader() + '&excerpt=y&paths=' + escape(helpids) + '&callback=MenuSlider.prototype.receiveSuccess');
	},
	
	'requestKbArticles': function(requestid, articleids) {
		this.loadScript(this.getHostForKmLoader() + '/kb/index?page=kmdata&requestid=' + requestid + '&locale=' + this.getLocaleForKmLoader() + '&excerpt=y&documentids=' + escape(articleids) + '&maxrecords=30&callback=MenuSlider.prototype.receiveSuccess');
	},
	
	'sendRequest': function(topic_id, solution_ids) {
		if (topic_id != undefined && solution_ids != undefined) {
			var article_kb_list = [];
			var article_help_list = [];
			for (var i = 0; i < solution_ids.length; i++) {
				var solution = this.data.solution_by_id[solution_ids[i]];
				if (solution.type == 'kb') {
					article_kb_list.push(solution.article);
				}
				else if (solution.type == 'help') {
					article_help_list.push(solution.article);
				}
				/* dont send request for type=page solutions */
				else if (solution.type == 'page') {
					var solution_title = this.data.name_by_key[solution.key];
					var solution_excerpt = this.data.name_by_key[solution.key + '_excerpt'];
					this.storeResult(solution.key, solution.type, solution_title, solution.article, solution_excerpt);
				}
			}
			if (this.hasTopicBeenRequested(topic_id) == false) {
				if (article_kb_list.length > 0) {
					this.requestKbArticles(topic_id, article_kb_list.join(','));
				}
				if (article_help_list.length > 0) {
					this.requestHelpArticles(topic_id, article_help_list.join(','));
				}
			}
		}
	},
	
	'storeMoreLink': function(topic, topic_id) {
		var topic_key = this.data.topic_key_by_id[topic_id];
		this.more_link[topic_id] = {};
		this.more_link[topic_id].enabled = false;
		var more_links = topic.getElementsByTagName('more_link');
		for (var j = 0; j < more_links.length; j++) {
			var more_link = more_links[j];
			var more_link_value = this.getValue(more_link);
			if (this.isShowable(more_link)) {
				if (more_link_value == 'true' || (more_link_value != 'false' && more_link_value != '')) {
					this.more_link[topic_id].enabled = true;
					this.more_link[topic_id].name = this.data.name_by_key[topic_key + '_more_link'];
					if (more_link_value == 'true') {
						this.more_link[topic_id].url = 'http://support.apple.com/kb/index?page=search&src=support_site.psp.snowleopard.more&q=' + escape(this.data.name_by_key[topic_key]);
					}
					else {
						this.more_link[topic_id].url = more_link_value;
					}
				}
			}
		}
	},
	
	'storeResult': function(key, type, title, url, excerpt) {
		this.results[key] = {
			'key': (key != undefined && key != null) ? key : '',
			'type': (type != undefined && type != null) ? type : '',
			'title': (title != undefined && title != null) ? title : '',
			'url': (url != undefined && url != null) ? url : '',
			'excerpt': (excerpt != undefined && excerpt != null) ? this.truncateExcerpt(excerpt) : ''
		};
	},
	
	'storeName': function(item, tag, key) {
		if (item != undefined && tag != undefined) {
			var name = this.extractName(item, tag);
			if (name != null) {
				if (key != undefined) {
					this.data.name_by_key[key] = name;
				}
				else if (item.getAttribute('key') != undefined) {
					this.data.name_by_key[item.getAttribute('key')] = name;
				}
			}
		}
	},
	
	'trackClick': function(id, type, title, url) {
		var title = (title != undefined) ? title : '';
		var url = (url != undefined) ? url: document.URL;
		var tracking_title = '';
		if (id != undefined && type != undefined) {
			if (type == 'kb') {
				tracking_title += id + ': ';
			}
			if (title != '') {
				tracking_title += title;
			}
		}
		else if (title != '') {
			tracking_title += title;
		}
		if (typeof(SCReporting) != 'undefined') {
			SCReporting.trackClick(tracking_title, url);
		}
	},
	
	'truncateExcerpt': function(excerpt) {
		var truncated_excerpt = excerpt;
		var excerptLimit = 150;
		if (this.getPageLang() == 'ja') {
			if (truncated_excerpt.indexOf('。') != -1) {
				var shortened = truncated_excerpt.split('。');
				truncated_excerpt = shortened[0] + '。';
			}
		}
		if (truncated_excerpt.length > excerptLimit) {
			truncated_excerpt = truncated_excerpt.truncate(excerptLimit);
			var words = truncated_excerpt.split(' ');
			truncated_excerpt = '';
			words = words.without(words.last());
			words.each(function(word) {
				truncated_excerpt += ' ' + word;
			});
			truncated_excerpt += '...';
		}
		return truncated_excerpt;
	}

});

document.observe('dom:loaded', function() {
	new MenuSlider($('issues'));
});

