﻿/*
 * KmLoader functions for dynamic portlets
 */
 
if (window.location.hostname.match(/^(www\.)?apple\.com(\.cn)?$/) == null) {
	KmLoader.akamaiUrl = KmLoader.akamaiUrl.replace(/km\./, '');
}

/*
 * Wrapper function for KmLoader.sendKmCall that checks if element
 * with id=portlet_[n] exists in DOM before making the API call.
 * wrap() is a Prototype function.
 */
KmLoader.sendKmCall = KmLoader.sendKmCall.wrap(
	function(origSendKmCall) {
		var args = Array.prototype.slice.call(arguments);
		args = args.slice(1);
		var requestId = args[1];
		if (requestId != undefined && !isNaN(requestId)) {
			/* 0-99: dynamic portlets */
			if (requestId < 100 && $('portlet_' + requestId) != null) {
				return origSendKmCall.apply(this, args);
			}
			/* 100-199: downloads module */
			else if (requestId >= 100 && requestId < 200 && $('downloads_module') != null) {
				return origSendKmCall.apply(this, args);
			}
		}
	}
);

// as long as KmLoader.js is included in this page, the 
// success() function will execute when data is received from the HTTP portlet call
		
KmLoader.success = function(json, requestId) {
	
	if ($('portlet_'+requestId) != null) {
		
		$('portlet_'+requestId).innerHTML = '';

		// fix spacing for manually coded linked lists above/below portlet
		if ($('portlet_' + requestId).previous() != undefined && $('portlet_' + requestId).previous().match('ul')) {
			$('portlet_' + requestId).previous().setStyle({paddingBottom: '0px'}); 
		}
		if ($('portlet_' + requestId).next() != undefined && $('portlet_' + requestId).next().match('ul')) {
			$('portlet_' + requestId).setStyle({paddingBottom: '0px'}); 
		}

		if(json==undefined || json==null) {
			alert('Something went wrong. Please try again!') 
		}
		else {
			var portletData = '';

			for(i=0;i<json['results'].length;i++) {
				if (json.results[i] != null) {
					var displayItem = true;
					if(KmLoader.ignoreArticles!==undefined && json.results[i].url.indexOf("support.apple.com/kb/")!=-1) {
						// if kb article, omit if it's in the ignoreArticles list
						var endIndex = json.results[i].url.indexOf("?")!=-1 ? json.results[i].url.indexOf("?") : json.results[i].url.length;
						var artId = json.results[i].url.substring(json.results[i].url.lastIndexOf("/")+1, endIndex);
						if(KmLoader.ignoreArticles.indexOf(artId)!=-1) {
							displayItem = false;
						}
					}
					if(displayItem) {
						portletData += "<li><a href=\"" + json.results[i].url + "\" onclick=\"s_objectID='" +  json.results[i].url + "_p" + requestId + "-" + i + "';\">" + json.results[i].title + "</a></li>";
					}
				}
			}
			$('portlet_' + requestId).innerHTML = portletData;
		}
	}
}
		
KmLoader.error = function(errorMsg, requestId) {
	if ($('portlet_'+requestId) != null) {
		$('portlet_'+requestId).innerHTML = '';
		//console.log('RequestId: ' + requestId + " Error: " + errorMsg);
	}
}

/*
 * Name
 * 	DownloadsModule
 *
 * Description
 * 	An object that makes requests for Downloads content only. 
 * 	Used on product support pages to display the dynamic Downloads module.
 *
 * Dependencies
 * 	Javascript : prototype.js, scriptaculous.js, support.global.js
 * 	HTML : <div id="downloads_module" class="module"></div>
 * 
 */
var DownloadsModule = {

	'container': 'downloads_module',
	'default_locale': 'en_US',
	'dm_results': [],
	'hard_list_top': [],
	'hard_list_bottom': [],
	'initialized': false,
	'links_container': 'downloads_module_links',
	'loaderid': 100,
	'load_order': [],
	'locale_api': {},
	'urlpath': {},
	'vars': {},
	
	'buildLinks': function(listsize, productids, loaderid) {
		new PeriodicalExecuter(function(pe) {
			if ($(this.links_container) && !isNaN(listsize) && productids != '' && this.load_order[0] == loaderid && this.locale_api[productids] != undefined) {
				if ($('intro_link').readAttribute('href') == null || $('intro_link').readAttribute('href') == '') {
					this.createDownloadsLinks(productids);
				}
				if ($(this.links_container + '_mid')) {
					$(this.links_container + '_mid').insert(new Element('ul', {
						'class': 'square',
						'id': this.links_container + '_' + loaderid
					}));
				}
				if ($(this.links_container + '_top')) {
					this.hard_list_top.each(function(el) {
						if ($('dm_spinner').visible()) { $('dm_spinner').hide(); }
						$(this.links_container + '_top').insert(el.addClassName('square').show()).appear({'duration': 0.3});
					}.bind(this)).shift();
				}
				if ($(this.links_container + '_bottom')) {
					this.hard_list_bottom.each(function(el) {
						if ($('dm_spinner').visible()) { $('dm_spinner').hide(); }
						$(this.links_container + '_bottom').insert(el.addClassName('square').show()).appear({'duration': 0.3});
					}.bind(this)).shift();
				}
				this.load_order.shift();
				this.requestLinks(listsize, productids, loaderid);
				pe.stop();
			}
		}.bind(this), 0.1);
	},
	
	'buildModule': function() {
		new PeriodicalExecuter(function(pe) {
			if ($(this.container).immediateDescendants().length == 0 && this.vars.hed != undefined && this.vars.intro != undefined && this.vars.subhed != undefined && this.vars.see_all != undefined) {
				var h2 = new Element('h2');
				var div = new Element('div').update(this.vars.hed);
				h2.insert(div);
				$(this.container).insert(h2);
				var div_sidebar = new Element('div').addClassName('sidebar pad10');
				var a_icon = new Element('a', {'id': 'icon_link'});
				var img_icon = new Element('img', {
					'src': 'http://images.apple.com/support/_images/icon_downloads.png', 
					'id': 'dm_icon'
				}).addClassName('lefticon');
				a_icon.insert(img_icon);
				var div_desc1 = new Element('div').addClassName('desc').update(this.vars.intro);
				var div_desc2 = new Element('div').addClassName('desc').update(this.vars.subhed + ':');
				var div_links = new Element('div', {'id': 'downloads_module_links'});
				var img_spinner = new Element('img', {
					'src': 'http://images.apple.com/support/main/elements/aqua2spinner12.gif', 
					'id': 'dm_spinner'
				});
				var div_links_top = new Element('div', {'id': 'downloads_module_links_top'});
				var div_links_mid = new Element('div', {'id': 'downloads_module_links_mid'}).hide();
				var div_links_bot = new Element('div', {'id': 'downloads_module_links_bottom'}).hide();
				div_links.insert(img_spinner);
				div_links.insert(div_links_top);
				div_links.insert(div_links_mid);
				div_links.insert(div_links_bot);
				var div_padtop10 = new Element('div').addClassName('padtop10');
				var a_seeall = new Element('a', {'id': 'see_all_link'}).addClassName('arrowlink').update(this.vars.see_all);
				div_sidebar.insert(a_icon);
				div_sidebar.insert(div_desc1);
				div_sidebar.insert(div_desc2);
				div_sidebar.insert(div_links);
				div_sidebar.insert(div_padtop10);
				div_sidebar.insert(a_seeall);
				$(this.container).insert(div_sidebar);
				pe.stop();
			}
		}.bind(this), 0.1);
	},
	
	'createDownloadsLinks': function(productids) {
		if ($('intro_link')) {
			$('intro_link').writeAttribute({
				'href': this.getIntroLink(productids), 
				'onclick': 's_objectID=\'' + this.getIntroLink(productids) + '_dm_intro\''
			});
		}
		if ($('icon_link')) {
			$('icon_link').writeAttribute({
				'href': this.getIntroLink(productids), 
				'onclick': 's_objectID=\'' + this.getIntroLink(productids) + '_dm_icon\''
			});
		}
		if ($('see_all_link')) {
			$('see_all_link').writeAttribute({
				'href': this.getSeeAllLink(productids), 
				'onclick': 's_objectID=\'' + this.getSeeAllLink(productids) + '_dm_see_all\''
			});
		}
	},
	
	'getCategoryKey' : function () {
		return (typeof(ACCategoryKey) == 'undefined' || ACCategoryKey.empty()) ? false : ACCategoryKey;
	},
	
	'getIntroLink': function(productid) {
		var locale = this.locale_api[productid];
		if (locale == 'en_US') {
			return 'http://support.apple.com/downloads/';
		}
		else {
			return 'http://support.apple.com/' + locale + '/downloads/';
		}
	},
	
	'getLocaleForApi' : function () {
		/* languages with multiple countries that are specific to inquira */
		/* these fall into the default group: pt_BR pt_PT zh_CN zh_TW */
		if (ACWPod.getLang() == 'de') { return 'de_DE'; }
		else if (ACWPod.getLang() == 'en') { return 'en_US'; }
		else if (ACWPod.getLang() == 'es') { return 'es_ES'; }
		else if (ACWPod.getLang() == 'fr') { return 'fr_FR'; }
		else if (ACWPod.getLang() == 'nl') { return 'nl_NL'; }
		else if (ACWPod.getLocale() == 'zh_HK') { return 'zh_TW'; }
		else { return ACWPod.getLocale(); }
	},
	
	'getSeeAllLink': function(productid) {
		var locale = this.locale_api[productid];
		var urlpath = this.urlpath[this.getCategoryKey()];
		var url = 'http://support.apple.com/';
		if (locale != 'en_US') { url += locale + '/'; }
		url += 'downloads/';
		if (urlpath != undefined && urlpath != '') { url += '#' + urlpath; }
		return url;
	},
	
	'getHostForKmLoader': function() {
		return KmLoader.akamaiUrl;
	},
	
	'load': function(listsize, ids) {
		var loaderid = this.loaderid;
		this.load_order.push(loaderid);
		
		if (!this.initialized) {
			if ($(this.container)) {
				this.loadCSS();
				this.loadVars();
				this.storeHardcodedLists();
				this.buildModule();
			}
			this.initialized = true;
		}
		
		var productids = '';
		if (ids != undefined && ids != '') {
			productids = ids;
		}
		else if (this.getCategoryKey() != false) {
			productids = this.getCategoryKey();
		}
		else if (this.getCategoryKey() == false) {
			alert('DownloadsModule: ACCategoryKey not defined.');
			return;
		}
		else {
			alert('DownloadsModule: Product ID not defined.');
			return;
		}
		
		this.requestCheckProduct(productids);
		this.buildLinks(listsize, productids, loaderid);
		this.loaderid++;
	},
	
	'loadCSS': function() {
		$$('head').first().insert(new Element('link', {
			'rel': 'stylesheet',
			'href': 'http://images.apple.com/support/scripts/portlet/DownloadsModule/css/styles.css',
			'type': 'text/css',
			'charset': 'utf-8'
		}));
	},
	
	'loadScript': function(url) {
		$$('head').first().insert(new Element('script', {
			'src': url,
			'type': 'text/javascript',
			'charset': 'utf-8'
		}));
	},
	
	'loadVars': function() {
		var varslang = ACWPod.getLang();
		/* locale-specific languages */
		if (ACWPod.getLocale() == 'pt_BR' || ACWPod.getLocale() == 'pt_PT' || ACWPod.getLocale() == 'zh_CN' || ACWPod.getLocale() == 'zh_TW') {
			varslang = ACWPod.getLocale();
		}
		/* force hk lang to zh_TW */
		else if (ACWPod.getLocale() == 'zh_HK') {
			varslang = 'zh_TW';
		}
		this.loadScript('http://images.apple.com/support/scripts/portlet/DownloadsModule/vars/' + varslang + '.js');
	},
	
	'requestCheckProduct': function(productids) {
		this.loadScript(this.getHostForKmLoader() + '/kb/index?page=categorydata&productid=' + productids + '&locale=' + this.getLocaleForApi() + '&callback=DownloadsModule.successCheckProduct');
	},
	
	'requestLinks': function(listsize, productids, loaderid) {
		this.loadScript(this.getHostForKmLoader() + '/kb/index?page=kmdata&requestid=' + loaderid + '&doctype=DOWNLOADS&sort=published&productid=' + productids + '-HIDE_IN_PSP&locale=' + this.locale_api[productids] + '&maxrecords=' + listsize + '&matchallcategories=y&callback=DownloadsModule.successLinks');
	},
	
	'storeHardcodedLists': function() {
		/* hold onto any hard-coded lists for display later */
		var hardcoded = $(this.container).immediateDescendants();
		hardcoded.each(function(el) {
			if (el.readAttribute('position') != null && el.readAttribute('position') != '') {
				if (el.readAttribute('position') == 'top') {
					this.hard_list_top.push(el);
				}
				else if (el.readAttribute('position') == 'bottom') {
					this.hard_list_bottom.push(el);
				}
			}
			else {
				this.hard_list_top.push(el);
			}
		}.bind(this));
		$(this.container).immediateDescendants().invoke('remove');
	},
	
	'successLinks': function(json, requestId) {
		var has_results = false;
		var request_container = this.links_container + '_' + requestId;
		new PeriodicalExecuter(function(pe) {
			if ($(request_container) != null) {
				if (json != undefined && json != null) {
					if ($('dm_spinner').visible()) { $('dm_spinner').hide(); }
					for (i = 0; i < json['results'].length; i++) {
						if (json.results[i] != null) {
							if (this.dm_results.indexOf(json.results[i].url) == -1) {
								var ahref = new Element('a', {
									'href': json.results[i].url,
									'onclick': 's_objectID=\'' + json.results[i].url + '_dm_' + requestId + '-' + i + '\';'
								});
								ahref.update(json.results[i].title);
								portletData = new Element('li').insert(ahref);
								$(request_container).insert(portletData);
								this.dm_results.push(json.results[i].url);
								has_results = true;
							}
						}
					}
					if (has_results) {
						$(this.links_container + '_mid').appear({'duration': 0.3});
					}
				}
				pe.stop();
			}
		}.bind(this), 0.1);
	},
	
	'successCheckProduct': function(json) {
		if (json.hasdownloads != undefined && json.hasdownloads == true && json.id != undefined && json.urlpath != undefined) {
			this.locale_api[json.id] = this.getLocaleForApi();
			this.urlpath[json.id] = json.urlpath;
		}
		else {
			this.locale_api[json.id] = this.default_locale;
			this.urlpath[json.id] = '';
		}
		this.createDownloadsLinks(json.id);
	}
	
};

Event.observe(window, 'load', function() {
	$$('ul.portlet').each(function(port) { port.innerHTML = '<img src="http://images.apple.com/support/main/elements/aqua2spinner12.gif">'; });
});
