var searchFieldEntered = false;
function submitPreference() {
}

function doGroupAdd(group, user) {
	$.ajax({
		url: '/cda/components/groups',
		data: { action: 'add', group: group, username: user},
		cache: false,
		error: function(msg) {
			$('#messages').append('<div>Could not add to group: <b>' + group + '</b></div>');
		},
		success: function(msg){
			$('#messages').append('<div>Successfully added to group: <b>' + group + '</b></div>');
		}
	});
}
					
function doGroupRemove(group, user) {
	$.ajax({
		url: '/cda/components/groups',
		data: { action: 'remove', group: group, username: user},
		cache: false,
		error: function(msg) {
			$('#messages').append('<div>Could not remove from group: <b>' + group + '</b></div>');
		},
		success: function(msg){
			$('#messages').append('<div>Successfully removed from group: <b>' + group + '</b></div>');
		}
	});
}

function openSecWindow(URL) {
    window.open(URL,"Ext_Win","menuBar=no,HEIGHT=300,WIDTH=400,resizable,scrollbars");
    return false;
}
function openEditor(editor, id, siteId) {
	var url = $.query(editor).set('id', id).set('s', siteId);
	var w = window.open(url,'oE' + id,"width=790,height=500,directories=no,location=yes,menubar=yes,scrollbars=no,status=yes,toolbar=no,resizable=yes");
	w.focus();
	return false;
}
function oE(contentId, siteId) {
	return openEditor(document.editorURL, contentId, siteId);
}
function oME(menuId, siteId) {
	return openEditor(document.menuURL, menuId, siteId);
}
function oC(siteId, pcId, type) {
	var url = $.query(document.createURL).set('s', siteId).set('pcId', pcId).set('type', type);
	var w = window.open(url,'oE',"width=790,height=500,directories=no,location=yes,menubar=yes,scrollbars=no,status=yes,toolbar=no,resizable=yes");
	changeCDAElt('pref' + pcId);
	w.focus();
	return false;
}
function oMC(siteId) {
	return openEditor(document.createMenuURL, '', siteId);
}
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var address = location.href;
var requestsSerialized;
function encode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   input = input || '';
   do {
      chr1 = input.charCodeAt(i++);
      chr2 = input.charCodeAt(i++);
      chr3 = input.charCodeAt(i++);

      enc1 = chr1 >> 2;
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
      enc4 = chr3 & 63;

      if (isNaN(chr2)) {
         enc3 = enc4 = 64;
      } else if (isNaN(chr3)) {
         enc4 = 64;
      }

      output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
   } while (i < input.length);
   
   return output;
}

function decode64(input) {
   var output = "";
   var chr1, chr2, chr3;
   var enc1, enc2, enc3, enc4;
   var i = 0;

   input = (input || '').replace(/[^A-Za-z0-9\+\/\=]/g, "");
   do {
      enc1 = keyStr.indexOf(input.charAt(i++));
      enc2 = keyStr.indexOf(input.charAt(i++));
      enc3 = keyStr.indexOf(input.charAt(i++));
      enc4 = keyStr.indexOf(input.charAt(i++));

      chr1 = (enc1 << 2) | (enc2 >> 4);
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
      chr3 = ((enc3 & 3) << 6) | enc4;

      output = output + String.fromCharCode(chr1);

      if (enc3 != 64) {
         output = output + String.fromCharCode(chr2);
      }
      if (enc4 != 64) {
         output = output + String.fromCharCode(chr3);
      }
   } while (i < input.length);

   return output;
}

var preferencesName = 'cdaPreferences2';
var preferences;
function getPreferences() {
	if (!preferences) {
		preferences = new $.query('?' + decode64($.cookie(preferencesName)), '|');
	}
	return preferences;
}

function getPreference(name, dv) {
	return getPreferences().get(name) || dv;
}

function setPreference(name, value) {
	getPreferences().set(name, value);
	$.cookie(preferencesName, encode64(getPreferences().toString() + '|a=b'), { expires: 60*60*24*30, path : '/' });
}

function clearPreferences() {
	$.cookie(preferencesName, '', { expires: 1, path : '/' });
	$.cookie('cdaPreferences', '', { expires: 1, path : '/' });
}

function getEditorStatus() {
	return getPreference('editor-' + siteId, 'off');
}

function getSecurityStatus() {
	return getPreference('security-' + siteId, 'off');
}

function openMenuSecurity() {
	openSecWindow('/cda/security/menu?menuId=' + $(this).attr('name'));
}
function openContentSecurity() {
	openSecWindow('/cda/security/content?contentId=' + $(this).attr('name'));
}

function toggleSecurity() {
	if ($('.oS').length > 0) {
		setPreference('security-' + siteId, 'off');
		$('.oS').remove();
	} else {
		setPreference('security-' + siteId, 'on');
		initSecurity();
	}
	return false;
}

function initSecurity() {
	$('a[name]').each(function() {
		var $this = $(this);
		var name = $this.attr('name');
		var type = name.charAt(0);
		if ((type == 'm' || type == 'c') && !isNaN(name.substring(1))) {
			var nav = $('<a href=# name=' + name.substring(1) + ' class=oS><img src=/cma/images/lock.gif border=0></a>');
			nav.click(type == 'm' ? openMenuSecurity : openContentSecurity);
			$this.before(nav);
			nav.show();
		}
	});
}

function toggleEditor() {
	if ($('.oE').length > 0 || $('#pageSpec').hasClass('editorOn')) {
		setPreference('editor-' + siteId, 'off');
		$('#pageSpec').removeClass('editorOn');
		$('.oE').remove();
		$('#inlineCreateMenuLink').remove();
	} else {
		setPreference('editor-' + siteId, 'on');
		initEditor();
	}
	return false;
}

function initEditor() {
	$('.prefDiv').each(function() {
		var $this = $(this);
		var props = $this.attr('id').split('-');
		var id = props[0];
		if (props.length == 2) {
	   		var name = props[1];
			var html = '<a class=inlineCreateLink title="Create New Content" href="#" onclick="changeCDAElt(\'pref' + id + '\'); return false;">'
				+ '<img align=right src="/cma/images/create.gif" id=pref'+id+'Img></a>'
				+ '<span class=pref id=pref' + id + '>'
				+ '<a class=odd href="#" onclick="oC(' + siteId + ',' + id + ',\'A\'); return false;">Article</a>';
			if (name.indexOf('Full Article') == -1) {
				html += '<a class=even href="#" onclick="oC(' + siteId + ',' + id + ',\'F\'); return false;">Managed File</a>'
					+ '<a class=odd href="#" onclick="oC(' + siteId + ',' + id + ',\'W\'); return false;">Web Link</a>';
			}		
	   		html += '<a class=even href="#" onclick="oC(' + siteId + ',' + id + ',\'C\'); return false;">Custom Form</a>'
	   			+ '</span>'
	   			+ '<span class=inlineCreateLink>' + name + '</span>';
			$this.html(html);
		}
	});

	initEditorLinks(document.access);

	$('#pageSpec').addClass('editorOn');
}

var editorLinks = {
	'm' : {'method' : 'oME', 'img' : '<img src=/cma/images/icon.gif border=0>'},
	'c' : {'method' : 'oE', 'img' : '<img src=/cma/images/file.gif border=0>'}
};

function initEditorLinks(access) {
	var menus = access == 'S';
	if (menus) {
		$('#tnav tr').prepend('<td id=inlineCreateMenuLink><a id=inlineCreateLink title="Create New Menu" href="#" onclick="oMC(' + siteId + '); return false;"><img align=right src="/cma/images/create.gif" border="0"></a></td>');
	}
	$('a[name]').each(function() {
		var curr = $(this);
		var name = curr.attr('name');
		var type = name.charAt(0);
		if (((menus && type == 'm') || type == 'c') && !isNaN(name.substring(1))) {
			var id = name.substring(1);
			var nav = $('<a class=oE href="#" onclick="' + editorLinks[type].method + '(\''+id+'\',\''+siteId+'\'); return false;">' + editorLinks[type].img + '</a>');
			curr.before(nav);
			nav.show();
		}
	});
}

function changeCDAElt(eltName) {
		var val = $('#' + eltName);
		var img = $('#' + eltName + 'Img');
		var offset = img.offset();
		
		val.css('top', offset.top + 16);
		val.css('left', offset.left - 70);
		val.toggle();
}

jQuery.query = function(value, sep, valueSep) {
	var params = new Array();
	var s = (sep || '&');
	var vs = (valueSep || '=');
	var parts = value.toString().split('?');
	var uri = parts[0];
	
	if (parts.length > 1) {
		var values = parts[1].split(s);
		for (var i in values) {
			if (values[i].split) {
				var p = values[i].split(vs);
				params[p[0]] = p.length == 2 ? p[1] : '';
			}
		}
	}
	
	this.get = function(p) {
		return params[p];
	}
	
	this.set = function(p,v) {
		params[p] = v;
		return this
	}
	this.getQuery = function() {
		var q = [];
		for (p in params) {
			if (p != '' && params[p] != null && !jQuery.isFunction(params[p])) {
				q[q.length] = p + (params[p] == '' ? '' : vs + params[p]);
			}
		}
		return q.join(s);
	}
	
	this.toString = function() {
		return (uri == '' ? '' : uri + '?') + this.getQuery();
	}
	
	return this;
}

function replaceQueryArg(str, arg, val) {
	var result = str;
	var splitter = '&';
	var queryParts = str.split('&' + arg + '=');
	if (queryParts.length == 1) {
		splitter = '?';
		queryParts = str.split('?' + arg + '=');
	}
	if (queryParts.length == 2) {
		result = queryParts[0] + splitter + arg + '=' + val;
		var nextAmp = queryParts[1].indexOf('&');
		if (nextAmp > -1) {
			result += queryParts[1].substring(nextAmp, queryParts[1].length);
		}
	}
	return result;
}
function removeQueryArg(str, arg) {
	var result = str.split('?').join('&');
	var splitter = '&' + arg + '=';
	var queryParts = result.split(splitter);
	if (queryParts.length == 2) {
		result = queryParts[0];
		var nextAmp = queryParts[1].indexOf('&');
		if (nextAmp > -1) {
			result += queryParts[1].substring(nextAmp, queryParts[1].length);
		}
	}
	result = '?' + result.substring(1);
	return result;
}
var oid;
function getOIDValue(valsToRemove) {
	var query = $.query(oid || location.search);
	if (valsToRemove) {
		var vals = valsToRemove.split(',');
		for (var i = 0; i < vals.length; ++i) {
			query.set(vals[i], null);
		}
	}
	return '?' + (query.get('languageId') ? '' : query.getQuery() + '&');
	/*
	var l = oid || location.search;
	if (valsToRemove) {
		var vals = valsToRemove.split(',');
		for (var i = 0; i < vals.length; ++i) {
			l = removeQueryArg(l, vals[i]);
		}
	}
	if (l.indexOf("&x=") > -1) {
		var qStr = l.split("&x=");
		if (qStr[1].indexOf("&") > -1) {
			return qStr[0] + "&x=" + qStr[1].substring(0, qStr[1].indexOf("&")) + '&';
		} else {
			return qStr[0] + "&x=" + qStr[1] + '&';
		}
	} else if (l.indexOf("languageId=") > -1) {
		return '?';
	} else if (l.indexOf("?x=") > -1) {
		return l + '&';
	}
	return "?";
	*/
}
function sendSearch(formName,searchValue, searchUrl) {
	formName.submit();
}
var siteId;
function languageRedirect(newLang, delim, oldLang, isCDA) {
	loc = parent.location.href.split("x" + delim + oldLang);
	if (loc.length > 1) {
		parent.location.href = loc[0] + "x" + delim + newLang + loc[1];
	} else if (parent.location.href.indexOf('?') > -1) {
		parent.location.href = parent.location.href + "&x" + delim + newLang;
	} else {
		parent.location.href = parent.location.href + "?x" + delim + newLang;
	}
	if (document.form1) {
		loc = document.form1.action.split("x" + delim + oldLang);
		document.form1.action = loc[0] + "x" + delim + newLang + loc[1];
		document.form1.submit();
	}
}
function openApp(selectBox) {
	if (selectBox.selectedIndex == 0)
		return false;
	var s = selectBox.options[selectBox.selectedIndex].value.split('*');
	if (s[0] == 'N') {
		parent.location.href=s[1];
	} else {
		if (s[1].length > 11 && s[1].substring(0, 11) == "javascript:") {
			eval(s[1].substring(11, s[1].length));
		} else {
			var win=window.open(s[1], 'Ext_Win' + selectBox.selectedIndex); win.focus();
		}
	}
}
function toggleVisibility(elt) {
	with (document.getElementById(elt).style)
		display = display == 'none' ? 'block' : 'none';
}
function populate(dbvalue) {
	for (var i = 0; i < 5; i++) {
		if (preference.noofresults.options[i].value == dbvalue) {
			preference.noofresults.options[i].selected = true;
		}
	}
}
function getCurrentDate() {
	var now = new Date();
	var months = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	var year = now.getYear();
	return ((now.getDate()<10) ? "0" : "") + now.getDate() + "-" + months[now.getMonth()] + "-" + ((year < 1000) ? year + 1900 : year);
}
function showCurrentDate() {
	document.write(getCurrrentDate());
}
var windowProfiles = new Array();
windowProfiles[0] = '';
windowProfiles[1] = 'width=800,height=600,left=50,right=50,directories=no,location=no,menubar=no,scrollbars=yes,status=no,toolbar=no,resizable=yes';
function openNewWindow(url, name, profile) {
	var w = window.open(url, name || 'Ext_Win', profile || 'menuBar=yes,HEIGHT=600,WIDTH=600,resizable,scrollbars');
	w.focus();
	return false;
}
function openWindow(){
	if (arguments.length==3) {
		try {
			executeOpenWindow(arguments[0], arguments[1], arguments[2]);
		}catch(e){}
		return false;
	}
	else if (arguments.length==2) executeOpenWindow(arguments[0], "win" + new Date().getTime());
	else executeOpenWindow(arguments[0]);
}
function executeOpenWindow(url, name, profile){
        var w;
	if (window.Ext_Win) window.Ext_Win.close();
	if (profile) {
		w = window.open(url, name || 'Ext_Win', windowProfiles[profile] || profile);
	} else {
		w = window.open(url, name || 'Ext_Win');
	}
	w.focus();
	return false;
}
function isValidRecord(record) {
	return /^-?\d+$/.test(record) && record.toString().length == 10;
}
function confirmDelete(record,confirmMessage) {
	if (confirm(confirmMessage ? confirmMessage :'Would you like to delete Record number: '+record+' ??')) {
		document.customForm.target = "_self";
		document.customForm.actionType.value = "delete";
		document.customForm.submit();
		return true;
	}
	return false;
}
function loaddata(message) {
	if (isValidRecord(document.customForm.record.value)) {
		document.customForm.target = "lookupFrame";
		document.customForm.actionType.value = "lookup";
		var oldRecordId = document.customForm.RecordID.value;
		document.customForm.RecordID.value = document.customForm.record.value;
		document.customForm.submit();
		document.customForm.RecordID.value = oldRecordId;
		return true;
	} else {
		alert(message ? message : 'Record number should contain 10 digit numbers');
		resetdata();
		document.customForm.record.focus();
		return false;
	}
}
function deletedata(validationMessage,confirmMessage) {
	var lookuprecord = document.customForm.RecordID.value;
	if (lookuprecord != "") {
		if (isValidRecord(document.customForm.record.value)) {
			confirmDelete(lookuprecord,confirmMessage);
			return false;
		}
	}
	if (isValidRecord(document.customForm.record.value)) {
		if (document.customForm.RecordID.value != "") {
			document.customForm.target = "_self";
		}
		else {
			document.customForm.target = "lookupFrame";
		}
		document.customForm.actionType.value = "delete";
		document.customForm.submit();
		return true;
	} else {
		alert(validationMessage ? validationMessage : 'Record number should contain 10 digit numbers');
		resetdata();
		document.customForm.record.focus();
		return false;
	}
}
function resetdata() {
	document.customForm.actionType.value = "";
	document.customForm.RecordID.value = "";
	document.getElementById('cufErrMsg').innerHTML = "";
	document.customForm.record.readOnly = false;
	document.customForm.reset();
	return false;
}

function gotoPage(page) {
	document.moreForm.page.value = page;
	document.moreForm.submit();
	return false;
}

function dcsMultiTrack() {
}

function doMetric(href) {
		$.ajax({
			type: "GET",
			data: { 
				url : href,
				referrer : document.referrer | ''
			},
			url: "/cda/metric/record"
		});
}

function showFooterComponent(id, value) {
	if (value && value != '') {
		$(id).append(value).show();
	}
}

function getDomain() {
	var host = document.location.hostname.split('.');
	return host.slice(host.length - 2).join('.');
}

function initMetrics() {
	//doMetric(document.location.href);
	// SDC
	try {
		var sso = decode64($.cookie('SSOCookie')).split('|');
		var cookieProps = { domain: getDomain(), path : '/' };
		$.cookie('CWS_ID', sso[0], cookieProps);

		var attrs = new $.query('?' + sso[4], '{', '}');
		$.cookie('AFFILIATION_CODE', attrs.get('catAffiliationCode'), cookieProps);
		$.cookie('AFFILIATED_ORG_CODE', attrs.get('catAffiliatedOrgCode'), cookieProps);
	} catch (e) {}

	dcsTag();

	$('a').click(function() {
		var $this = $(this);
		var href = $this.attr('href');
		var params = new $.query(href);
		var language = params.get('language');
		var country = params.get('country');

		if (language || country) {
			$.cookie(
				'cdaPreferences',
				encode64('language=' + (language || 'en') + '|country=' + (country || 'US') + '|mark=rules'),
				{ expires: 60*60*24*30, path : '/', domain : getDomain() }
			);
		}

		// if managed file || external link
			//doMetric(href);
		
		if (gDcsId && gDcsId != '') {
			if ($this.hasClass('type-F')) {
				dcsMultiTrack('DCS.dcsuri',href,'WT.ti',$this.text());
			} else if (href.match(urlRegex)) {
				dcsMultiTrack('DCS.dcsuri','/','WT.ti',$this.text(),'DCSext.externalLink','1','DCSext.url',href);
			}
			return true;
		}
	});
}

var urlRegex = new RegExp('^(https?|ftp):\/\/.*$');
$(function() {
	$('.focus').focus();

	if (getEditorStatus() == 'on') {
		initEditor();
	}
	if (getSecurityStatus() == 'on') {
		initSecurity();
	}
	
	initMetrics();

	$('select[name=language]').change(function() {
		setPreference('language', $(this).val());
		return true;
	});

	if ($.query(document.location).get('printerFriendly')) {
		$('#printerFriendly').hide();
	}
	showFooterComponent('#confidentiality', document.confidentiality);
	showFooterComponent('#contentAuthor', document.author);
	showFooterComponent('#contentOwner', document.owner);
	showFooterComponent('#contentDate', document.date.replace('CURRENT_DATE', getCurrentDate()));
});