/** Configipedia helper script
  *  + shows a list of categories when you type in 'TidewayInfobox'
  *  + fixes labels if they are not up-to-date on pages with 'TidewayInfobox'
  *  + replaces deprecated categories/labels with new values
  *
  * WARNING: REMEMBER ABOUT BOTH EDITPAGE AND CREATEPAGE FORMS!!!
  */

AJS.toInit(function () {
	var possible_categories = [
		'Application Deployment Software',
		'Application Server Software Platforms',
		'Archive and HSM Software',
		'Automated Software Quality Tools',
		'Change and Configuration Software',
		'Clustering and Availability Software',
		'Content Management',
		'Data Integration and Access Software',
		'Data Protection and Recovery Software',
		'End-User Query, Reporting, and Analysis',
		'Enterprise Portals',
		'Enterprise Resource Management Applications',
		'Event Automation Tools',
		'Hardware',
		'Hardware Consolidation',
		'Identity and Access Management',
		'Integrated Collaborative Environments',
		'Integration Server Software Platforms',
		'Job Scheduling Tools',
		'Message Oriented Middleware',
		'Network Management Software',
		'Nonrelational Database Management Systems',
		'Output Management Tools',
		'Performance Management Software',
		'Relational Database Management Systems',
		'Secure Content and Threat Management',
		'Software Configuration Management Tools',
		'Storage Infrastructure Software',
		'Storage Management Software',
		'System and Network Management Software',
		'Transaction Server Middleware',
		'Virtual Machine Software',
		'Virtual User Interface Software'];
	var deprecated_categories = [
	    {old:'End User, Query, and Reporting Analysis', new:'End-User Query, Reporting, and Analysis'},
	    {old:'End User Query and Reporting Analysis', new:'End-User Query, Reporting, and Analysis'}];
	var configipedianonceproductpagemessage = '<span style="color: grey; margin-left:20px;"><span><a href="'+AJS.General.getContextPath()+'/display/Configipedia/Restricted+access" target="_blank"><img src="'+AJS.General.getContextPath()+'/images/icons/lock_16_grey.png" width="16" height="16" style="float:none; margin-right: 5px;position:relative; top:0.2em;"></a>This page is for a product that is not included in the community edition, and so will be <a href="'+AJS.General.getContextPath()+'/display/Configipedia/Restricted+access" target="_blank">restricted to customers only</a>.</span><br /><span style="margin-left: 43px;">To be publically visible, the product must be in the <a href="'+AJS.General.getContextPath()+'/display/Configipedia/TKU+Community+Edition" target="_blank">community edition</a>.</span></span>';

	var configipediahelper1 = document.createElement('div');
	configipediahelper1.id = 'configipedia-helper-1';
	configipediahelper1.style.display = 'none';
	var configipediahelper2 = document.createElement('div');
	configipediahelper2.id = 'configipedia-helper-2';
	configipediahelper2.style.display = 'none';
	var configipediahelper3 = document.createElement('div');
	configipediahelper3.id = 'configipedia-helper-3';
	configipediahelper3.style.display = 'none';
	var configipediahelper4 = document.createElement('div');
	configipediahelper4.id = 'configipedia-helper-4';
	configipediahelper4.style.display = 'none';

	var infomsg1 = '<table cellpadding="5" cellspacing="8px" class="infoMacro" border="0" align="center"><tbody>';
	infomsg1 += '<tr><td valign="top" width="1%"><img src="'+AJS.General.getContextPath()+'/images/icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td>';
	infomsg1 += '<td onclick="var c=document.getElementById(\'configipedia-helper-1-list\');if(c.style.display==\'none\')AJS.$(c).slideToggle(\'slow\');else c.style.display=\'none\';">';
	infomsg1 += 'You are dealing with a product page, <b><u>click</u></b> for the list of possible categories for <b>copy&amp;paste</b>';
	infomsg1 += ' or <b>drag\'n\'drop</b>:</td></tr><tr><td colspan=2><div id="configipedia-helper-1-list" style="display:none;"><ul>';
	for(var cat = 0; cat < possible_categories.length; cat++)
		infomsg1 += '<li style="display:inline; float: left; width: 33%">'+possible_categories[cat]+'</li>';
	infomsg1 += '</ul></td></tr></tbody></table>';
	configipediahelper1.innerHTML = infomsg1;

	var infomsg2 = '<table cellpadding="5" cellspacing="8px" class="infoMacro" border="0" align="center"><tbody>';
	infomsg2 += '<tr><td valign="top" width="1%"><img src="'+AJS.General.getContextPath()+'/images/icons/emoticons/information.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td>';
	infomsg2 += '<td>The labels were adjusted according to the contents of the page. Please recheck them or <a href="#">revert labels back</a> and disable auto-adjustment.</td></tr></tbody></table>';
	configipediahelper2.innerHTML = infomsg2;
	
	var infomsg3 = '<table cellpadding="5" cellspacing="8px" class="noteMacro" border="0" align="center"><tbody>';
	infomsg3 += '<tr><td valign="top" width="1%"><img src="'+AJS.General.getContextPath()+'/images/icons/emoticons/warning.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td>';
	infomsg3 += '<td>Please click to <a href="#">adjust the location of this page</a>.<br />It should be better located at <b>\'Configipedia &gt; <span id="configipedia-helper-3-page">Products</span>\'</b>.</td>';
	infomsg3 += '</td></tr></tbody></table>';
	configipediahelper3.innerHTML = infomsg3;

	var infomsg4 = '<br><table cellpadding="5" cellspacing="8px" class="warningMacro" border="0" align="center"><tbody>';
	infomsg4 += '<tr><td valign="top" width="1%"><img src="'+AJS.General.getContextPath()+'/images/icons/emoticons/warning.gif" width="16" height="16" align="absmiddle" alt="" border="0"></td>';
	infomsg4 += '<td>';
	infomsg4 += 'This product page has a deprecated category &quot;'+deprecated_categories[0].old+'&quot;, it should be changed to &quot;'+deprecated_categories[0].new+'&quot;. You can <a href="#" class="click">click here</a> to adjust wiki markup.';
	infomsg4 += '</td></tr></tbody></table>';
	configipediahelper4.innerHTML = infomsg4;
	configipediahelper4.getElementsByClassName("click")[0].onclick = function(){rebuildContent(form, deprecated_categories);};

	String.prototype.toLabel = function(s)
	{
		return this.toLowerCase().replace(/(,)? /gi,'_').replace(/,/gi,'_');
	}
	
	/**
	 * Adjusts the content replacing deprecated values with new ones.
	 */
	function rebuildContent (form,deprecated_categories)
	{
	  var m = form.content.value.match(/{TidewayInfobox\s*:\s*(\|\s*)?([^}]*)}/i);
	  if(m)
	  {
		var m2 = m[0];
		for(var n = 0; n < deprecated_categories.length; n++)
		  m2 = m2.replace(deprecated_categories[n].old, deprecated_categories[n].new);
		form.content.value = form.content.value.replace(m[0], m2);
	  }
	}
	/**
	 * Adjusts labels according to TidewayInfobox macro.
	 * @returns true - changed labels, warn the user
	 *			false - labels were okay
	 */
	function checkLabels (form, possible_categories, deprecated_categories)
	{
		var m = form.content.value.match(/{TidewayInfobox\s*:\s*(\|\s*)?([^}]*)}/i);
		if(m)
		{
			m = m[2].trim().split('|');
			var publisher = null;
			var categories = null;
			var release = null;
			for(var mm = 0; mm < m.length; mm++)
			{
				if(mmm = m[mm].trim().match(/^\s*Publisher\s*=(.*)$/))
					publisher = mmm[1].trim();
				if(mmm = m[mm].trim().match(/^\s*Categories\s*=(.*)$/))
					categories = mmm[1].trim();
				if(mmm = m[mm].trim().match(/^\s*Release\s*=(.*)$/))
					release = mmm[1].trim();
			}
			
			var curLabels = " "+form.labelsString.value.toLowerCase()+" ";
			var needUpdate = false;
			if(!curLabels.match(/ products /i))
				needUpdate = true;
			if(!needUpdate && publisher && !curLabels.match(" "+publisher.toLabel()+" "))
				needUpdate = true;
			if(!needUpdate && categories && !curLabels.match(" "+categories.toLabel()+" "))
				needUpdate = true;
			if(!needUpdate)
			  for(var n = 0; n < deprecated_categories.length; n++)
			    if(!needUpdate && curLabels.match(" "+deprecated_categories[n].old.toLabel()+" "))
			      needUpdate = true
			if(!needUpdate && release && !curLabels.match(" "+release.toLabel()+" "))
				needUpdate = true;
			
			
			
			if(needUpdate)
			{
				var newLabels = curLabels.replace(/ products /i,' ').replace(/ tku_\d\d\d\d-\w\w\w-\d\d? /i, ' ');
				for(var n = 0; n < deprecated_categories.length; n++)
				  newLabels = newLabels.replace(" "+deprecated_categories[n].old.toLabel()+" ", ' ');
				newLabels = newLabels.replace(" "+publisher.toLabel()+" ", ' ');
				for(var cat = 0; cat < possible_categories.length; cat++)
					newLabels = newLabels.replace(" "+possible_categories[cat].toLabel()+" ", ' ');
				
				newLabels = newLabels.split(/\s+/);
				newLabels = 'products ' + publisher.toLabel()+' ' + categories.toLabel() + ' ' + release.toLabel() + ' ' + newLabels.join(' ').trim();
				
				form.labelsString.value = newLabels;
				document.getElementById('configipedia-helper-2').style.display = "";
				window.scroll(0, AJS.$("body").height());
				
				return true;
			}
			
			document.getElementById('configipedia-helper-2').style.display = "none";
			
			return false;
		}
		
		return false;
	}

	var form = AJS.$("#editpageform, #createpageform");
	if(form.length == 1)
	if(form[0].cancel.length == 2) 
	{
		form = form[0];
		
		/** Attach DIV elements **/
		var subm = AJS.$("#editpageform div.submit-buttons:last, #createpageform div.submit-buttons:last");
		if(subm.length == 1)
			subm[0].parentNode.insertBefore(configipediahelper2, subm[0]);
		
		form.insertBefore(configipediahelper4, form.childNodes[0]);
		form.insertBefore(configipediahelper1, form.childNodes[0]);
		
		var loc = AJS.$("#editpageform #location_info, #createpageform #location_info");
		if(loc.length == 1)
			loc[0].parentNode.appendChild(configipediahelper3);
		
		/** Put special message for non-community-edition product page which will be restricted to guest members only (@see Configipedia/Restricted+access) **/
		if(document.getElementById('configipedianonceproductpageedit'))
		{
			document.getElementById('configipedianonceproductpageedit').innerHTML = configipedianonceproductpagemessage;
			document.getElementById('configipedianonceproductpageedit').style.display = '';
			document.getElementById('configipedianonceproductpageview').style.display = 'none';
		}

		/** Setup events handlers **/
		configipediahelper3.getElementsByTagName('A')[0].onclick = function () {
			if(typeof configipediahelper3.parentpagestring == 'string')
			{
				AJS.$('#editpageform #parent_content, #createpageform #parent_content')[0].innerText = configipediahelper3.parentpagestring;
				form.parentPageString.value = configipediahelper3.parentpagestring;
				AJS.$('#editpageform #parent_info, #createpageform #parent_info').removeClass('hidden');
				form.position.value = 'append';
				form.moveHierarchy.value = 'true';
			}
			return false;
		}
		
		
		var oldclk = (form.cancel[0].onclick == null) ? form.cancel[1].onclick : form.cancel[0].onclick;
		var oldsub = form.onsubmit;
		
		configipediahelper2.getElementsByTagName('A')[0].onclick = function () {
			if(typeof configipediahelper2.originalLabels == 'string')
			{
				form.labelsString.value = configipediahelper2.originalLabels;
				form.onsubmit = oldsub;
				configipediahelper2.style.display = "none";
			}
			return false;
		}
		
		form.onsubmit = function() {
			configipediahelper2.style.display = "none";
			if(typeof configipediahelper2.originalLabels != 'string')
				configipediahelper2.originalLabels = form.labelsString.value;
			var changed = checkLabels(form, possible_categories, deprecated_categories);
			if(changed)
				return false;
			
			if(oldsub) oldsub();
			return true;
		}
		form.cancel[0].onclick = form.cancel[1].onclick = function() {
			form.onsubmit = oldsub;
			if(oldclk) oldclk();
		}
		
		/** Setup ticker **/
		window.setInterval(function (){
			var isproductpage = form.content.value.match(/{TidewayInfobox\s*:/i);
			var isproductpageincorrect = isproductpage && (form.parentPageString.value != 'Products');
			var title = AJS.$('#content-title')[0].value; //WARNING: #content-title IS OUTSIDE #editpageform AND #createpageform
			var isproductsubpagematch = title.match(/^(.+)\s-\s((Reports\s&\sAttributes)|(Product\sLifecycle))$/i);
			var isproductsubpageincorrect = isproductsubpagematch && typeof isproductsubpagematch[1] == 'string' &&
											(form.parentPageString.value != isproductsubpagematch[1]);
			var hasdeprecatedcategory = false;
			for(var n = 0; n < deprecated_categories.length; n++)
			  hasdeprecatedcategory = hasdeprecatedcategory || (form.content.value.indexOf(deprecated_categories[n].old)!= -1);
			configipediahelper1.style.display = isproductpage?'':'none';
			configipediahelper3.style.display = (isproductpageincorrect || isproductsubpageincorrect)?'':'none';
			configipediahelper4.style.display = (isproductpage && hasdeprecatedcategory)?'':'none';
			if(isproductpage)
			{
				configipediahelper3.parentpagestring = 'Products';
			}else if(isproductsubpagematch && typeof isproductsubpagematch[1] == 'string')
			{
				configipediahelper3.parentpagestring = isproductsubpagematch[1];
			}else
			{
				configipediahelper3.parentpagestring = null;
			}
			AJS.$('#configipedia-helper-3-page')[0].innerText = (configipediahelper3.parentpagestring)?configipediahelper3.parentpagestring:'';
		}, 1000);
	}
});





