﻿if (typeof(TS) == 'undefined') TS = {};


TS.Panel = Class.create({

	baseURL: '/support/mobileme/',
	defaultLanguage: 'en',
	defaultCountry: 'US',
    
	issuesdiv: null,
    categoriesAndTopics: {},

	initialize: function(issuesdiv) {
		if (!issuesdiv) return false;
		this.issuesdiv = issuesdiv;
		this.loadCategoriesAndTopics(this.baseURL + this.getLangDir() + '/_issues.xml');
		window.overlay = new TS.Overlay();
	},

	loadCategoriesAndTopics: function(url) {
		if (!url) return false;
        
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				var response = transport.responseXML;
				this.buildPage(response);
			}.bind(this)
		});
	},

	buildPage: function(response) {
		this.currentTopicCount = 1;

		var categories = $A(response.getElementsByTagName('category'));
        this.categoriesAndTopics = categories;
        
		categories.each(function(category) {
			// for each category, create elements
			var categorydiv = new Element('div', { 'class':'category' });
			var categoryh3 = new Element('h3');
			categoryh3.innerHTML = category.getAttribute('title');
			// onclick for categories
			categoryh3.observe('click', function() {
				new TS.Drawer(categorydiv, topicdiv);
			
				if (categorydiv.hasClassName('selected')) {
					this.showMessage('select-topic');
					/* only do click tracking when menu opens */
					this.clickTracking(undefined, undefined, this.truncateTitle(category.getAttribute('title')), undefined);
				} else {
					this.showMessage('select-category');
				}
				if (categorydiv.hasClassName('secondary')) categorydiv.removeClassName('secondary');

 				this.getSolutions(topicdiv);
			}.bind(this));
			categorydiv.insert(categoryh3);

			// set option: email form type
			var emailOption;
			if (category.getElementsByTagName('emailform')[0].firstChild) emailOption = category.getElementsByTagName('emailform')[0].firstChild.nodeValue;
			categorydiv.setAttribute('emailform', emailOption);

			// set option: show or hide chat link
			var chatOption;
			if (category.getElementsByTagName('chat')[0].firstChild) {
				chatOption = category.getElementsByTagName('chat')[0].firstChild.nodeValue;
			}
			categorydiv.setAttribute('chat', chatOption);
			
			var chatSkill = 'none';
			if (category.getElementsByTagName('chat')[0].getAttribute('skill')) {
				chatSkill = category.getElementsByTagName('chat')[0].getAttribute('skill');
			}
			categorydiv.setAttribute('chatskill', chatSkill);
			
			var chatLanguage = 'none';
			if (category.getElementsByTagName('chat')[0].getAttribute('language') != null) {
				chatLanguage = category.getElementsByTagName('chat')[0].getAttribute('language');
			}
			categorydiv.setAttribute('chatlanguage', chatLanguage);
			
			var chatEnabled = 'off';
			if (category.getElementsByTagName('chat')[0].getAttribute('enabled') != null) {
				chatEnabled = this.isChatEnabled(category.getElementsByTagName('chat')[0].getAttribute('enabled'));
			}
			categorydiv.setAttribute('chatenabled', chatEnabled);

			// create wrapper elements for topics
			var topicdiv = new Element('div', { 'class':'drawer', 'style':'display:none;' });
			var topicul = new Element('ul');

			// create each topic element
			var topics = $A(category.getElementsByTagName('topic'));
			topics.each(function(topic, i) {
				var topicli = new Element('li', { 'id':'topic_' + this.currentTopicCount });
				var span = new Element('span');
				var span2 = new Element('span').update(topic.getAttribute('title'));
				span.insert(span2);
				topicli.insert(span);

				// add 'last' class for last list item
				if (i == topics.length-1) topicli.addClassName('last');

				// grab all solutions for this topic
				var solutions = $A(topic.getElementsByTagName('solution'));
				solutions.each(function(solution) {
					if (solution.firstChild) var solutionID = solution.firstChild.nodeValue;
                    
					// add attribute to LI:
					if (solutionID) {
						var currentAttribute = topicli.getAttribute('articles');
						if (currentAttribute) solutionID = currentAttribute + ',' + solutionID;
						topicli.setAttribute('articles', solutionID);
					}
				}.bind(this));
                

				topicli.observe('click', function() {
					// if the topic is already selected, do nothing
					if (topicli.hasClassName('selected')) return false;

					// unselect other topics and hide their solutions
					this.removeSelected(categorydiv.down('li.selected'));
					this.removeSelected($('articles').down('div.selected'))
							
					// give category it's secondary selected class:
					categorydiv.addClassName('secondary');
							
					// select this topic
					topicli.addClassName('selected');

					// if 'have you tried?' section is hidden, unhide it. and remove 'Return to Solutions' link
					$('haveyoutried').style.display = 'inline';
					if ($('return')) $('return').remove();

					this.chatToggle(categorydiv);
					this.setEmailLink(categorydiv);
					this.showMessage('select-article');
					this.buildArticles(topicli, categorydiv);
					this.clickTracking(undefined, undefined, this.truncateTitle(category.getAttribute('title')+' - '+topic.getAttribute('title')), undefined);
				}.bind(this));
				
				topicul.insert(topicli);
			
				this.currentTopicCount++;
			}.bind(this));

			topicdiv.insert(topicul);
			categorydiv.insert(topicdiv);

			// finally, add all elements for this category/topics to the page
			this.issuesdiv.insert(categorydiv);
		}.bind(this));
		
		this.issuesdiv.removeClassName('loading');
	},
	
	buildArticles: function(topicli, categorydiv) {
		// grab article ids
		var articles = topicli.getAttribute('articles');
        
		// build elements for associated articles
		var topicid = topicli.id.split('_')[1];

		this.removeSelected($('haveyoutried').down('div.selected'));

		var collectiondiv = $('collection_' + topicid);
		collectiondiv.addClassName('selected');
	
		// if it's filled with data already, don't do it again
		if (collectiondiv.down('p')) return false;

		var ids;
		if (articles.indexOf(',') != -1) {
			ids = articles.split(',');
		}
		else {
			ids = [articles];
		}

		var testIfLoaded = function() {
			var loaded = true;
			ids.each(function(id) {
				var article = Object.clone(TS.Solutions.prototype.articles[id]);
				if (!article.url) loaded = false;
			});

			if (!loaded) {
				setTimeout(testIfLoaded, 300);
			} else {
				ids.each(function(id) {
					var article = Object.clone(TS.Solutions.prototype.articles[id]);
                    
					var title = article.title;
					var url = article.url;
					var excerpt = (article.excerpt != null) ? article.excerpt : '';
					var type = article.type;
					var locale = article.locale;
					
					// shorten the excerpt
					// handle truncation differently for ja
					if (this.getLocale()[0] == 'ja') {
						if (excerpt.indexOf('。') != -1) {
							var shortened = excerpt.split('。');
							excerpt= shortened[0] + '。';
						}
						//else if (excerpt.indexOf('�') != -1) {
						//	excerpt = excerpt.replace(/�/, ' ...');
						//}
					}
					else {
						var excerptLimit = 150; // # of characters
						if (excerpt.length > excerptLimit) {
							excerpt = excerpt.truncate(excerptLimit);
							var words = excerpt.split(' ');
							excerpt = '';
							words = words.without(words.last());
							words.each(function(word) {
								excerpt += ' ' + word;
							});
							excerpt += '...';
						}
					}

					// build elements for single article
					var titleh4 = new Element('h4');
					var titleLink = new Element('a', { 'href':url, 'target': '_blank' });
					titleLink.innerHTML = title;

					var excerptP = new Element('p')
					excerptP.innerHTML = excerpt;

					titleh4.insert(titleLink);
					collectiondiv.insert(titleh4);
					collectiondiv.insert(excerptP);
                    
                    if(type!='page') {
                        titleLink.observe('click', function(evt) {
                            if (evt) evt.stop();
                            var title = titleLink.innerHTML;

                            // get the email form attribute
                            var collection = titleLink.up('.collection');
                            var collectionId = collection.id.split('_')[1];
                            var categorydiv = $('topic_' + collectionId).up('.category');
                            
                            var emailonly;
                            var chatOption = categorydiv.getAttribute('chat');
                            if (chatOption == 'show') {
                                emailonly = false;
                            } else {
                                emailonly = true;
                            }

                            var emailform = categorydiv.getAttribute('emailform');

                            window.overlay.update(title, id, type, locale, emailform, emailonly);

                            // set click tracking
                            this.clickTracking(id, type, this.truncateTitle(title), undefined);
                        }.bind(this));
                    }
                    
				}.bind(this));			
			}
		}.bind(this)
		
		testIfLoaded();	
	},

	removeSelected: function(selected) {
		if (selected) selected.removeClassName('selected');
	},

	getSolutions: function(topicdiv) {
		var queryString = '';
        
		var topics = topicdiv.select('li');
        var topicIteration = 0;
        
		topics.each(function(topic){
			var id = topic.id.split('_')[1];

			// if articles are already on the page, don't make another call
			if ($('collection_' + id)) return false;

			var collectiondiv = new Element('div', { id:'collection_' + id, 'class':'collection' });
			var loadingImage = new Element('img', { src:'http://images.apple.com/search/images/waitanimation.gif', 'class':'loading' });
			collectiondiv.insert(loadingImage);
			$('articles').insert({ before:collectiondiv });

			// grab article ids from the topic
			var queries = topic.getAttribute('articles').split(',');
            var solutions = $A(topic.getElementsByTagName('solution'));
            var solutionIteration = 0;
            
			// only ask api for articles that haven't already been loaded
			queries.each(function(query) {
				if (!TS.Solutions.prototype.articles[query]) {
                
                    if(query.indexOf("http://")==0) {

                        // we do not need a call for this type, just add it to the articles array
						this.categoriesAndTopics.each(function(cat) {
							var tops = cat.getElementsByTagName('topic');
							$A(tops).each(function(top) {
								var sols = top.getElementsByTagName('solution');
								$A(sols).each(function(sol) {
									if (sol != undefined && sol != null) {
										if (sol.getAttribute('type') == 'page') {
											if (query == sol.firstChild.nodeValue) {
												TS.Solutions.prototype.articles[query] = {
							                    	title: sol.getAttribute('title'),
													url: query,
													excerpt: sol.getAttribute('excerpt'),
													type: 'page',
													locale: 'en_US'
							                    }
											}
										}
									}
								});
							});
						});
						
                        //var thisSolution =  this.categoriesAndTopics[0].getElementsByTagName('topic')[topicIteration].getElementsByTagName('solution')[solutionIteration];
						/*TS.Solutions.prototype.articles[query] = {
	                            title: thisSolution.getAttribute('title'),
	                            url: query,
	                            excerpt: thisSolution.getAttribute('excerpt'),
	                            type: 'page',
								locale: 'en_US'
	                    }*/
						//TS.Solutions.prototype.articles[query] = {}

                    }
                    else {
                    
                        if (queryString != '') {
                            queryString += ',';
                        }
                        // omit URL's that are hard coded
                        query = query.indexOf("http://")==0 ? "" : query;
                        queryString += query;
                        
                    }
					
				}
                
                solutionIteration++;
                
			}.bind(this));
            
            topicIteration++;
            
		}.bind(this));

		// if there are new articles, make the api call
		if (queryString) new KmLoader(1, null, null, null, queryString, null, this.getLocale()[0]+'_'+this.getLocale()[1], null, 1);
	},

	chatToggle: function(categorydiv) {
		var topic = $A(categorydiv.select('h3')).first();
		var subtopic = $A(categorydiv.select('li.selected span span')).first();
		
		if (categorydiv.getAttribute('chatenabled') == 'on' && categorydiv.getAttribute('chat') == 'show' && categorydiv.getAttribute('chatskill') != 'none' && categorydiv.getAttribute('chatlanguage') != 'none') {
			if (topic != undefined && subtopic != undefined) {
				$$('div#stillneedhelp h3').first().hide();
				$('helpchat').hide();
				$('helpemail').hide();
				createChatButton(categorydiv.getAttribute('chatskill'), categorydiv.getAttribute('chatlanguage'), topic.innerHTML, subtopic.innerHTML, this.getLocale()[1]);
			}
		}
		else if (categorydiv.getAttribute('chatenabled') == 'off' || categorydiv.getAttribute('chat') == 'hide') {
			$$('div#stillneedhelp h3').first().hide();
			$('helpchat').hide();
			$('helpemail').hide();
			if (this.defaultCountry != this.getLocale()[1]) {
				$$('div#stillneedhelp h3').first().appear({duration:1.0});
				$('helpemail').appear({duration:1.0});
			}
		}
	},
	
	isChatEnabled: function(locales) {
		var chatEnabledLocales = (locales.indexOf(',') != -1) ? locales.split(',') : [locales];
		var currentLocale = this.getLocale()[0] + '_' + this.getLocale()[1];
		var chatEnabledBool = 'off';
		chatEnabledLocales.each(function(loc) {
			if (currentLocale == loc) {
				chatEnabledBool = 'on';
			}
		});
		return chatEnabledBool;
	},

	setEmailLink: function(categorydiv) {
		var emailform = categorydiv.getAttribute('emailform');
		var link = $('helpemail').down('a.button');
		if (!link.getAttribute('original')) {
			link.setAttribute('original', link.href);
		}
		
		// pass selected topic and subtopic to email form
		var topic = $A(categorydiv.select('h3')).first();
		var subtopic = $A(categorydiv.select('li.selected span span')).first();
		var topicsurl = '&topic=' + encodeURI(topic.innerHTML).replace(/\//g,'%2F').replace(/\&amp;/g,'%26') + '&subtopic=' + encodeURI(subtopic.innerHTML).replace(/\//g,'%2F').replace(/\&amp;/g,'%26');
		link.href = link.getAttribute('original') + '?form=' + emailform + topicsurl;
	},

	showMessage: function(div) {
		var div = $(div);

		// hide other messages
		this.removeSelected(div.parentNode.down('.swap.selected'))
		
		// show this message
		div.addClassName('selected');
	},

	reset: function() {		
		// close drawer, if drawer is open
		var categorydiv = $('issues').down('.category.selected');
		if (categorydiv) {
			var drawer = categorydiv.down('.drawer');
			TS.Drawer.prototype.closeDrawer(categorydiv, drawer);
			if (categorydiv.hasClassName('secondary')) categorydiv.removeClassName('secondary');
		}

		// show default message
		this.showMessage('select-category');

	},

	showContact: function() {
		var backLinkP = new Element('p', { id:'return' });
		var backLink = new Element('a').update('&laquo; ' + TS.text.returnToSolutions);
		backLink.observe('click', function() {
			var effect = Effect.BlindDown($('haveyoutried'), {duration:0.3});
			backLinkP.remove();
		});
		backLinkP.insert(backLink);
		$('select-article').insert({ top:backLinkP });

		var effect = new Effect.BlindUp($('haveyoutried'), {duration:0.3});
	},

	clickTracking: function(id, type, title, url) {
		var this_title = (title != undefined) ? title : '';
		var url = (url != undefined) ? url: document.URL;
		var tracking_title = '';
		if (id != undefined && type != undefined) {
			if (type == 'kbase') {
				tracking_title += id + ': ';
			}
			if (this_title != '') {
				tracking_title += this_title;
			}
		}
		else if (this_title != '') {
			tracking_title += this_title;
		}
		if (typeof(SCReporting) != 'undefined') {
			SCReporting.trackClick(tracking_title, url);
		}
	},
	
	truncateTitle: function(title) {
		return (title != undefined) ? title.truncate(70) : title;
	},
	
	customLinkTracking: function(id, type, title, url) {
		// send custom link data to SiteCatalyst
		var podcountry = this.readCookie('POD')!==null ? this.readCookie('POD').substring(0,2).toUpperCase() : this.defaultCountry;
		var title = (title!=undefined) ? title : "";
		var url = (url!=undefined) ? url : document.URL;
		var tracking_title = "";
		
		// article type is defined (kbase, help, etc)
		if (id!=undefined && type!=undefined) {
			if (type=='kbase') {
				tracking_title += id + ": ";
			}
			tracking_title += (title!="") ? title : document.title;
			tracking_title = tracking_title.truncate(70) + " (" + podcountry + " Me)";
		}
		else {
			tracking_title += document.title;
			if (title!="") {
				tracking_title += " - " + title;
			}
			tracking_title = tracking_title.truncate(70) + " (" + podcountry + ")";
		}
		if (typeof(s_gi) != 'undefined') {
			var s = s_gi(s_account);
			s.linkTrackVars='pageName,prop1,prop2,prop4,prop5,prop6,events,pageURL,referrer';
			s.pageName = tracking_title;
			s.prop1 = '';
			s.prop2 = '';
			s.prop4 = url;
			s.prop5 = '';
			s.prop6 = s.getQueryParam('cp')+": "+s.pageName;
			s.events = '';
			s.pageURL = url;
			s.referrer = s.fl(s.wd.location ? s.wd.location : '', 255);
			s.tl(true,'o',s.pageName);
		}
	},

	readCookie: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
		}
		return null;
	},
	
	getLocale: function() {
		var lang = this.defaultLanguage;
		var country = this.defaultCountry;
		var pod = this.readCookie('POD');
		if (pod !== null && pod.indexOf('~') != -1) {
			lang = pod.split('~')[1].toLowerCase();
			country = pod.split('~')[0].toUpperCase();
		}
		return [lang, country];
	},
	
	getLangDir: function() {
		var language = this.getLocale()[0];
		var country = this.getLocale()[1];
		var supported_langs = ['fr','de','ja'];
		var langdir = this.defaultLanguage;
		supported_langs.each(function(lang) {
			if (language == lang) {
				langdir = language;
			}
		});
		return langdir;
	},
	
	writeArticleURL: function(articletype, articleid) {
		var articleurl = undefined;
		if (articletype != undefined && articleid != undefined) {
			if (articletype == 'kbase') {
				articleurl = 'http://support.apple.com/kb/' + articleid;
			}
			else if (articletype == 'help') {
				articleurl = 'http://docs.info.apple.com/article.html?path=' + articleid;
			}
		}
		return articleurl;
	}

});


TS.Drawer = Class.create();
Object.extend(TS.Drawer.prototype, TS.Panel.prototype);
Object.extend(TS.Drawer.prototype, {
	initialize: function(categorydiv, drawer) {
		if (categorydiv.hasClassName('selected')) {
			this.closeDrawer(categorydiv, drawer);
		} else {
			this.openDrawer(categorydiv, drawer);
		}
	},
	
	openDrawer: function(categorydiv, drawer) {
		// close selected drawer first
		var selected = $('issues').down('.category.selected');
		if (selected) {
			var selectedDrawer = selected.down('.drawer');
			this.closeDrawer(selected, selectedDrawer);
		}

		// open drawer, set as selected
		categorydiv.addClassName('selected');
		var effect = new Effect.BlindDown(drawer, {duration:0.3});
	},

	closeDrawer: function(categorydiv, drawer) {
		if (!categorydiv) return false;
		categorydiv.removeClassName('selected');
		
		// unselect currently selected topic
		this.removeSelected(categorydiv.down('li.selected'));

		var effect = new Effect.BlindUp(drawer, {duration:0.3});
	}
});


TS.Overlay = Class.create();
Object.extend(TS.Overlay.prototype, TS.Panel.prototype);
Object.extend(TS.Overlay.prototype, {

	initialize: function(title, articleid, options) {
		this.title = title;
		this.articleid = articleid;

		this.options = options || {};
		if (!this.options.show) this.options.show = {};
		if (!this.options.hide) this.options.hide = {};

		this.options.show.afterFinish = function() {
			$('overlay').down('.content').addClassName('selected')
		}
		this.options.hide.beforeStart = function() {
			$('overlay').down('.content').removeClassName('selected')
		}

		this.createOverlay();
		this.createShadow();
		this.createObstruction();
	},

	createOverlay: function() {
		if (this.overlay) return false;

		this.overlay = new Element('div', { id:'overlay', 'style':'display:none;' });

		// bring in overlay html:
		var url = this.baseURL + this.getLangDir() + '/overlay.html';
		new Ajax.Request(url, {
			method: 'get',
			onSuccess: function(transport) {
				// embed html into page
				this.overlay.innerHTML = transport.responseText;

				// set event handlers
				var close = this.overlay.down('.close a')
				close.observe('click', function() {
					this.options.hide['afterFinish'] = '';
					this.clickTracking(this.articleid, this.articletype, this.truncateTitle(this.title)+' - Close', this.articleurl);
					this.hide();
				}.bind(this));
				
				var yes = this.overlay.down('.yes a');
				yes.observe('click', function() {
					this.options.hide['afterFinish'] = function() {
						this.reset();
					}.bind(this);
					this.clickTracking(this.articleid, this.articletype, this.truncateTitle(this.title)+' - Yes', this.articleurl);
					this.hide();
				}.bind(this));

				var no = this.overlay.down('.no a')
				no.observe('click', function() {
					this.options.hide['afterFinish'] = '';
					this.clickTracking(this.articleid, this.articletype, this.truncateTitle(this.title)+' - No', this.articleurl);
					this.hide();
				}.bind(this));

				var contact = this.overlay.down('.contact a');
				contact.observe('click', function(evt) {
					if (evt) evt.stop();

					if (this.emailonly == false) {
						this.options.hide['afterFinish'] = function() {
							this.showContact();
						}.bind(this)
						this.hide();			
					}
					else {
						var topic = $$('div.category.selected h3').first();
						var subtopic = $$('li.selected span span').first();
						window.location = contact.href + '?form=' + this.emailform + '&topic=' + encodeURI(topic.innerHTML).replace(/\//g,'%2F').replace(/\&amp;/g,'%26') + '&subtopic=' + encodeURI(subtopic.innerHTML).replace(/\//g,'%2F').replace(/\&amp;/g,'%26');
					}
					this.clickTracking(this.articleid, this.articletype, this.truncateTitle(this.title)+' - Contact', this.articleurl);
				}.bind(this));

				this.content = this.overlay.down('.content');
				this.createContent(this.articlelocale);
				this.hide();
			}.bind(this)
		});

		$(document.body).insert({ bottom: this.overlay });
	},

	createShadow: function() {
		if (!this.shadow) {
			var imageSrc = 'http://images.apple.com/support/mobileme/images/overlay_shadow.png';  // TODO: change path
			var image = new Element('img', { 'src':imageSrc });
			this.shadow = $('overlayshadow') || new Element('div', { id: 'overlayshadow', 'style':'display:none;' });
			this.shadow.appendChild(image);

			document.body.appendChild(this.shadow);
		}
	},
	
	createObstruction: function() {
		if (!this.obstruction) {
			this.obstruction = $('overlayobstruction') || new Element('div', { id:'overlayobstruction', 'style':'display:none;' });
			this.obstruction.style.height = (document.body.offsetHeight>document.viewport.getHeight()) ? document.body.offsetHeight+'px' : document.viewport.getHeight()+'px';

			// click on the page and close the overlay
			this.obstruction.observe('click', this.hide.bind(this));

			document.body.appendChild(this.obstruction);
		}
	},

	createContent: function(articlelocale) {
		this.content.addClassName('loading');
		this.content.innerHTML = '';

		var title = new Element('h2', { 'class':'title' });
		title.innerHTML = this.title;

		this.content.insert(title);

		// api call
		var locale = (articlelocale != undefined) ? articlelocale : this.defaultLanguage + '_' + this.defaultCountry;
		new KmLoader(this.articleid, locale);
	},

	show: function() {
		// verically and horizontally center
		var overlayMarginLeft = -(this.overlay.getWidth()/2);
		this.overlay.style.marginLeft = overlayMarginLeft + 'px';
		this.shadow.style.marginLeft = overlayMarginLeft - 13 + 'px';
		if (typeof document.body.style.maxHeight === 'undefined') {
			// if ie6
			var html = $$('html')[0];
			$(html).setStyle({
				overflow: 'hidden',
				height: '100%',
				width: '100%'
			});
			$(html.down('body')).setStyle({
				height: '100%',
				width: '100%'
			});
		} else {
			// other browsers
			var overlayMarginTop = -(this.overlay.getHeight()/2);
			this.overlay.style.marginTop = overlayMarginTop + 'px';
			this.shadow.style.marginTop = overlayMarginTop - 13 + 'px';		
		}

		new Effect.Parallel([
			Effect.Appear(this.overlay, { sync:true }),
			Effect.Appear(this.shadow, { sync:true }),
			Effect.Appear(this.obstruction, { to:.5, sync:true })
		], {
			duration:.5,
			beforeStart: this.options.show.beforeStart,
			afterFinish: this.options.show.afterFinish
		});
	},

	hide: function(type) {
		new Effect.Parallel([
			Effect.Fade(this.overlay, { sync:true }),
			Effect.Fade(this.shadow, { sync:true }),
			Effect.Fade(this.obstruction, { sync:true })
		], {
			duration:.5,
			beforeStart: this.options.hide.beforeStart,
			afterFinish: this.options.hide.afterFinish
		});
		if (typeof document.body.style.maxHeight === 'undefined') {
			// if ie6
			var html = $$('html')[0];
			$(html).setStyle({
				overflow: '',
				height: 'auto',
				width: 'auto'
			});
			$(html.down('body')).setStyle({
				height: 'auto',
				width: 'auto'
			});
		}
	},

	update: function(title, articleid, articletype, articlelocale, emailform, emailonly) {
		if (!articleid || !articletype || !articlelocale) return false;
		this.title = title;
		this.articleid = articleid;
		this.articletype = articletype;
		this.articleurl = this.writeArticleURL(articletype, articleid);

		if (emailform) {
			this.emailform = emailform;
		} else {
			this.emailform = '';
		}

		if (emailonly) {
			this.emailonly = true;
		} else {
			this.emailonly = false;
		}

		this.content = $('overlay').down('.content');
		this.createContent(articlelocale);

		this.show();
	}
});


TS.Solutions = Class.create({
	articles: {},

	initialize: function(json, requestId) {
    
		// go through json record and parse results
		json.results.each(function(record, i) {
			if (record != null) {
				// create an id, based on the url
				var id;
				var type;
				var locale = 'en_US';
				if (record.url.indexOf('/kb/') != -1) {
					/* sometimes record.url has a query like '?viewlocale=fr_FR' which should not be part of id */
					if (record.url.indexOf('?') != -1) {
						id = record.url.substring(record.url.indexOf('/kb/') + '/kb/'.length, record.url.indexOf('?'));
						/* set locale of record */
						var params = record.url.toQueryParams();
						if (params.viewlocale != undefined) {
							locale = params.viewlocale;
						}
					}
					else {
						id = record.url.split('/kb/')[1];
					}
					type = "kbase";
				} 
				else if (record.url.indexOf('.html') != -1) {
					id = record.url.split('http://docs.info.apple.com/article.html?path=')[1];
					type = "help";
				}

				// build objects
				this.articles[id] = {
					title: record.title,
					url: record.url,
					excerpt: record.excerpt,
					type: type,
					locale: locale
				}
			}
		}.bind(this));
	},

	parseContent: function(json, requestId) {
        
		// build elements from parsed content
		var parseddiv = new Element('div', { 'class':'parsed' });
		var documentid = '';

		json.records.each(function(record, i) {
			record.each(function(parsed, i) {
				// skip over certain data
				var label = parsed[0];
				if (label == 'REVIEW_PRIORITY' || label == 'OLD_ARTICLE_NUMBER' || label == 'TITLE' || label == 'MASTERIDENTIFIER' || label == 'DISPLAY_PRIORITY' || label == 'REQUEST_FOR_LOCALIZATION' || label == 'LOCALIZED_GRAPHIC_NEEDED' || label == 'ADDITIONAL_AFFECTED_PRODUCT' || label == 'PRODUCT_CATEGORIES' || label == 'ARCHIVE' || label == 'LOCALECODE' || label == 'LASTMODIFIED') return false;
				
				else if (label == 'DOCUMENTID' || label == 'PATH') {
					documentid = parsed[1];
					return false;
				}
				else if (label == 'SHORT_TITLE') {
					// if overlay.update function was called with blank title, use the short title
					var overlaytitle = $('overlay').down('.title');
					if (!overlaytitle.innerHTML) {
						overlaytitle.update(parsed[2]);
					}
					return false;
				}

				var title = parsed[1];
				if (title != 'Content') {
					var titleh3 = new Element('h3');
					titleh3.innerHTML = title;
				}

				var content = parsed[2];
				// set any links to open in new window
				content = this.customizeLinks(content);

				parseddiv.insert(titleh3);
				parseddiv.insert(content);
			}.bind(this));
		}.bind(this));
		
		// Add article source
		parseddiv.insert(this.addArticleSource(documentid));

		// remove 'loading' class on content area
		var content = $('overlay').down('.content');
		content.removeClassName('loading');

		// insert content to overlay
		content.appendChild(parseddiv);
	},
	
	customizeLinks: function(htmlContent) { 		
		if(htmlContent) {
			var span = new Element('span').update(htmlContent);
			// parse links
			span.select('a').each(function(link) {
				var href = link.readAttribute('href');
				if (!href) {  }
				// remove MobileMe Support links
				else if (href.search(/(?:http\:\/\/www\.apple\.com)?(?:\/?.{2,5})?\/support\/(?:mobileme(?:\/ww)?|dotmac\/?.*)/) != -1) {
					var linktext = link.innerHTML;
					link.replace(linktext);
				}
				// open kbase links in overlay
				else if (href.search(/http:\/\/support.apple.com\/kb\/(HT\d{1,6}|TS\d{1,6})/) != -1) {
					var kbaseid = href.match(/http:\/\/support.apple.com\/kb\/(HT\d{1,6}|TS\d{1,6})/);
					link.writeAttribute({'onclick': 'window.overlay.update(\'\', \'' + kbaseid[1] + '\', \'kbase\', \'en_US\', \'default\', true); return false;'});
				}
				// open other links in separate window
				else {
					link.writeAttribute({'target': '_blank'});
				}
			});
			// parse images
			span.select('img').each(function(image) {
				var src = image.readAttribute('src');
				if (!src) {  }
				// make relative images absolute
				else if (src.search(/^\s*https?\:\/\//) == -1) {
					var host = 'http://km.support.apple.com';
					if (src.search(/^\s*[^\/]/) != -1) {
						host += '/';
					}
					image.writeAttribute({'src': host + src});
				}
			});
			// wrap content in <p> if needed
			if (!span.innerHTML.startsWith('<p>')) {
				span.innerHTML = '<p>' + span.innerHTML + '</p>';
			}
			return span.innerHTML;
		}
	},
	
	addArticleSource: function(documentid) {
		if (this.articles[documentid] != undefined && this.articles[documentid].url != undefined) {
			var article_source =  new Element('p').addClassName('article_source').update('Article source: <a href="' + this.articles[documentid].url + '" target="_blank">' + this.articles[documentid].url + '</a>');
			return article_source;
		}
		else {
			return;
		}
	}
});



JSONscriptRequest.prototype.fullUrl = "http://support.apple/kb/"; 

// you need to set this if you are using anything but production
//KmLoader.akamaiUrl = 'http://support-uat.apple.com';  

KmLoader.success = function(json, requestId) {
	if (json == undefined || json == null) {
		alert('Something went wrong. Please try again!') 
	} else if (json.results) {
		var loadingImages = $('haveyoutried').getElementsBySelector('img.loading');
		loadingImages.each(function(image) {
			image.remove();
		});

		// for title, link & excerpt:
		new TS.Solutions(json, requestId);
	} else if (json.records) {
		// for article content:
		TS.Solutions.prototype.parseContent(json, requestId);
	}
}; // KmLoader.success

KmLoader.error = function(errorMsg, requestId) {
	//alert('RequestId: ' + requestId + " Error: " + errorMsg);
}

KmLoader.logCall = function(urlValue) {
	// show spinning ball:
	//	$('content').innerHTML = '<img src="http://images.apple.com/support/aruba/main/elements/aqua2spinner12.gif">';
	//	$('content').style.display = 'block';
}


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