// Flash Player Version Detection - Rev 1.5
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			if ( descArray[3] != "" ) {
				tempArrayMinor = descArray[3].split("r");
			} else {
				tempArrayMinor = descArray[4].split("r");
			}
			var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs)
{
    var str = '';
    if (isIE && isWin && !isOpera)
    {
  		str += '<object ';
  		for (var i in objAttrs)
  			str += i + '="' + objAttrs[i] + '" ';
  		for (var i in params)
  			str += '><param name="' + i + '" value="' + params[i] + '" /> ';
  		str += '></object>';
    } else {
  		str += '<embed ';
  		for (var i in embedAttrs)
  			str += i + '="' + embedAttrs[i] + '" ';
  		str += '> </embed>';
    }

    document.write(str);
}

function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();

    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}


//function to toggle flash navigation width
//default state is 0 (collapsed)
var flashNavState = 0;
var flashNavDefaultWidth = 215;
var flashNavExpandedWidth = 500;
var flashNavColumnWidth = 191;
var flashNavLightbox;


/* firefox2 for mac doesn't work correctly when combining opacity and wmode transparent */
function detectMacXFF2() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (/firefox[\/\s](\d+\.\d+)/.test(userAgent)) {
    var ffversion = new Number(RegExp.$1);
    if (ffversion < 3 && userAgent.indexOf('mac') != -1) {
      return true;
    }
  }
}

function toggleFlashWidth(columnNum){

	if(columnNum>1)
	{
		
		if (flashNavLightbox == undefined && !(detectMacXFF2()))
		{
			flashNavLightbox = document.getElementById("flashnav-curtain");
			var bodySize = Element.getDimensions(document.body);
			var lightBoxSize = {
				height: Math.max(bodySize.height, getViewportSize().height),
				width: Math.max(bodySize.width, getViewportSize().width)
			};
			Object.extend(flashNavLightbox.style, {
				display: 'block',
				height: lightBoxSize.height+'px',
				width: lightBoxSize.width+'px',
				background: '#000',
				opacity: 0.4,
				filter: 'alpha(opacity=40)',
				position: 'absolute',
				left: 0,
				top: 0
			});
		}
		else if (detectMacXFF2())
		{
			flashNavLightbox = document.getElementById("flashnav-curtain");
			flashNavLightbox.style.backgroundImage="url(/themes/newbase/i/bg_lightbox_curtain.png)";
		    flashNavLightbox.style.backgroundRepeat="repeat";

			var bodySize = Element.getDimensions(document.body);
			var lightBoxSize = {
				height: Math.max(bodySize.height, getViewportSize().height),
				width: Math.max(bodySize.width, getViewportSize().width)
			};
			Object.extend(flashNavLightbox.style, {
				display: 'block',
				height: lightBoxSize.height+'px',
				width: lightBoxSize.width+'px',
				position: 'absolute',
				left: 0,
				top: 0
			}
			);
			
		}
		
		
		else
		{
			flashNavLightbox.style.display = "block";
		}
	}
	else
	{
		if (flashNavLightbox != undefined)
		{
			flashNavLightbox.style.display = "none";	
		}
	}
	
  var newWidth;
  var flashNav = document.getElementById('flashNavigator3');
  if (!flashNav){
    flashNav = document.flashNavigator3;
  }
  newWidth = (typeof columnNum != 'undefined') ? columnNum*flashNavColumnWidth : flashNavColumnWidth;

  try {
    flashNav.width = newWidth;
    flashNav.style.width = newWidth+"px";
  }
  catch(e){
    throw e;
  }
  
  return true;
}

var xmlServed = false;
function getFlashXML()
{
	var hiddenXMLnode = document.getElementById('flashxmltextarea');
	var xml = hiddenXMLnode.value.toString();
	//alert(xml);
	xmlServed = true;
	return xml;
}

function isXmlServed()
{
	return xmlServed;
}


var jsReady = false;

function isReady()
{
	if (jsReady == false && document.getElementById('flashxmltextarea')) {
		jsReady = true;
	}
	return jsReady;
}

function pageInit()
{
	jsReady = true;
	//getFlashXML();
}


function redirectToSearchPage()
{
	var keywordFromPost = document.getElementById("topics-search").value;
	var globalSearchUrl = document.getElementById("globalSearchUrl").value;
	var keyword  = new String(keywordFromPost);
	keyword = keyword.strip().replace("+", "%2B");
	if (keyword.length == 0) return true;
	
	try
	{
		if(document.getElementById("searchAllPortals").checked == true)
    	{
        	document.forms["topics_search"].action = globalSearchUrl + "&topics-search=" + keyword;
    	}
    	else if(document.getElementById("searchAllPortals").checked == false)
    	{
        	var portalSearchUrl = document.getElementById("portalSearchUrl").value;
			document.forms["topics_search"].action = portalSearchUrl + "&topics-search=" + keyword;
    	}
	}
	catch(err)
	{
		document.forms["topics_search"].action = globalSearchUrl + "&topics-search=" + keyword;
	}


}




EventSelectors.register({
	'div#flashxml': function(el, index) {
		pageInit();
	}
}, true);
// check if Recurrence End Date field should be disabled
function checkRecurrence()
{	     
	var recur = document.getElementById('ruleid_0').checked;	
	if (recur)
	{
		//#10185  CA-SIVARAM
		document.getElementById('eventrecurrenceenddate').disabled = false;
		document.getElementById('eventrecurrenceendtime').disabled = false;
		document.getElementById('event_recurrence').style.display = 'none';
		//**CA-SIVARAM.
	}
	else
	{
		document.getElementById('event_recurrence').style.display = 'block';		
		EventSelectors.register({
			'input.rtime': function(el) {
				new kNumberBox({
					node: el,
					options: [
						'1:00 pm',
						'1:30 pm',
						'2:00 pm',
						'2:30 pm',
						'3:00 pm',
						'3:30 pm',
						'4:00 pm',
						'4:30 pm',
						'5:00 pm',
						'5:30 pm',
						'6:00 pm',
						'6:30 pm',
						'7:00 pm',
						'7:30 pm',
						'8:00 pm',
						'8:30 pm',
						'9:00 pm',
						'9:30 pm',
						'10:00 pm',
						'10:30 pm',
						'11:00 pm',
						'11:30 pm',
						'12:00 pm',
						'12:30 pm',
						'1:00 am',
						'1:30 am',
						'2:00 am',
						'2:30 am',
						'3:00 am',
						'3:30 am',
						'4:00 am',
						'4:30 am',
						'5:00 am',
						'5:30 am',
						'6:00 am',
						'6:30 am',
						'7:00 am',
						'7:30 am',
						'8:00 am',
						'8:30 am',
						'9:00 am',
						'9:30 am',
						'10:00 am',
						'10:30 am',
						'11:00 am',
						'11:30 am',
						'12:00 am',
						'12:30 am'
					],
					imgUp: '/themes/admin_default/i/up.gif',
					imgDown: '/themes/admin_default/i/down.gif',
					startValue: (new Date()).format('g:i a'), // Right now time
					sort: function(a,b) {
						var dissector = /^\s*(1?[0-9]{1}):([0-9]{2})\s*([ap]{1}m{1})\s*$/i;
						var aBits = dissector.exec(a);
						var bBits = dissector.exec(b);
						if (aBits[3] > bBits[3]) return 1;
						if (aBits[3] < bBits[3]) return -1;
						if (parseInt(aBits[1]) > parseInt(bBits[1])) return 1;
						if (parseInt(aBits[1]) < parseInt(bBits[1])) return -1;
						if (parseInt(aBits[2]) > parseInt(bBits[2])) return 1;
						if (parseInt(aBits[2]) < parseInt(bBits[2])) return -1;
						return 0;
					},
					freeText: true,
					validate: /^\s*1?[0-9]{1}:[0-9]{2}\s*([ap]{1}m{1})\s*$/i
				});
			}
		});
		//#10185  CA-SIVARAM
		if(document.getElementById('recurrenceend').selectedIndex!=0)
		{
			//#11276 CA-SIVARAM
			//[Tanuja, 2008-06-02, Task 22028 : Modified Addition of dates]
			var sindex=document.getElementById('recurrenceend').selectedIndex;			
			var startDateTime = document.getElementById('eventtimedate').value +' '+ document.getElementsByName('eventtimetime')[0].value;
			
			startDateTime = startDateTime.substring(5,7)+ '/' + startDateTime.substring(8,10) + '/' + startDateTime.substring(0,4) + ' ' + startDateTime.substring(11,19);
			
			var Today = new Date (startDateTime);
			if (Today != "Invalid Date")
			{
				var dTemp = new Date(startDateTime);	
				
				if(sindex==1)				
					dTemp.setDate(dTemp.getDate() + 1);			
				else if(sindex==2)
					dTemp.setDate(dTemp.getDate() + 7);			
				else if(sindex==3)
					dTemp.setMonth(dTemp.getMonth() + 1);			
				else if(sindex==4)
					dTemp.setFullYear(dTemp.getFullYear()+1);
				else if(sindex==5)
					dTemp.setFullYear(dTemp.getFullYear()+5);
				else if(sindex==6)
					dTemp.setFullYear(dTemp.getFullYear()+20);
	
				var correctMonth = dTemp.getMonth() + 1;
				if (correctMonth < 10) correctMonth = '0' + correctMonth;
				var correctDate = dTemp.getDate();
				if (correctDate < 10) correctDate = '0' + correctDate;
				var recurDate = dTemp.getFullYear() + "-" + correctMonth + "-" + correctDate;
				var recurTime = startDateTime.substring(11,19);
			}
			else
			{
				alert('Please enter a valid event start date');
				var recurDate = "";
				var recurTime = "";				
			}
			
			document.getElementById('eventrecurrenceenddate').value=recurDate;
			document.getElementById('eventrecurrenceendtime').value=recurTime;
			document.getElementById('eventrecurrenceenddate').disabled = true;
			document.getElementById('eventrecurrenceendtime').disabled = true;
			//#11276 ** CA-SIVARAM
		}
		else
		{
			document.getElementById('eventrecurrenceenddate').disabled = false;
			document.getElementById('eventrecurrenceendtime').disabled = false;				
		}
		//**CA-SIVARAM	
	}
}

//12122 CA-Murali
//12881 CA-Murali
function setSearchfocus(cval)
{
	document.sitesearch.q.value="";
	document.sitesearch.q.focus();		 
}
function setTopicfocus(cval)
{
	document.topics_search.topics_search.value="";
	document.topics_search.topics_search.focus();		 
}

function validateEventStartDate()
{
	var startDateTime = document.getElementById('eventtimedate').value +' '+ document.getElementsByName('eventtimetime')[0].value;			
	startDateTime = startDateTime.substring(5,7)+ '/' + startDateTime.substring(8,10) + '/' + startDateTime.substring(0,4) + ' ' + 		startDateTime.substring(11,19);	

	var eventStartDateTime = new Date (startDateTime);
	var currentDateTime = new Date();	
	if (eventStartDateTime < currentDateTime)
	{		
		var answer = confirm('The date you have selected is in the past. Do you want to save this date?') ;
		if (!answer)		
			document.getElementById('eventtimedate').value = document.getElementsByName('eventtimedate_original')[0].value;			
		else
			document.getElementsByName('eventtimedate_original')[0].value = document.getElementById('eventtimedate').value;
		
	}
}

function getCalendarDate()
{
   var now         = new Date();
   var monthnumber = now.getMonth();
   var monthday    = now.getDate();
   var year        = now.getYear();

   if(year < 2000) { year = year + 1900; }
   monthnumber = monthnumber + 1;
   if (monthnumber < 10) monthnumber = '0' + monthnumber;
   if (monthday < 10) monthday = '0' + monthday;
   var dateString = year + '-' + monthnumber + '-' + monthday;
   return dateString;
} // function getCalendarDate()

function getClockTime()
{
   var now    = new Date();
   var hour   = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   var ap = "am";
   if (hour   > 11) { ap = "pm";             }
   if (hour   > 12) { hour = hour - 12;      }
   if (hour   == 0) { hour = 12;             }
   if (hour   < 10) { hour   = "0" + hour;   }
   if (minute < 10) { minute = "0" + minute; }
   if (second < 10) { second = "0" + second; }
   var timeString = hour +
                    ':' +
                    minute +
                    ':' +
                    second +
                    " " +
                    ap;
   return timeString;
} // function getClockTime()
//**end #12122 CA-Murali

//#10185 CA-SIVARAM
//if (rCheck == 'true')
//{
//	document.getElementById('content-form-time').style.display = 'none';
//}
//**CA-SIVARAM.

var messageStack = stdClass.extend({
	//constructor
	constructor: function(el, settings) {
		this.base();
		// initialize settings
		Object.extend(this.s, {
			timer: null,
			waitTime: 10000,
			effectTime: 5000,
			closeSelector: ".close",
			autoRemove: (typeof(settings) != 'undefined' && typeof(settings.autoRemove) != 'undefined') ? settings.autoRemove : false
			/* put extensions to collections here */
		});
		
		// initialize nodes
		Object.extend(this.n, {
			el: el,
			childEl: [],
			tempContainer: document.createElement('div')
			/* put extensions to nodes here */
		});
		
		// initialize collections
		Object.extend(this.c, {
			messageFunctions: {
				success: this.successMessage.bind(this),
				error: this.errorMessage.bind(this)
			}
			/* put extensions to collections here */
		});
		var eles = this.n.el.getElementsBySelector('ul');
		
		for(var x=0; x<eles.length; x++){
			var childEl = {
				el: eles[x],
				timer: null
			}
			if (this.s.autoRemove){
			  this.startTimer(childEl);        
      }
			this._attachEvents(childEl);
		}
	},
	closeClicked: function(childEl){
		this.removeMessage(childEl);
	},
	addMessage: function(message, type){
		if(!this.n.el){
			return;
		}
		if(typeof(this.c.messageFunctions[type]) == "function"){
			var html = this.c.messageFunctions[type](message);
		}else{
			return;
		}
		
		this.n.tempContainer.innerHTML = html;
		var childEl = {
			el:this.n.tempContainer.firstChild,
			timer:null
		}
		this.n.el.appendChild(childEl.el);
		this._attachEvents(childEl);
		Element.show(this.n.el);
		if(window.Effect && this.s.autoRemove){
			Effect.BlindDown(childEl.el,{
				duration: (this.s.effectTime/1000),
				afterFinishInternal: function(effect) {
					effect.element.undoClipping();
					effect.element.style.height = '';
				}
			});
		}else{
			Element.show(childEl.el);
		}
		if (this.s.autoRemove){
		  this.startTimer(childEl);
	  }
	},
	removeMessage: function(childEl) {
		this.endTimer(childEl);
		if(window.Effect && this.s.autoRemove){
			Effect.Fade(childEl.el, {
				duration: (this.s.effectTime/1000)
			});
			/*Effect.BlindUp(childEl.el,{
				duration: (this.s.effectTime/1000),
				afterFinishInternal: function(effect) {
					effect.element.undoClipping();
					effect.element.style.height = '';
					Element.hide(effect.element);
				}
			});*/
		}else{
			Element.hide(this.n.el);
		}
	},
	startTimer: function(childEl) {
		this.endTimer(childEl);
		this.s.timer = setTimeout(this.removeMessage.bind(this, childEl), this.s.waitTime);
	},
	endTimer: function(childEl) {
		if(childEl.timer != null){
			clearTimeout(childEl.timer);
			childEl.timer = null;
		}
	},
	successMessage: function(message){
		var html = '<ul class="success">';
		html += '<li class="title">Success</li>';
		html += '<li>' + message + '</li>';
		html += '</ul>';
		return html;
	},
	errorMessage: function(message){
		var html = '<ul class="error">';
		html += '<li class="title">Error</li>';
		html += '<li>' + message + '</li>';
		html += '<li class="close">Close me</li>';
		html += '</ul>';
		return html;
	},
	_attachEvents: function(childEl) {
		var eles = document.getElementsBySelector(this.s.closeSelector, (childEl.el||this.n.el));
		for(var x=0; x<eles.length; x++){
			this.eObserve(eles[x], 'click', this.closeClicked.bind(this, childEl));
		}
	}
});
Behaviour.register({
	'#messagestack' : function(el){
		new messageStack (el);
	}
});
function makeFlashObject(SwfURL, w, h, id, flashVars, flashScale, flashVersion){
	if (flashVersion == undefined) {
		flashVersion = 7;
	}

	var SwfHTML =
		'<object \n' +
			'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" \n' +
			'codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/Swflash.cab#version=' + flashVersion + ',0,0,0" \n' +
			'id="'+id+'" \n' +
			'align="top" \n' +
			'width="'+ w +'" height="' + h + '" \n' +
		'>\n' +
			'<param name="movie" value="'+SwfURL+'" />\n' +
			(flashVars ? ('<param name="FlashVars" value="'+ flashVars +'"/>\n') : '') +
			'<param name="allowScriptAccess" value="always" />\n' +
			//'<param name="bgcolor" value="#E4EFCF" />\n' +
			'<param name="menu" value="false"/>\n' +
			'<param name="quality" value="high" />\n' +
			'<param name="wmode" value="transparent" />\n' +
			(flashScale ? ('<param name="scale" value="'+ flashScale +'"/>\n') : '') +
			'<embed \n' +
				'type="application/x-shockwave-flash" \n' +
				'pluginspage="http://www.macromedia.com/go/getflashplayer" \n' +
				'name="' + id + '" \n' +
				'align="top" \n' +
				'width="' + w + '" height="' + h + '" \n' +
				'src="'+ SwfURL +'" \n' +
				(flashVars ? ('FlashVars="' + flashVars + '" \n') : '') +
				'allowScriptAccess="always" \n' +
		//		'bgcolor="#E4EFCF" \n' +
				'menu="false" \n' +
				'quality="high" \n' +
				'wmode="transparent" \n' +
				(flashScale ? ('scale="' + flashScale + '" \n') : '') +
			'/>\n' +
		'</object>';
	document.write(SwfHTML);
}

// Flash Player Version Detection - Rev 1.5
// Detect Client Browser type
// Copyright(c) 2005-2006 Adobe Macromedia Software, LLC. All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			if ( descArray[3] != "" ) {
				tempArrayMinor = descArray[3].split("r");
			} else {
				tempArrayMinor = descArray[4].split("r");
			}
			var versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs)
{
    var str = '';
    if (isIE && isWin && !isOpera)
    {
  		str += '<object ';
  		for (var i in objAttrs)
  			str += i + '="' + objAttrs[i] + '" ';
  		for (var i in params)
  			str += '><param name="' + i + '" value="' + params[i] + '" /> ';
  		str += '></object>';
    } else {
  		str += '<embed ';
  		for (var i in embedAttrs)
  			str += i + '="' + embedAttrs[i] + '" ';
  		str += '> </embed>';
    }

    document.write(str);
}

function AC_FL_RunContent(){
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();

    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}
var aStarRatings = stdClass.extend({
	//constructor
	constructor: function(el, settings) {
		this.base();
		// initialize settings
		Object.extend(this.s, {
			//moduleName: null,
			//2007.06.19 13:11:11-AV
			moduleName: 'AddRating',
			json: {
				ver: '0.1',
				meta: {},
				data: {
					requests: []
				}
			},
			ulSelector: 'ul',
			loggedInClass: 'rateable',
			loggedOutClass: 'rated',
			starSelector: 'a',
			ratingTextSelector: '.rating_text',
			currentRatingSelector: '.current-rating',
			
			//2007.06.19 13:51:11-AV
			uniqueID: null,
			type: null
			/* put extensions to collections here */
		});
		Object.extend(this.s, settings);
		// initialize nodes
		Object.extend(this.n, {
			container: el,
			ul: null,
			stars: [],
			ratingText: null,
			currentRating: null,
			jsonNode: document.createElement('div')
			/* put extensions to nodes here */
		});
		
		// initialize collections
		Object.extend(this.c, {
			requests: []
			/* put extensions to collections here */
		});
		this.parseClasses(this.n.container, true);
		/*if(!this.n.container.vars){
			alert('You need to add the class of "vars:{moduleName:theNameOfModule}" to your container!');
			return;
		}*/
		if(this.n.container.vars && this.n.container.vars.moduleName != ""){
			this.s.moduleName = this.n.container.vars.moduleName;
		}

		this._findElements();
		
	},
	starClicked: function(e, el){
		Event.stop(e);
		this.addRequest("changeRating", {
			newRating: el.vars.stars,
			uniqueID: this.n.ul.vars.uniqueID,
			type: this.n.ul.vars.type
		});		
		this.JsonOut();
	
	},
	starClickedLoggedOut: function(e, el){
		Event.stop(e);
		
		var heading = '';
		var classes = 'kDialog2 lightboxPopup noTitle';
		var confirmDialog = new ConfirmDialog({
			'+zones': {
				heading: heading,
				content: '		<div class="text"><p>You must be logged in to add a rating. Click here to <a href="/login/?redirection=true">login</a>.</p></div>' +
				'		<form class="buttons">' +
				'			<input type="image" src="'+Config.templatePath+'i/button_close.gif" alt="Close" class="ok">' +
				'		</form>'
			},
			position: {  
				exemplarAnchor: 'top left',
				selfAnchor: 'bottom right',
				exemplar: el,
				offsetY: 0,
				offsetX: 0
			},
			classNames: [classes],
			'+innerTriggers': [
				{node: '.ok', event: 'click', action: 'onClickOK'},
				{node: '.cancel', event: 'click', action: 'onClickCancel'},
				{node: '.close', event: 'click', action: 'hide'}
			]
		});
	},
	parseClasses: function(el, parseChildren){
		var classes = String(el.className).split(" ");
		var keepClasses = [];
		for(var x=0; x<classes.length; x++){
			if(classes[x].indexOf(':') != -1){
				var matches = classes[x].match(/^(\w*):{1,2}\{(.*)\}$/);
				var ob = {};
				var vars = matches[2].split(",");
				for(var y=0; y<vars.length; y++){
					vars[y] = vars[y].split(/::?/);
					if(!vars[y][1]) vars[y][1] = '';
					ob[vars[y][0]] = vars[y][1];
				}
				el[matches[1]] = ob;
			}else{
				keepClasses.push(classes[x]);
			}
		}
		el.className = keepClasses.join(" ");
		if(parseChildren){
			var eles = el.getElementsByTagName('*');
			for(var x=0; x<eles.length; x++){
				this.parseClasses(eles[x]);
			}
		}
	},
	addRequest: function(requestName, dataObject) {
		this.c.requests.push({
			id: this.c.requests.length,
			type: requestName,
			data: dataObject
		});
	},
	//json methods
	JsonOut: function() {
		//construct the post
		this.s.json.data.requests = this.c.requests;
		//this.setMeta('columns', '');
		var data = '__json=' + this.s.moduleName + '&data=' + Object.toJSON(this.s.json);
		this.c.requests = [];
		//send out the request
		if(this.s.moduleName == ''){
			
			
			//2007.06.19 13:02:22-AV Commented this out because it is using the old output
			//var returnData = '{"meta":{},"data":{"html":"<div class=\'rating vars:{moduleName:AdminModule__rating}\'><ul class=\'rateable floatleft vars:{uniqueID=51820}\'><li class=\'current-rating\' style=\'width: ' + (this.s.json.data.requests[0].data.newRating*16) + 'px;\'> </li><li><a href=\'javascript:void(0)\' title=\'1 star\' class=\'one-star vars:{stars:1}\'>1</a></li><li><a href=\'javascript:void(0)\' title=\'2 stars\' class=\'two-stars vars:{stars:2}\'>2</a></li><li><a href=\'javascript:void(0)\' title=\'3 stars\' class=\'three-stars vars:{stars:3}\'>3</a></li><li><a href=\'javascript:void(0)\' title=\'4 stars\' class=\'four-stars vars:{stars:4}\'>4</a></li><li><a href=\'javascript:void(0)\' title=\'5 stars\' class=\'five-stars vars:{stars:5}\'>5</a></li></ul><span class=\'rating_text\'>' + this.s.json.data.requests[0].data.newRating + '/5</span></div>"},"responses":[{"id":1,"type":"changeRating","data":{"success":"true"}}]}';
			
			var returnData = '{"meta":{},"data":{"html":"<div class=\'rating vars:{moduleName:AdminModule__rating}\'><ul class=\'rateable floatleft vars:{uniqueID=51820}\'><li class=\'current-rating\' style=\'width: ' + (this.s.json.data.requests[0].data.newRating*15) + 'px;\'> </li><li><a href=\'javascript:void(0)\' title=\'1 star\' class=\'one-star vars:{stars:1}\'>1</a></li><li><a href=\'javascript:void(0)\' title=\'2 stars\' class=\'two-stars vars:{stars:2}\'>2</a></li><li><a href=\'javascript:void(0)\' title=\'3 stars\' class=\'three-stars vars:{stars:3}\'>3</a></li><li><a href=\'javascript:void(0)\' title=\'4 stars\' class=\'four-stars vars:{stars:4}\'>4</a></li><li><a href=\'javascript:void(0)\' title=\'5 stars\' class=\'five-stars vars:{stars:5}\'>5</a></li></ul><span class=\'rating_text\'>' + this.s.json.data.requests[0].data.newRating + '/5</span></div>"},"responses":[{"id":1,"type":"changeRating","data":{"success":"true"}}]}';
			

			this.JsonIn({responseText:returnData});
		}else{
			var myAjax = new Ajax.Request(window.location,
			{
				method: 'post',
				parameters: data,
				onSuccess: this.JsonIn.bind(this)
			});		
		}
	},
	
	JsonIn: function(t) {
		//alert(t.responseText);
		var result = t.responseText.evalJSON();
		(result.responses.length).times(function(i) {
			if(result.responses[i].type == 'changeRating'){				
				this.n.jsonNode.innerHTML = result.data.html;
				
				// 2007.10.12, Issue Id: 12809, If you need to hide ratings text, comment this
				this.n.ratingText.innerHTML = document.getElementsBySelector(this.s.ratingTextSelector, this.n.jsonNode)[0].innerHTML;

				this.n.currentRating.style.width = document.getElementsBySelector(this.s.currentRatingSelector, this.n.jsonNode)[0].style.width;
				this._startScripts(this.n.container);
				var stars = document.getElementsBySelector(this.s.starSelector, this.n.ul);				
				
				for(var x=0; x<stars.length; x++){
					stars[x].blur();
				}
			}
		}.bind(this));
	},
	_startScripts: function(el) {
		//empty for now...
	},
	_findElements: function(){

		this.n.ul = document.getElementsBySelector(this.s.ulSelector, this.n.container)[0];
		if(!this.n.ul){
			return;
		}
		this.n.currentRating = document.getElementsBySelector(this.s.currentRatingSelector, this.n.container)[0];
		var stars = document.getElementsBySelector(this.s.starSelector, this.n.ul);

		this.n.stars = [];
		
		for(var x=0; x<stars.length; x++){
			if (Element.hasClassName(this.n.ul, this.s.loggedOutClass)) {
				// logged out
				this.eObserve(stars[x], 'click', this.starClickedLoggedOut.bindAsEventListener(this, stars[x]));
			}
			else {
				// logged in
				this.eObserve(stars[x], 'click', this.starClicked.bindAsEventListener(this, stars[x]));
			}
			this.n.stars.push(stars[x]);
		}
		this.n.ratingText = document.getElementsBySelector(this.s.ratingTextSelector, this.n.container)[0];
	}
});
EventSelectors.register({
	'.rating': function(el, index) {
		new aStarRatings(el, {
			moduleName: 'AddRating'
		});
	}
}, true);var Favorites = stdClass.extend({
	//constructor
	constructor: function(el, settings) {
		this.base();
		// initialize settings
		Object.extend(this.s, {
			moduleName: 'AddBookmark',
			json: {
				ver: '0.1',
				meta: {},
				data: {
					requests: []
				}
			},
			uniqueID: null,
			type: null
			/* put extensions to collections here */
		});
		
		// initialize nodes
		Object.extend(this.n, {
			el: el,
			link: null,
			links: null,
			linkSpans: null
			/* put extensions to nodes here */
		});
		
		// initialize collections
		Object.extend(this.c, {
			requests: []
			/* put extensions to collections here */
		});
		
		this._addEvents();
		
		// Get query params
		var args = this.n.el.href.substr(this.n.el.href.indexOf('?')+1);
		// Split using the &
		if (args != "#")
		{
			args = args.split("&");
			
			for(var x=0; x<args.length; x++){
				kv = args[x].split("=");
				if (kv[0] == "type")
					this.s.type = kv[1];
				
				if (kv[0] == "id")
					this.s.uniqueID = kv[1]
			}
		}
	},
	
	linkOnClick: function(e){		
		Event.stop(e);
		if(Element.hasClassName(this.n.el, 'bookmark_add')){
			this.addRequest("addFavorites", {
				uniqueID: this.s.uniqueID,
				type: this.s.type
			});
			this.JsonOut();
		}else if(Element.hasClassName(this.n.el, 'bookmark_remove')){
			this.addRequest("removeFavorites", {
				uniqueID: this.s.uniqueID,
				type: this.s.type
			});
			this.JsonOut();
		}
	},
	
	addRequest: function(requestName, dataObject) {
		this.c.requests.push({
			id: this.c.requests.length,
			type: requestName,
			data: dataObject
		});
	},
	
	//json methods
	JsonOut: function() {
		//construct the post
		this.s.json.data.requests = this.c.requests;
		var data = '__json=' + this.s.moduleName + '&data=' + Object.toJSON(this.s.json);
		this.c.requests = [];
		var myAjax = new Ajax.Request(window.location,
		{
			method: 'post',
			parameters: data,
			onSuccess: this.JsonIn.bind(this)
		});
	},
	
	JsonIn: function(t) {
		var result = t.responseText.evalJSON();
		(result.responses.length).times(function(i) {
			if(result.responses[i].type == 'addFavorites'){
				var newLink = result.data.html.toDOMNodes()[0];
				DOM.replace(this.n.el, newLink);
				this.n.el = newLink;
			}else if(result.responses[i].type == 'showMessage'){
				new kDialog2({
					'+zones': {
						heading: result.responses[i].data.headline,
						text: result.responses[i].data.html
					},
					position: {  
						exemplarAnchor: 'bottom right',
						selfAnchor: 'top right',
						exemplar: this.n.el,
						offsetY: 0,
						offsetX: 0
					},
					groupId: 'showMessage',
					groupLimit: 1,
					startHidden: false
				});
			}
		}.bind(this));
	},
	
	_addEvents: function() {
		// Bind the a element to listen for the click event
		this.eObserve(this.n.el, 'click', this.linkOnClick.bindAsEventListener(this));
	}
});

EventSelectors.register({
	'.bookmark_add': function(el, index) {
		new Favorites(el);
	}
}, true);
/**
 * rSelect
 *
 * @version 1.6
 * @author Ryan Brill
 *
 * @requires prototype.js
 * @requires prototype_ss.js
 * @requires DOM.js
 * @requires EventSelectors.js
 **/

var rSelectClass = Class.create();
rSelectClass.prototype = {

	//Constructor
	initialize: function(el, s) {
		this.items = [];									// array of list items
		this.el = el;										// <select class="rSelect">
		this.label = document.createElement('div');			// the label of our dropdown
		this.labelText = document.createElement('span');	// the text node inside our label
		this.container = document.createElement('div');		// the container element
		this.ulcontainer = document.createElement('div');	// Generated UL mirroring the <select> box
		this.imask = document.createElement('iframe');		// iframe fix for IE
		this.actualCols = 0;								// Actual number of columns that get created
		this.ulInit = false;								// Keeps track of if ul is initialized
		this.s = {
			fixedWidth: true,					// set the width to the size of the original <select> box
			className: 'rSelectBox',			// Class name to apply to the <div> tag
			selectedClass: 'selected',			// Class name for the seleted item in the select box
			hoverClass: 'hover',				// Class name for the hover of the items in the list
			toggleClass: 'toggle',				// Class name for the toggle all items in the list
			isMultiSelect: false,				// whether or not this is a multiple select box. It will look for the attribute multiple="multiple" on the select box
			defaultLabel: 'No Values Selected',	// Default value for when no options are selected in a multi-select box
			pxPerChar: 9,						// Number of pixels to allow for each character in the label
			maxHeight: 300,						// Maximum height of the dropdown for multi selects
			maxCols: 1,							// Maximum number of columns - will be fewer colums if fewer fit in maxHeight
			pxPerRow: 22,						// Number of pixels to allow for each row
			processed: 'rSelectReplaced',        // Flag to tell whether a select has been processed yet
			width: Element.getDimensions(this.el).width
			
		};
		for (var key in s) {
			this.s[key] = s[key];
		}
		
		if(this.el.hasClassName(this.s.processed)) {
			return 0;
		}
		Element.addClassName(this.el, this.s.processed);
		
		var multi = (this.el.attributes['multiple']) ? this.el.attributes['multiple'].value : this.el.getAttribute('multiple');
		if (multi && (multi.toLowerCase() == "multiple" || multi.toLowerCase() == "true")){
			this.s.isMultiSelect = true;
		}
		
		Element.addClassName(this.container, this.s.className);
		if(this.el.className != ''){
			Element.addClassName(this.container, this.el.className);
		}
		
		/* Event observers */
		Event.observe(this.label, 'click', this.clickLabel.bind(this));
		
		this.createContainer();
		Element.hide(this.el);
	},
	//Methods
	findElements: function() {
		var alleles = this.el.childNodes;
		var eles = new Array();
		var totalEles = 0;
		var makeSelected = false;
		var currentRow = 0;
		var ul = document.createElement('ul');
		
		// add top level <option> and <optgroups> to eles, and count all rows (totalEles) that will get outputted
		for (var i=0; i<alleles.length; i++) {
			switch (String(alleles[i].tagName).toLowerCase()) {
				case 'optgroup':
					eles.push(alleles[i]);
					var opts = alleles[i].getElementsByTagName('option');
					if (alleles[i].label) {
						totalEles++;
					}
					totalEles = totalEles + opts.length;
				case 'option':
					if (alleles[i].childNodes.length == 1) {
						eles.push(alleles[i]);
						totalEles++;
					}
			}
		}
		
		// Check how many rows we are expecting
		var expectedCols = (Math.ceil(totalEles * this.s.pxPerRow / this.s.maxHeight) > this.s.maxCols ? this.s.maxCols : Math.ceil(totalEles * this.s.pxPerRow / this.s.maxHeight));
		
		for (var i=0; i<eles.length; i++) {
			
			// Close our current UL and start a new one
			if (currentRow > Math.ceil(totalEles / expectedCols) - 1) {
				Element.addClassName(ul, 'col');
				this.ulcontainer.appendChild(ul);
				ul = document.createElement('ul');
				currentRow = 0;
				this.actualCols++;
			}
						
			// Fix disabled options in IE
			if(eles[i].selected && eles[i].disabled){
				makeSelected = true;
			}
			if(makeSelected && !eles[i].disabled && String(eles[i].tagName).toLowerCase() == "option"){
				makeSelected = false;
				eles[i].selected = true;
			}
			
			switch (String(eles[i].tagName).toLowerCase()) {
				case 'optgroup':
					var li = document.createElement('li');
					var optgroupUl = document.createElement('ul');
					
					if (eles[i].label) {
						Element.addClassName(li, 'optlabel');
						if (eles[i].disabled) {
							Element.addClassName(li, 'disabled');
							Element.addClassName(optgroupUl, 'disabled');
						}
						li.innerHTML = eles[i].label;
						ul.appendChild(li);
						currentRow++;
					}
					
					var opts = eles[i].getElementsByTagName('option');
					currentRow = currentRow + opts.length;

					for (var j=0; j<opts.length; j++) {
						// Fix disabled options in IE
						if(opts[j].selected && (eles[i].disabled || opts[j].disabled)){
							makeSelected = true;
						}
						if(makeSelected && !eles[i].disabled && !opts[j].disabled){
							makeSelected = false;
							opts[j].selected = true;
						}
						
						this.createElement(opts[j], eles[i].disabled, optgroupUl);
					}
					ul.appendChild(optgroupUl);
					break;
				case 'option':
					if (eles[i].childNodes.length == 1) {
						this.createElement(eles[i], eles[i].disabled, ul);
						currentRow++;
					}
					break;
			}
		}
		this.actualCols++;
		if (this.actualCols > 1) {
			Element.addClassName(ul, 'col');
		}
		this.ulcontainer.appendChild(ul);
		
	},
	createElement: function(el, state, parent) {
		// Fix disabled options in IE
		var elSelected = (el.selected && (!el.disabled && (!el.parentNode || !el.parentNode.disabled))) ? true : false;
		
		var itemvar = {};
		itemvar.value = el.value;
		itemvar.el = el;
		itemvar.selected = elSelected;
		
		itemvar.disabled = (el.disabled || el.parentNode.disabled) ? true : false;
		itemvar.text = el.text;
		itemvar.li = document.createElement('li');
		if(itemvar.el.className != ''){
			Element.addClassName(itemvar.li, itemvar.el.className);
		}
		if (state == true) {
			itemvar.li.innerHTML = el.text;
			Element.addClassName(itemvar.li, 'disabled');
		}
		else {
			itemvar.a = document.createElement('a');
			itemvar.a.href = 'javascript:void(0);';
			itemvar.text = el.text;
			if(this.s.isMultiSelect){
				itemvar.a.innerHTML = '<input type="checkbox" ' + ((itemvar.selected)? ' checked="checked"' : '' ) + '> ' + el.text;
			}else{
				itemvar.a.innerHTML = el.text;
			}
			itemvar.li.appendChild(itemvar.a);
		}
		parent.appendChild(itemvar.li);
		this.items.push(itemvar);
		if (elSelected) { // create our label element
			this.setLabel(el.text);
		}
	},
	
	createContainer: function(){
		Element.addClassName(this.label, 'label');
		
		var icon = document.createElement('div');
		Element.addClassName(icon, 'icon');
		icon.appendChild(this.labelText);
		this.label.appendChild(icon);
		this.container.appendChild(this.label);
		
		// container width
		if (this.s.fixedWidth == true && this.s.width) {
			this.container.style.width = this.s.width + 'px'; // set the width of the original <select>
		}
		
		DOM.insertAfter(this.container, this.el);
		
		var text = [];
		var opts = this.el.getElementsByTagName('option');
		for(var i=0, len=opts.length; i<len; i++)
			if(opts[i].selected)
				text.push(opts[i].text);
		text = text.join(', ');
		if(text == '')
			text = this.s.defaultLabel;
		this.setLabel(text);
	},
	
	createUL: function() {
		
		Element.addClassName(this.ulcontainer, 'ulcontainer');
		this.container.appendChild(this.ulcontainer);
		this.ulcontainer.show();
		
		var width = this.container.offsetWidth;
		var uldims = Element.getDimensions(this.ulcontainer);
		
		var uls = this.ulcontainer.childNodes;
		var ulswidth = 0;
		for (i=0; i<uls.length; i++) {
			if (uls[i].tagName.toLowerCase() == 'ul') {
				ulswidth += uls[i].offsetWidth;
			}
		}
		
		// dropdown width
		if (ulswidth > width) {
			// options longer than select
			this.ulcontainer.style.width = ulswidth + ((!isNaN(this.s.maxHeight) && uldims.height > this.s.maxHeight) ? 17 : 0) + 'px';
			//alert ('2');
		}
		else if (this.s.fixedWidth == true) {
			// set the width of the original <select>
			this.ulcontainer.style.width = width + 'px';
			this.ulcontainer.style.width = width + (width - this.ulcontainer.offsetWidth) + 'px';
			//alert ('3');
		}
		
		if (!isNaN(this.s.maxHeight) && uldims.height > this.s.maxHeight) {
			this.ulcontainer.style.height = this.s.maxHeight + 'px';
			this.ulcontainer.style.overflow = 'auto';
		}
		
		var left = String(Position.cumulativeOffset(this.ulcontainer));
		left = Number(left.substring(0, left.indexOf(',')));
		left += Element.getDimensions(this.ulcontainer).width;
		if(Element.getDimensions(document.getElementsByTagName('body')[0]).width < left){
			this.ulcontainer.style.right = "0px";
		}
		
		var uldims = Element.getDimensions(this.ulcontainer);
		
		if (document.all) { 
			/* create an iFrame to fix IE bug */
			this.imask.scrolling = 'no';
			this.imask.frameborder = '0';
			this.imask.style.display = 'none';
			this.imask.style.position = 'absolute';
			this.imask.style.marginTop = '-1';
			this.imask.style.zIndex = 10;
			this.ulcontainer.style.zIndex = 11;
			this.imask.style.width = uldims.width + 'px';
			this.imask.style.height = uldims.height + 'px';
			this.container.appendChild(this.imask);
			this.imask.style.top = this.ulcontainer.style.top;
			if(Element.getDimensions(document.getElementsByTagName('body')[0]).width < left){
				this.imask.style.right = "0px";
			}
		}
		
		this.ulInit = true;
	},	
	clickLabel: function(e) {
		if(!this.ulInit){	//ul not initialized?
			this.findElements();
			this.createUL();
			this.initializeULEvents();
			this.show();
		}
		else
			this.toggle();
		for (var i=0; i<this.items.length; i++) {
			Element.removeClassName(this.items[i].li, this.s.hoverClass);
			Element.removeClassName(this.items[i].li, this.s.selectedClass);
			if (this.items[i].selected == true) {
				Element.addClassName(this.items[i].li, this.s.hoverClass);
				Element.addClassName(this.items[i].li, this.s.selectedClass);
			}
		}
		if (typeof(this.el.onclick) == 'function') {
			this.el.onclick();
		}
		if(!Element.visible(this.ulcontainer)){
			this.hide();
			if (typeof(this.el.onclose) == 'function') {
				this.el.onclose();
			}
			if (typeof(Event.fire) == 'function') {
				Event.fire(this.el, "close");
			}
		}
	},
	toggle: function() {
		if(Element.visible(this.ulcontainer)){
			this.hide();
		}else{
			this.show();
		}
	},
	hide: function() {
		Element.hide(this.ulcontainer);
		if (document.all) { 
			Element.hide(this.imask);
		}
	},
	show: function() {
		Element.show(this.ulcontainer);
		if (document.all) { 
			Element.show(this.imask);
		}
		var left = String(Position.cumulativeOffset(this.ulcontainer));
		left = Number(left.substring(0, left.indexOf(',')));
		left += Element.getDimensions(this.ulcontainer).width;
		if(Element.getDimensions(document.getElementsByTagName('body')[0]).width < left){
			this.ulcontainer.style.right = "0px";
		}
	},
	checkItem: function(itemvar, index){
		itemvar.selected = true;
		itemvar.el.selected = true;
		if(itemvar.li.getElementsByTagName('input')[0]){
			itemvar.li.getElementsByTagName('input')[0].checked = true;
		}
		Element.addClassName(itemvar.li, this.s.selectedClass);
		if(index){
			this.el.selectedIndex = index;
		}
	},
	uncheckItem: function(itemvar){
		itemvar.selected = false;
		itemvar.el.selected = false;
		if(itemvar.li.getElementsByTagName('input')[0]){
			itemvar.li.getElementsByTagName('input')[0].checked = false;
		}
		Element.removeClassName(itemvar.li, this.s.selectedClass);
	},
	onClick: function(e) {
		var ele = Event.element(e);
		while(ele && ele != this.container){
			if(ele.tagName.toLowerCase() == 'a'){
				break;
			}
			ele = ele.parentNode;
		}
		if(ele.tagName.toLowerCase() != 'a'){
			return;
		}
		if(this.s.isMultiSelect){
			for (var i=0; i<this.items.length; i++) {
				if (this.items[i].a == ele) {
					if(this.items[i].selected == true){
						this.uncheckItem(this.items[i]);
					}else{
						this.checkItem(this.items[i]);
					}
					break;
				}
			}
		}else{
			for (var i=0; i<this.items.length; i++) {
				if (this.items[i].a == ele) {
					this.checkItem(this.items[i], i);
				} else {
					this.uncheckItem(this.items[i]);
				}
			}
			this.hide();
		}
		var allchecked = true;
		for(var x=0; x<this.items.length; x++){
			if(this.items[x].a == ele){
				var itemvar = this.items[x];
			}
			if(this.items[x].selected == false && !Element.hasClassName(this.items[x].li, this.s.toggleClass) && !this.items[x].disabled){
				allchecked = false;
			}
		}
		if(Element.hasClassName(itemvar.li, this.s.toggleClass)){
			for(var x=0; x<this.items.length; x++){
				if(allchecked){
					//uncheck all
					this.uncheckItem(this.items[x]);
				}else{
					//check all
					if (!this.items[x].disabled) {
						this.checkItem(this.items[x]);
					}
				}
			}
		}else if(allchecked){
			for(var x=0; x<this.items.length; x++){
				if(Element.hasClassName(this.items[x].li, this.s.toggleClass)){
					//alert ('ran');
					this.checkItem(this.items[x]);
				}
			}
		}else{
			for(var x=0; x<this.items.length; x++){
				if(Element.hasClassName(this.items[x].li, this.s.toggleClass)){
					this.uncheckItem(this.items[x]);
				}
			}
		}
		this.updateLabel();
		if (typeof(this.el.onclick) == 'function') {
			this.el.onclick();
		}
		if (typeof(this.el.onchange) == 'function') {
			this.el.onchange();
		}
		if (typeof(Event.fire) == 'function') {
			Event.fire(this.el, "change");
		}
	},
	onMouseOver: function (e) {
		var ele = Event.element(e);
		if(ele.tagName.toLowerCase() != 'a' && ele.tagName.toLowerCase() != 'li'){
			return;
		}
		for (var i=0; i<this.items.length; i++) {
			Element.removeClassName(this.items[i].li, this.s.hoverClass);
			if (this.items[i].a == ele) {
				Element.addClassName(this.items[i].li, this.s.hoverClass);
			}
		}
	},
	initializeULEvents: function() {
		Event.observe(this.ulcontainer, 'click', this.onClick.bind(this));
		Event.observe(this.ulcontainer, 'mouseover', this.onMouseOver.bind(this));
		Event.observe(document, 'click', this.onBlur.bind(this), false);
		Event.observe(window, 'blur', this.onBlur.bind(this), false);
	},
	onBlur: function (e) {
		var el = Event.element(e);
		var found = false;
		do {
			if (el == null || el == window || el == document.body) break;
			if(el == this.container){
				found = true;
				break;
			}
		} while(el = el.parentNode);
		if(!found && Element.visible(this.ulcontainer)){
			this.hide();
			if (typeof(this.el.onclose) == 'function') {
				this.el.onclose();
			}
			if (typeof(Event.fire) == 'function') {
				Event.fire(this.el, "close");
			}
		}
	},
	updateLabel: function() {
		var selectedItems = [];
		for(var x=0; x<this.items.length; x++){
			if(this.items[x].selected && !Element.hasClassName(this.items[x].li, this.s.toggleClass)){
				selectedItems.push(this.items[x].text);
			}
		}
		text = selectedItems.join(', ');
		if(text == ''){
			text = this.s.defaultLabel;
		}
		this.setLabel(text);
	},
	setLabel: function(text) {
		//shorten text if necessary
		var shorttext = text.substring(0, Math.round(this.s.width/this.s.pxPerChar));
		if(shorttext != text)
			text = shorttext.substring(0, shorttext.length-2) + '\u2026'; // truncate text and replace last character with ellipsis
			
		//this.labelText.innerHTML = text; // This brakes in IE
		var text = document.createTextNode(text);
		this.labelText.innerHTML = '';
		this.labelText.insertBefore(text, this.labelText.firstChild);
	}
}

//instantiate and use the object
EventSelectors.register({
	'select.rSelect' : function(el) {
		new rSelectClass (el, {
		});
	},
	'select.rSelectSmall' : function(el) {
		new rSelectClass (el, {
			fixedWidth: false,
			className: 'rSelectBoxSmall'
		});
	},
	'select.rSelectNetwork' : function(el) {
		new rSelectClass (el, {
			defaultLabel: 'My Network'
		});
	}
}, true);
/*
* by Nandhin Coutinho on 10/1/2008
* Modified by Ashok Naidu May 16 2008 for archive
*/
var deleteContent = stdClass.extend({
	//constructor
	constructor: function(el, settings, archived, shared, customdomain)
	{
		//get GroupId and contentId from URL
		var href = window.location.href;
		var newhref = href.split("?");
		var href_array = newhref[0].split("/");
		//Find The Archiveid Value If its set
		if(archived)
		{
			var hrefquery_array = newhref[1].split("&");
			//Find the "Archiveid="  from the array
			archiveidflag = false;
			for (i=0;i<hrefquery_array.length;i++)
			{
				if(hrefquery_array[i].indexOf("archiveid=") > -1)
				{
					archiveidflag = true;
					archiveidarry=hrefquery_array[i].split("=");
					archiveid = archiveidarry[1];
					break;
				}
			}
			if(!archiveidflag)
			archiveid = 0;
		}
		else
		archiveid = 0;
		
		topic = '';
		if (newhref !=null && newhref.length > 1)
		{
			var hrefquery_array = newhref[1].split("&");
			for (i=0;i<hrefquery_array.length;i++)
			{
				if(hrefquery_array[i].indexOf("topic=") > -1)
				{					
					refArray=hrefquery_array[i].split("=");
					topic = refArray[1];
					break;
				}
			}
		}
		var contentId = href_array[href_array.length -2];
		var groupId = href_array[href_array.length -3];
		if(customdomain)
			var portalshortname = ''
		else
			var portalshortname = href_array[href_array.length-5]
		var section	= href_array[href_array.length-4]

		this.base();
		
		if(/*!groupId ||  !portalshortname ||*/ !contentId || !settings.module)
			return ;
			
		// initialize settings
		Object.extend(this.s, {
			json: {
				ver: '0.1',
				meta: {},
				data: {
					requests: []
				}
			},
					  
			GroupId: groupId,
			ContentId: contentId,
			module:	settings.module,
			archiveid: archiveid,
			archiveflag: archived,
			sharedflag: shared,
			PortalshortName: portalshortname,
			Section: section,
			Topic: topic,
			CustomDomain: customdomain,
			entryType: (settings.type) ? settings.type : 'content'
			
		});
		
		// initialize nodes
		Object.extend(this.n, {
			el: el
		});

		// initialize collections
		Object.extend(this.c, {
			/* put extensions to collections here */
			requests: []			
		});
					
		this._addEvents();
	},
	
	
	buttonOnClick: function(e) {
		Event.stop(e);
		
		if(this.s.sharedflag || this.s.archiveflag || !this.s.entryType) {
			this.showDeleteConfirmDialog();
		}else {
			this.sendCheckEditRequest();
		}
	},
	
	showDeleteConfirmDialog: function() {
		if (this.s.sharedflag)
			windowhref = '?__module='+ this.s.module + '&contentsection='+this.s.Section+'&action=unlink&groupName=' + this.s.PortalshortName + '&contentId=' + this.s.ContentId + '&topic=' + this.s.Topic;
		else if(this.s.archiveflag)
			windowhref = '?__module='+ this.s.module + '&contentsection='+this.s.Section+'&action=delete&archiveid='+this.s.archiveid+'&groupName=' + this.s.PortalshortName + '&contentId=' + this.s.ContentId + '&topic=' + this.s.Topic;
		else
			windowhref = '?__module='+ this.s.module + '&contentsection='+this.s.Section+'&action=delete&groupName=' + this.s.PortalshortName + '&contentId=' + this.s.ContentId + '&topic=' + this.s.Topic;
		
		windowhref = windowhref + "&customDomain="+ this.s.CustomDomain
		var confirmDialog = new ConfirmDialog({
			classNames: ['kDialog2 lightboxPopup'],
			onClickOK: function() {
				window.location.href = windowhref;
				return true;
			}.bind(this),
			startHidden: true
		});
		if(this.s.sharedflag)
			confirmDialog.setText('Are you sure you wish to remove the shared content?');
		else if(this.s.archiveflag)
			confirmDialog.setText('Are you sure you wish to delete this archived content?');
		else
			confirmDialog.setText('Deleting this content will also delete the archived data.<br>Are you sure you want to delete this entry and all of its archive?');
		confirmDialog.show();

	},
	
	addRequest: function(requestName, dataObject) {
		this.c.requests.push({
			id: this.c.requests.length,
			type: requestName,
			data: dataObject
		});
	},	

	sendCheckEditRequest : function () {
		// check if content being edited
		this.addRequest("checkBeingEdited", {
			uniqueID: this.s.ContentId,
			entryType: this.s.entryType
		});		
		this.JsonOut();
	},

	_alertBeingEdited: function (message) {
		
		var beingEditedAlert = new ConfirmDialog({
				'+zones': {
					heading: 'Item Being Edited',
					content: '<div class="text"> Oops! This item is being edited.</div>' +
					'		<form class="buttons">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_ok.gif" alt="Ok" class="ok">' +
					'		</form>'
				},
				classNames: ['kDialog2 lightboxPopup']
			});
	},
	
	_addEvents: function() {
		this.eObserve(this.n.el, 'click', this.buttonOnClick.bindAsEventListener(this));
	},

	/* --------------------- JSON Methods ---------------------------------*/
	JsonOut: function() {
		//construct the post
		this.s.json.data.requests = this.c.requests;
		//this.setMeta('columns', '');
		var data = '__json=ManageEditCollision' + '&data=' + Object.toJSON(this.s.json);
		this.c.requests = [];
		
		//send out the request
		var myAjax = new Ajax.Request(window.location,
		{
			method: 'post',
			parameters: data,
			onSuccess: this.JsonIn.bind(this)
		});
		
	},
	
	JsonIn: function(t) {
		//alert(t.responseText);
		var result = t.responseText.evalJSON();
		(result.responses.length).times(function(i) {
			if(result.responses[i].type == 'canEdit'){
				this.showDeleteConfirmDialog();
			}
			else if(result.responses[i].type == 'beingEdited'){
				this._alertBeingEdited();
			}else{
				this.showDeleteConfirmDialog();
			}

		}.bind(this));
	}
	
	
});
/*
* by Nandhin Coutinho on 10/1/2008
* Modified by Ashok Naidu May 19 2008 
*/
EventSelectors.register({
	'.deleteEntry': function(el, index) {
		new deleteContent(el,{
			module: 'BlogDetail',
			type: 'content'
		},false,false,false);
	},
	'.deleteEntryDomain': function(el, index) {
		new deleteContent(el,{
			module: 'BlogDetail',
			type: 'content'			
		},false,false,true);
	},
	'.deleteArchivedEntry': function(el, index) {
		new deleteContent(el,{
			module: 'BlogDetail',
			type: 'content'			
		},true,false,false);
	},
	'.deleteArchivedEntryDomain': function(el, index) {
		new deleteContent(el,{
			module: 'ArticleDetail',
			type: 'content'			
		},true,false,true);
	},
	'.unlinkEntry': function(el, index) {
		new deleteContent(el,{
			module: 'BlogDetail',
			type: 'content'			
		},false,true,false);
	},
	'.unlinkEntryDomain': function(el, index) {
		new deleteContent(el,{
			module: 'BlogDetail',
			type: 'content'			
		},false,true,true);
	}
}, true);
/*
* By Ashok Naidu on 16 May 2008
* RollBack Version
*/
var deleteRollBack = stdClass.extend({
	//constructor
	constructor: function(el, settings, archived)
	{
		//get GroupId and contentId from URL
		var href = window.location.href;
		var newhref = href.split("?");
		var href_array = newhref[0].split("/");
		//Find The Archiveid Value If its set
		if(archived)
		{
			var hrefquery_array = newhref[1].split("&");
			//Find the "Archiveid="  from the array
			archiveidflag = false;
			for (i=0;i<hrefquery_array.length;i++)
			{
				if(hrefquery_array[i].indexOf("archiveid=") > -1)
				{
					archiveidflag = true;
					archiveidarry=hrefquery_array[i].split("=");
					archiveid = archiveidarry[1];
					break;
				}
			}
			if(!archiveidflag)
			archiveid = 0;
		}
		else
		archiveid = 0;
		
		var contentId = href_array[href_array.length -2];
		var groupId = href_array[href_array.length -3];
		var portalshortname = href_array[href_array.length-5]
		var section	= href_array[href_array.length-4]
		
		this.base();
		
		if(/*!groupId || */!contentId || !settings.module)
			return ;
			
		// initialize settings
		Object.extend(this.s, {
			json: {
				ver: '0.1',
				meta: {},
				data: {
					requests: []
				}
			},
					  
			GroupId: groupId,
			ContentId: contentId,
			module:	settings.module,
			archiveid: archiveid,
			archiveflag: archived,
			Section: section,
			PortalshortName: portalshortname,
			entryType : 'content'
		});
		
		// initialize nodes
		Object.extend(this.n, {
			el: el
		});

		// initialize collections
		Object.extend(this.c, {
			/* put extensions to collections here */
			requests: []			
		});
					
		this._addEvents();
	},
	
	
	buttonOnClick: function(e) {
		Event.stop(e);
		
		if(!this.s.entryType) {
			this.showConfirmDialog();
		}else {
			this.sendCheckEditRequest();
		}
		
	},
	
	showConfirmDialog:  function() {
		windowhref = '?__module='+ this.s.module + '&action=rollback&archiveid='+this.s.archiveid+'&contentsection='+ this.s.Section+'&groupName='+ this.s.PortalshortName +'&rollback=yes&contentId=' + this.s.ContentId;
	var confirmDialog = new ConfirmDialog({
		classNames: ['kDialog2 lightboxPopup'],
		onClickOK: function() {
			window.location.href = windowhref;
			return true;
		}.bind(this),
		startHidden: true
		});
		confirmDialog.setText('Are you sure you want to rollback to this version?');
		confirmDialog.show();
		
	},
	
	_addEvents: function() {
		this.eObserve(this.n.el, 'click', this.buttonOnClick.bindAsEventListener(this));
	},

	addRequest: function(requestName, dataObject) {
		this.c.requests.push({
			id: this.c.requests.length,
			type: requestName,
			data: dataObject
		});
	},	

	sendCheckEditRequest : function () {
		// check if content being edited
		this.addRequest("checkBeingEdited", {
			uniqueID: this.s.ContentId,
			entryType: this.s.entryType
		});		
		this.JsonOut();
	},

	_alertBeingEdited: function (message) {
		
		var beingEditedAlert = new ConfirmDialog({
				'+zones': {
					heading: 'Item Being Edited',
					content: '<div class="text"> Oops! This item is being edited.</div>' +
					'		<form class="buttons">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_ok.gif" alt="Ok" class="ok">' +
					'		</form>'
				},
				classNames: ['kDialog2 lightboxPopup']
			});
	},
	/* --------------------- JSON Methods ---------------------------------*/
	JsonOut: function() {
		//construct the post
		this.s.json.data.requests = this.c.requests;
		//this.setMeta('columns', '');
		var data = '__json=ManageEditCollision' + '&data=' + Object.toJSON(this.s.json);
		this.c.requests = [];
		
		//send out the request
		var myAjax = new Ajax.Request(window.location,
		{
			method: 'post',
			parameters: data,
			onSuccess: this.JsonIn.bind(this)
		});
		
	},
	
	JsonIn: function(t) {
		//alert(t.responseText);
		var result = t.responseText.evalJSON();
		(result.responses.length).times(function(i) {
			if(result.responses[i].type == 'canEdit'){
				this.showConfirmDialog();
			}
			else if(result.responses[i].type == 'beingEdited'){
				this._alertBeingEdited();
			}else{
				this.showConfirmDialog();
			}

		}.bind(this));
	}
	
});

EventSelectors.register({
	'.rollBack': function(el, index) {
		new deleteRollBack(el,{
			module: 'BlogDetail'
		},true);
	}
}, true);/*
* By Nandhin Coutinho on Jan 26th 2009
* Handles edit collision and record locking
*/
var editContent = stdClass.extend({
	//constructor
	constructor: function(el, settings, archived)
	{
		
		if(!settings.module || !settings.type) return ;
			
		//get contentId from URL
		if(!contentId && settings.type == 'group' && el.href) {
			var elHref = el.href.split('?');
			elHref_A = elHref[0].split('/');
			var contentId = elHref_A[elHref_A.length -2];
		}else {
			var href = window.location.href;
			var newhref = href.split("?");
			var href_array = newhref[0].split("/");
			var contentId = href_array[href_array.length -2];			
		}
		
		if(!contentId)  return ;
			
		this.base();
		
		// timers
		var checkEditTimer = null;
		
		
		// initialize settings
		Object.extend(this.s, {
			json: {
				ver: '0.1',
				meta: {},
				data: {
					requests: []
				}
			},

			contentId: contentId,
			entryType: settings.type,			
			moduleName:	settings.module
			
		});
		
		// initialize nodes
		Object.extend(this.n, {
			el: el,
			beingEditedAlert: null,
			canEditAlert: null,
			overrideCautionAlert: null,
			viewEditAlert: null
			
		});

		// initialize collections
		Object.extend(this.c, {
			requests: []
			/* put extensions to collections here */
		});
					
		this._addEvents();
	},
	
	
	editOnClick: function(e) {
		Event.stop(e);
		
		this.sendCheckEditRequest();
		
	},
	
	sendCheckEditRequest : function () {
		// check if content being edited
		this.addRequest("checkBeingEdited", {
			uniqueID: this.s.contentId,
			entryType: this.s.entryType
		});		
		this.JsonOut();
	},

	sendRemoveLockRequest : function () {
		// check if content being edited
		this.addRequest("removeLock", {
			uniqueID: this.s.contentId,
			entryType: this.s.entryType			
		});		
		this.JsonOut();
	},
	
	sendReadOnlyRequest : function () {
		// check if content being edited
		this.addRequest("readOnly", {
			uniqueID: this.s.contentId
		});		
		this.JsonOut();
	},
	
	addRequest: function(requestName, dataObject) {
		this.c.requests.push({
			id: this.c.requests.length,
			type: requestName,
			data: dataObject
		});
	},	
	
	_addEvents: function() {
		this.eObserve(this.n.el, 'click', this.editOnClick.bindAsEventListener(this));
	},
	
	/* --------------------- Dialog Boxes ---------------------------------*/
	
	_alertCanEdit: function (message) {		
		// create can edit dialog
		this.n.canEditAlert = new ConfirmDialog({
				'+zones': {
					heading: 'Can Edit Item',
					content: '<div class="text"> You Can now edit the item. </div>' +
					'		<form class="buttons">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_edit.gif" alt="Edit" class="image ok">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_cancel.gif" alt="Cancel" class="image cancel">' +
					'		</form>'
				},
				classNames: ['kDialog2 lightboxPopup'],
				onClickOK: function() {
					window.location = this.n.el.href;
					return true;
				}.bind(this)
		});
		
	},
	
	
	_alertOverrideCaution: function (message) {		
	
		// store parent for event handlers
		var parentThis = this;
		
		// create warning dialog
		this.n.overrideCautionAlert = new ConfirmDialog({
				'+zones': {
					heading: 'Warning',
					content: '<div class="text"> WARNING: you are about to override the edit lock, which could result in edit collisions and data loss. Are you sure you want to proceed? </div>' +
					'		<form class="buttons">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_override_caution.gif" alt="Proceed With Caution" class="image override">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_cancel.gif" alt="Cancel" class="image cancel">' +
					'		</form>'
				},
				classNames: ['kDialog2 lightboxPopup'],
				'+innerTriggers': [
					{node: '.override', event: 'click', action: function(ele, e) { parentThis.onClickOverrideProceed(ele, e); } },
					{node: '.cancel', event: 'click', action: 'onClickCancel' },
					{node: '.close', event: 'click', action: 'hide' }
				]
		});
		
	},

	_alertViewEdit: function (message) {
	
		// store parent for event handlers
		var parentThis = this;
		
		// create view readonly dialog
		this.n.viewEditAlert = new ConfirmDialog({
				'+zones': {
					heading: 'Warning',
					content: '<div class="text"> You will be able to view the edit form, but will not be able to save any edits. </div>' +
					'		<form class="buttons">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_view_editform.gif" alt="View Edit Form" class="image viewedit">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_cancel.gif" alt="Cancel" class="image cancel">' +
					'		</form>'
				},
				classNames: ['kDialog2 lightboxPopup'],
				'+innerTriggers': [
					{node: '.viewedit', event: 'click', action: function(ele, e) { parentThis.onClickViewEdit(ele, e); } },
					{node: '.cancel', event: 'click', action: 'onClickCancel' },
					{node: '.close', event: 'click', action: 'hide' }
				]
		});
		
	},

	_alertBeingEdited: function (message) {
		
		if(this.n.beingEditedAlert != null) {
			this.n.beingEditedAlert.setText(message);
		}else{
			var parentThis = this;
			this.n.beingEditedAlert = new ConfirmDialog({
				'+zones': {
					heading: 'Item Being Edited',
					content: '<div class="text">' + message + '</div>' +
					'		<form class="buttons">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_override_edit.gif" alt="Override Edit Lock" class="image override">' +
					'			<input type="image" src="'+Config.templatePath+'i/button_view_readonly.gif" alt="View as Read Only" class="image readonly" >' +
					'			<input type="image" src="'+Config.templatePath+'i/button_cancel.gif" alt="Cancel" class="cancel">' +

					'		</form>'
				},
				classNames: ['kDialog2 lightboxPopup'],
				'+innerTriggers': [
					{node: '.override', event: 'click', action: function(ele, e) { parentThis.onClickOverride(ele, e); } },
					{node: '.readonly', event: 'click', action: function(ele, e) { parentThis.onClickReadOnly(ele, e); }},					
					{node: '.cancel', event: 'click', action: function(ele, e) { parentThis.onClickEditCancel(ele, e); }},
					{node: '.close', event: 'click', action: function(ele, e) { parentThis.onClickEditCancel(ele, e); }},
					{node: '.ok', event: 'click', action: function(ele, e) { parentThis.onClickEditCancel(ele, e); }}					
				]
			});
		}
	},
	
	/* --------------------- Dialog Boxes  Event Handlers ---------------------------------*/
	
	onClickEditCancel: function(ele, e) {
		// reset edit
		this._resetEditSettings();
		
		return true;
	},
	
	onClickReadOnly: function(ele, e) {
		Event.stop(e);
		
		// reset edit
		this._resetEditSettings();
		
		// invoke viewEdit dialog
		this._alertViewEdit();
		
		return true;
	},
	
	onClickOverride: function(ele, e) {
		Event.stop(e);
		
		// reset edit
		this._resetEditSettings();
		
		// invoke caution dialog
		this._alertOverrideCaution();
		
		return true;
	},

	onClickOverrideProceed: function(ele, e) {
		Event.stop(e);
		
		// destroy the dialog
		if(this.n.overrideCautionAlert != null) {
			this.n.overrideCautionAlert.hide();
			this.n.overrideCautionAlert = null;
		}
		
		// remove lock;
		this.sendRemoveLockRequest();
		
		return true;
	},
	
	onClickViewEdit: function(ele, e) {
		Event.stop(e);
		
		// destroy the dialog
		if(this.n.viewEditAlert != null) {
			this.n.viewEditAlert.hide();
			this.n.viewEditAlert = null;
		}
		
		// send readonly request
		this.sendReadOnlyRequest();
		
		return true;
	},
	

	_resetEditSettings: function () {
		
		// clear checkEdit timer
		if(this.checkEditTimer != null) {
			clearInterval(this.checkEditTimer);
			this.checkEditTimer = null;
		}
		
		// destroy the dialog
		if(this.n.beingEditedAlert != null) {
			this.n.beingEditedAlert.hide();
			this.n.beingEditedAlert = null;
		}
	},
	
	
	/* --------------------- JSON Methods ---------------------------------*/
	JsonOut: function() {
		//construct the post
		this.s.json.data.requests = this.c.requests;
		//this.setMeta('columns', '');
		var data = '__json=' + this.s.moduleName + '&data=' + Object.toJSON(this.s.json);
		this.c.requests = [];
		
		//send out the request
		var myAjax = new Ajax.Request(window.location,
		{
			method: 'post',
			parameters: data,
			onSuccess: this.JsonIn.bind(this)
		});
		
	},
	
	JsonIn: function(t) {
		//alert(t.responseText);
		var result = t.responseText.evalJSON();
		(result.responses.length).times(function(i) {
			if(result.responses[i].type == 'beingEdited'){
				var message = result.data.html;
				this._alertBeingEdited(message);
				
				// check edit status every minute
				if(this.checkEditTimer == null) {
					this.checkEditTimer = setInterval (this.sendCheckEditRequest.bind(this), 60000);
				}
			}
			else if (result.responses[i].type == 'canEdit') {
				if(this.checkEditTimer != null || this.n.beingEditedAlert != null) {
					this._resetEditSettings();
					
					// show can edit message
					this._alertCanEdit();
				} else {
					// if we get here, allow edit
					window.location = this.n.el.href;
				}
			}
			else if (result.responses[i].type == 'removedLock') {
				
				// redirect to edit page
				window.location = this.n.el.href;
			}
			else if (result.responses[i].type == 'readOnly') {
				
				// reset edit settings ( close timer and dialog)
				this._resetEditSettings();
				
				// redirect with readonly params
				var redirectURL = this.n.el.href;

				var roString = decodeURIComponent(result.data.html);
				if(/\?/.test(roString)) {
					redirectURL += '&' + roString ;
				} else {
					redirectURL += '?' + roString ;
				}
				window.location = redirectURL;
			}			

		}.bind(this));
	}
	
});

EventSelectors.register({
	'#editEntry': function(el, index) {
		new editContent(el,{
			module: 'ManageEditCollision',
			type: 'content'
		},true);
	},
	'#editEventEntry': function(el, index) {
		new editContent(el,{
			module: 'ManageEditCollision',
			type: 'event'
		},true);
	},
	'#editGroupEntry': function(el, index) {
		new editContent(el,{
			module: 'ManageEditCollision',
			type: 'group'
		},true);
	},
	'#editCategory': function(el, index) {
		new editContent(el,{
			module: 'ManageEditCollision',
			type: 'topic'
		},true);
	},
	'a.manage_item': function(el, index) {
		new editContent(el,{
			module: 'ManageEditCollision',
			type: 'group'
		},true);
	}
}, true);/* rssViewer.js */
var RssViewer = Class.create();
RssViewer.prototype = {
	//Constructor
	initialize: function(el, settings) {
		if (!settings) {
			settings = {};
		}
		google.load("feeds", "1");
		this.el = el;
		this.container = document.createElement('div');
		this.container.className = "rssViewer";
		this.container.innerHTML = "Loading RSS Feed...";
		this.el.parentNode.insertBefore(this.container, this.el);
		
		this.maxEntries = (settings.maxEntries) ? settings.maxEntries : 0;
		this.useSnippet = (settings.useSnippet) ? settings.useSnippet : false;
		this.maxContentLength = (settings.maxContentLength) ? settings.maxContentLength : false;
		this.externalParams = (settings.externalParams) ? settings.externalParams : '';
		this.showFeedTitle = settings.showFeedTitle != undefined && settings.showFeedTitle == false ? false : true;
		this.resourceTitle = settings.resourceTitle;
		this.previewImage = settings.previewImage;
		this.contentEntryLink = settings.contentEntryLink;
		this.useCustomSnippet = settings.useCustomSnippet;
		this.maxSnippetLength = settings.maxSnippetLength;
		
		this.numChecked = 0;
		
		this.waitUntilReady();
	},
	
	waitUntilReady: function() {
		if (google && google.feeds && google.feeds.Feed && isReady()) {
			this.feed = new google.feeds.Feed(this.el.value);
			this.feed.load(this.onLoadFeed.bind(this));
		} else if(this.numChecked < 500) {
			this.numChecked++;
			setTimeout(this.waitUntilReady.bind(this), 10);
		}
	},
	
	onLoadFeed: function(result) {
		if (result.error && result.error.message) {
			this.container.innerHTML = result.error.message;
			return;
		}
		var html = "";
		if (Boolean(this.previewImage))
			html += '<span class="img floatleft"><a href="' + (Boolean(this.contentEntryLink) ? this.contentEntryLink :  entry.link) + '"><img src="' + this.previewImage + '" alt=""/></a></span>';
		if (this.showFeedTitle)
			html += '<div class="header"><h2>' + (Boolean(this.resourceTitle) ? this.resourceTitle : result.feed.title) + '</h2></div>';
		for (var i=0, entry; entry = result.feed.entries[i]; i++) {
			if (i >= this.maxEntries && this.maxEntries != 0) {
				break;
			}
			html += '<div class="entry">'+
			'<h3><a href="' + (Boolean(this.contentEntryLink) ? this.contentEntryLink :  entry.link) + '">' + entry.title + '</a></h3>';
			if (entry.publishedDate || entry.author) {
				var arr = new Array();
				if (entry.publishedDate) {
					arr.push(entry.publishedDate);
				}
				if (entry.author) {
					arr.push('Author: ' + entry.author);
				}
				html += '<p class="info">';
				html += arr.join('<br />');
				html += '</p>';
			}
			
			if (this.useCustomSnippet) {
				var content = entry.content.replace(/<.*?>/g, "");
				if (this.maxSnippetLength && content.length > this.maxSnippetLength) {
					content = content.substr(0, this.maxSnippetLength-3).replace(/\s\S*$/, "") + "...";
				}
			}
			else {
				var content = (this.useSnippet && entry.contentSnippet)? entry.contentSnippet : entry.content;
				if (content.length > this.maxContentLength) {
					content = content.substring(0, this.maxContentLength);
				}
			}
			html += '<div class="content">' + content + '</div>';
			html += '<p class="links"><a href="' + (Boolean(this.contentEntryLink) ? this.contentEntryLink :  entry.link) + '">Read More</a></p>';
			html += '</div>';
		}
		this.container.innerHTML = html;
		
		//fix the html so that the ManyOne banner stays on top
		if (!Boolean(this.contentEntryLink)) {
			var aElements = this.container.getElementsByTagName('a');
			for (var j=0, element; element = aElements[j]; j++) {
				element.href = 'http://' + Config.urlBase + 'external.php?link='+ element.href + '&' + this.externalParams;
			}
		}
	}
};/*
*/
var tocClass = Class.create();
tocClass.prototype = {

	//Constructor
	initialize: function(el) {
		this.el = el;
		this.tocArr = new Array;
		this.rx = /[hH]([1-6])/;	 
		this.generate_TOC('tableofcontents');		
	},
	//Methods
	 H_getText: function(el) {
	  	var text = "";
	  	for (var i = el.firstChild; i != null; i = i.nextSibling) {
			if (i.nodeType == 3 /* Node.TEXT_NODE, IE doesn't speak constants */)
		  		text += i.data;
			else if (i.firstChild != null)
		  	text += this.H_getText(i);
	  	}
	  	return text;
	},
	
	TOC_EL: function(el, text, level) {
		var obj = new Object();
		obj.element = el;
		obj.text = text;
		obj.level = level;
		return obj;
	},
	
	getHeadlines: function(el) {		
	  this.tocArr = new Array;	  
	  this.rec(el);
	  return this.tocArr;
	},

	
	 //recursive function that scans the DOM tree
 	rec: function (el) {
		for (var i = el.firstChild; i != null; i = i.nextSibling) 
		{
		 
		  if (i.nodeType == 1 /* Node.ELEMENT_NODE */) 
		  {			
			if (this.rx.exec(i.tagName))
			{			  
			  this.tocArr[this.tocArr.length] = this.TOC_EL(i, this.H_getText(i), parseInt(RegExp.$1));		
			}
			this.rec(i);
		  }
		}
	 },
	
	generate_TOC: function(parent_id) {	 
	
	  var exisitingTocNode = document.getElementById("tableofcontents");
	  
	  if (exisitingTocNode != null) return true;
	  
	  var topNode = document.getElementById("topofcontent"); // topofcontent
	  var showToc = document.getElementById("showtoc").getAttribute('showtoc');
	  
	  var hs = this.getHeadlines(topNode);
	  
	  if (hs.length >0 && showToc == 1)
	  {		
		  
		  var tocNode = document.createElement('div');
		  tocNode.id = parent_id;
		  tocNode.style.display = "block";		  
		  var parent = hs[0].element.parentNode.insertBefore(tocNode,hs[0].element);
		  var tocTitle = document.createElement('h5');
		  tocTitle.style.textAlign="center";
		  var tocTitleText = document.createTextNode(" Table of Contents");
		  tocTitle.appendChild(tocTitleText);
		  parent.appendChild(tocTitle);	
	  }
	  else
	  {  		
		return 0;
	  }	
	  
	  var lineNumberArray = new Array();
	  var oldLevels = new Array();
	  
	  lineNumberArray[0] = 0;
	  lineNumberArray[1] = 0;
	  lineNumberArray[2] = 0;
	  lineNumberArray[3] = 0;
	  lineNumberArray[4] = 0;
	  lineNumberArray[5] = 0;	  

	  for (var i = 0; i < hs.length; ++i) 
	  {
		  
		var hi = hs[i];		
		var lineNumber = '';
		var newLevel = hi.level;
		
		oldLevels[i] = hi.level;
		var changed = 0;
		if (i == 0)
		{
			newLevel = 1;
			hs[i].level = newLevel;		
			changed = 1;
		}
		else if(hs[i].level <= oldLevels[i-1])
		{			
			for(c=i-1;c >=0; c--)
			{
				if (oldLevels[c] > hs[i].level) continue;
				if (oldLevels[c] < hs[i].level)
					newLevel = hs[c].level+1;
				else
					newLevel = hs[c].level;				
				if (newLevel == 0) newLevel = 1;
				changed = 1;
				break;
			}
			
			if (changed == 0) newLevel = 1; //if no change in level, set it to 1
			hs[i].level = newLevel;
		}
		else if (hs[i].level - oldLevels[i-1] >= 1)
		{
			newLevel = hs[i-1].level+1;
			hs[i].level = newLevel;
			changed == 1;
		}
		
		
		for(c = newLevel; c < 6; c++)
		{
			lineNumberArray[c] = 0;
		}
		
		++lineNumberArray[newLevel-1];
		
		for(c = 0; c < newLevel; c++)
		{
			if (lineNumber == '')
				lineNumber = lineNumberArray[c];
			else
				lineNumber = lineNumber + "." + lineNumberArray[c];
		}		
		
		var d = document.createElement("div");
		if (hi.element.id == "")
		  hi.element.id = "gen" + i;
		var a = document.createElement("a");
		a.href = "#" + hi.element.id;
		a.appendChild(document.createTextNode(lineNumber + " " + hi.text));
		d.appendChild(a);		
		d.className = "level" + newLevel;
		parent.appendChild(d);
	  }	  
	  
	}
	

}

//instantiate and use the object
EventSelectors.addLoadEvent(function(e1) {
	new tocClass(e1);
});
var addComment = stdClass.extend({
	//constructor
	constructor: function(el, settings) {
		this.base();
		// initialize settings
		Object.extend(this.s, {
			moduleName: 'AddComment',
			json: {
				ver: '0.1',
				meta: {},
				data: {},
				requests: []
			}
			/* put extensions to collections here */
		});
		
		// initialize nodes
		Object.extend(this.n, {
			el: el,
			form: null,
			submitButton: null,
			dialog: null
			/* put extensions to nodes here */
		});
		
		// initialize collections
		Object.extend(this.c, {
			requests: []
			/* put extensions to collections here */
		});
		this._attachEvents();
	},
	
	elOnClick: function(e) {
		Event.stop(e);
		new FormDialog({
			'+zones': {
				heading: 'Loading...',
				text: 'Loading...'
			},
			position: {  
				exemplarAnchor: 'bottom right',
				selfAnchor: 'top right',
				exemplar: this.n.el,
				offsetY: 0,
				offsetX: 0
			},
			groupId: 'InviteDialogs',
			groupLimit: 1,
			startHidden: true,
			moduleName: this.s.moduleName,
			parentThis: this
		});
	},
	_attachEvents: function() {
		this.eObserve(this.n.el, 'click', this.elOnClick.bind(this));
	}
});

EventSelectors.register({
	'a.comment': function(el, index) {
		new addComment(el);
	}
}, true);
var refreshModuleClass = stdClass.extend({
	//constructor
	constructor: function(settings) {
		this.base();
		// initialize settings
		Object.extend(this.s, {
			moduleName: 'RefreshModule',
			ceid: null,
			json: {
				ver: '0.1',
				meta: {},
				data: {},
				requests: []
			}
			/* put extensions to settings here */
		});
		Object.extend(this.s, settings);
		
		// initialize nodes
		Object.extend(this.n, {
			/* put extensions to nodes here */
		});
		
		// initialize collections
		Object.extend(this.c, {
			requests: []
			/* put extensions to collections here */
		});
	},
	
	refresh: function(moduleNames){
		
		for(var x=0; x<moduleNames.length; x++){
			this.addRequest('getModule', {
				moduleName: moduleNames[x]
			});
		}
		this.JsonOut();
		
	},
	
	addRequest: function(requestName, dataObject) {
		this.c.requests.push({
			id: this.c.requests.length,
			type: requestName,
			data: dataObject
		});
	},
	//json methods
	JsonOut: function() {
		//construct the post
		this.s.json.data.requests = this.c.requests;
		//this.setMeta('columns', '');
		var data = '__json=' + this.s.moduleName + '&data=' + Object.toJSON(this.s.json);
		this.c.requests = [];
		//send out the request
		var myAjax = new Ajax.Request(window.location,
		{
			method: 'post',
			parameters: data,
			onSuccess: this.JsonIn.bind(this)
		});
	},
	
	JsonIn: function(t) {
		var result = t.responseText.evalJSON();
		(result.responses.length).times(function(i) {
			switch(result.responses[i].type){
			case "showPageModule":
				var tempEl = document.createElement('div');
				tempEl.innerHTML = result.responses[i].data.html;
				var ele = document.getElementById('pmid_' + result.responses[i].data.pageModuleId);
				if(ele){
					ele.innerHTML = document.getElementsBySelector('.box', tempEl)[0].innerHTML;
					if(typeof(addComment) != 'undefined'){
						var addComments = document.getElementsBySelector('a.comment', ele);
						for(var x=0; x<addComments.length; x++){
							new addComment(addComments[x]);
						}
					}
				}
				break;
			}
		}.bind(this));
	}
});

var RefreshModule = new refreshModuleClass({});