/*
-----------------------------------------------
$Rev: 1079 $
$Date: 2010-08-31 14:00:58 -0500 (Tue, 31 Aug 2010) $
$Author: boyan $
-----------------------------------------------
*/
adminUtilitiesInstance = {};
var adminUtilities = Class.create({
// Define the name of the css class that the script will look for
// and add confirmation for the html elements that have that class
confirmDeleteSelector: '[class="confirmDelete"],.confirmDelete',
selectAllOnClickElementSelector: '[class="selectAllOnClick"],.selectAllOnClick',
confirmInModalWindowOnDeleteContainerID: 'confirmInModalWindowOnDeleteContainer',
confirmDynamicContentID: 'confirmDynamicContent',
infoTriggerSelector: '[class="infoTrigger"],.infoTrigger',
tooltipTriggerSelector: '[class="tooltipTrigger"],.tooltipTrigger',
redirectButtonSelector: 'input[class="redirectButton"],.redirectButton',
refreshPageSelector: '[class="refreshPage"],.refreshPage',
refreshPageWithQueryStringSelector: '[class="refreshPageWithQueryString"],.refreshPageWithQueryString',
//redirectPageSelector: '[class="redirectPage"],.redirectPage',
reloadOnEnterSelector: '[class="reloadOnEnter"],.reloadOnEnter',
reloadOnClickSelector: '[class="reloadOnClick"],.reloadOnClick',
videoTabClass: 'videoTab',
videoTabSelector: '[class="videoTab"],.videoTab',
videoTabSelectedClass: 'videoTabSelected',
setFocusSelector: '[class="setFocus"],.setFocus',
adminMenuSelector: '[class="adminMenu"],.adminMenu',
hideObserver: '',
confirmYesButtonID: 'confirmYesButton',
confirmNoButtonID: 'confirmNoButton',
confirmMessage: 'Are You Sure?',
triggerElement: '',
initialize: function() {
	var statusMessageContainer = $$('div#statusMessageContainer')[0];

	this.adjustPageDim();
	
	// Hide the status message container if it's empty
	if ($(statusMessageContainer)) {
		if ($(statusMessageContainer).empty()) $(statusMessageContainer).hide();
	}

	if ($(this.confirmInModalWindowOnDeleteContainerID)) {
		$(this.confirmInModalWindowOnDeleteContainerID).hide();
	}

	// For each element that has the 'confirmDeleteSelector' defined,
	// add a function to the click event to confirm the delete action
	$$(this.confirmDeleteSelector).invoke('observe', 'click', this.confirmDelete.bind(this));

	// For each element that has the 'infoTriggerSelector' defined,
	// add a function to the click event to show the information in a modal window
	$$(this.infoTriggerSelector).invoke('observe', 'click', this.showInfo.bind(this));

	// For each element that has the 'redirectButtonSelector' defined,
	// add a function to the click event to redirect the page to the new location based on the
	// clicked element
	$$(this.redirectButtonSelector).invoke('observe', 'click', this.redirectPage.bind(this));

	// For each element that has the 'reloadOnEnterSelector' defined,
	// add a function to the keyup event to reload the page
	$$(this.reloadOnEnterSelector).invoke('observe', 'keyup', this.reloadPageOnEnter.bind(this));
	
	// For each element that has the 'reloadOnClickSelector' or 'refreshPageSelector' defined,
	// add a function to the click event to reload the page
	$$(this.reloadOnClickSelector, this.refreshPageSelector).invoke('observe', 'click', this.reloadPageOnClick.bind(this));

	$$(this.refreshPageWithQueryStringSelector).invoke('observe', 'click', this.reloadPageWithQueryStringOnClick.bind(this));

	var adminMenu = $$(this.adminMenuSelector);

	// If the admin drop down list exists on the page
	if (adminMenu.length > 0) {
		adminMenu = $$(this.adminMenuSelector)[0];

		// Add an observer to the admin menu's change event to redirect to the new location
		$(adminMenu).observe('change', this.redirectPage.bind(this));

		// Get the current aspx page
		var currentLocation = location.pathname.gsub(/.*\/(\w+.*)$/, '#{1}').toLowerCase();

		// Loop over the items in the drop down list and select the one
		// that matches the current url
		for (i = 0; i < $(adminMenu).options.length; i++) {
			if ($(adminMenu).options[i].value.toLowerCase().include(currentLocation)) {
				$(adminMenu).selectedIndex = i;
				break;
			}
		}
	}

	// For each element that has the 'videoTab' class defined
	$$(this.videoTabSelector).each((function(e) {
		// If the href attribute of the element is defined
		if ($(e).readAttribute('href') != 'undefined') {
			// Get the filename from the location string such as "myLibrary.aspx"
			// and compare it against the value of the "href" attribute
			if (location.href.toLowerCase().gsub(/.*\/(\w+\.\w+)\??.*$/, '#{1}') == $(e).readAttribute('href').toLowerCase().gsub(/(.*\/)?(\w+\.\w+)\??.*$/, '#{2}')) {
				// There was a match, so remove the videoTab class
				$(e).removeClassName(this.videoTabClass);
				// And add the "videoTabSelected" class to mark the tab as selected
				$(e).addClassName(this.videoTabSelectedClass);
			}
			else {
				// There was no match, so remove the videoTabSelected class
				$(e).removeClassName(this.videoTabSelectedClass);
				// And add the "videoTab" class to mark the tab as not selected
				$(e).addClassName(this.videoTabClass);
			}
		}
	}).bind(this));

	this.activateField();

	this.observeSelectAllOnClick();

	this.loadGoogleAnalytics();
},
setupModalBox: function(confirmMessage) {
	$(this.confirmDynamicContentID).update(
		new Element('p').update(confirmMessage)
		).insert(
		new Element('input', { type: 'button', value: 'Yes', id: this.confirmYesButtonID })
		).insert(
		new Element('span').update('&nbsp;or ')
		).insert(
		new Element('input', { type: 'button', value: 'No', id: this.confirmNoButtonID }));
},
setObservers: function() {
	$(this.confirmYesButtonID).observe('click', this.submitConfirm.bind(this));
	$(this.confirmNoButtonID).observe('click', function() { Modalbox.hide(); });
},
removeObservers: function() {
	$(this.confirmYesButtonID).stopObserving('click');
	$(this.confirmNoButtonID).stopObserving('click');
},
loadGoogleAnalytics: function() {
	if (typeof(pluginConfig) != 'undefined') {
		if (!pluginConfig.googleAnalyticsTrackerID.empty()) {
			try {
				pageTracker = _gat._getTracker(pluginConfig.googleAnalyticsTrackerID);
				pageTracker._setDomainName('none');
				pageTracker._setAllowLinker(true);
				pageTracker._setAllowHash(false);
				pageTracker._link();
				pageTracker._linkByPost();
				pageTracker._getLinkerUrl(location.href);
				pageTracker._trackPageview();
			} catch(err){}
		}
	}
},
loadAnalyticsScript: function(sourceUrl, cb) {
	this.loadScript(sourceUrl, '_ga', function () {
		return !!(typeof(_gat) == 'object');
	}, cb);
},
activateField: function() {
	// If the element has a class name that matches the setFocusSelector
	$$(this.setFocusSelector).each(function(e) {
		// Activate the element
		$(e).activate();

		throw $break;
	});
},
observeSelectAllOnClick: function() {
	// Observe the click on the links with selector 'selectAllOnClickElementSelector'
	// and select the text in the clicked textbox
	$$(this.selectAllOnClickElementSelector).invoke('observe', 'click', function(event) {
		var e = Event.element(event);

		if ($(e)) {
			$(e).select();
		}
	});
},
redirectPage: function(event) {
	// Get the element that caused the event
	var e = Event.element(event);
	var newUrl = '';

	if (e.readAttribute('rel') != 'undefined' && e.readAttribute('rel') != null) {
		newUrl = e.readAttribute('rel');
	}
	else if ($F(e) != 'undefined') {
		newUrl = $F(e);
	}

	if (!newUrl.empty()) location.href = newUrl;
},
reloadPageOnEnter: function(e) {
	var element = Event.element(e);

	if (e.element().type === 'text' && (e.keyCode == Event.KEY_RETURN || e.keyCode == 3)) {
		var url = location.href.gsub(/\?.*/, '') + '?' + $(element).readAttribute('name') + '=' + $F(element);
		location.href = url;
	}
},
reloadPageOnClick: function(e) {
	// Get the element that caused the event to fire
	var element = Event.element(e);
	var referanceElement = '';

	// If the element had a 'rel' attribute defined
	if (element.readAttribute('rel') != undefined && $(element.readAttribute('rel'))) {
		// Get the a handle on the element defined in the 'rel' attribute
		referanceElement = $(element.readAttribute('rel'));

		// Change the location of the page by appending the name and the value of the 'rel' defined element
		location.href = location.href.gsub(/\?.*/, '') + '?' + $(referanceElement).readAttribute('name') + '=' + $F(referanceElement);
	}
	else {
		// Change the location of the page by stripping the query string
		location.href = location.href.gsub(/\?.*/, '')
	}
},
reloadPageWithQueryStringOnClick: function(e) {
	// Get the element that caused the event to fire
	var element = Event.element(e);
	var referanceElement = '';
	var refreshUrl = '';

	// If the element had a 'rel' attribute defined
	if (element.readAttribute('rel') != undefined && $(element.readAttribute('rel'))) {
		// Get the a handle on the element defined in the 'rel' attribute
		referanceElement = $(element.readAttribute('rel'));

		// Set the refresh Url by appending the name and the value of the 'rel' defined element
		if (location.search != undefined) {
			refreshUrl = location.href + '&' + $(referanceElement).readAttribute('name') + '=' + $F(referanceElement);
		}
		else {
			refreshUrl = location.href + '?' + $(referanceElement).readAttribute('name') + '=' + $F(referanceElement);
		}
	}
	else if (element.readAttribute('strip') != undefined) {
		var stripFromQuery = element.readAttribute('strip');
		var queryString = $H(location.search.toQueryParams());

		queryString.unset(stripFromQuery);

		refreshUrl = location.href.gsub(/\?.*/, '') + '?' + queryString.toQueryString();
	}
	else {
		refreshUrl = location.href;
	}

	// Change the location of the page to the built refresh Url
	location.href = refreshUrl;
},
confirmDelete: function(event) {
	// Get the element that caused the event
	var e = Event.element(event);
	var confirmMessage = '';

	// If the element exists
	if ($(e)) {
		// Read the confirmation mesage from the element's 'rel' attribute
        // or use the default confirm message defined in this class
        confirmMessage = (e.readAttribute('rel') != null) ? e.readAttribute('rel') : this.confirmMessage;

		// If the confirm message is not empty, display it
		// and get the user's input
		if (!confirmMessage.empty()) {
			if ($(this.confirmInModalWindowOnDeleteContainerID)) {
				this.triggerElement = $(e);
				this.setupModalBox(confirmMessage);

				Modalbox.show($(this.confirmInModalWindowOnDeleteContainerID), {
					title: 'Confirm',
					width: 400,
					overlayClose: false,
					closeValue: '',
					afterLoad: this.setObservers.bind(this),
					onHide: this.removeObservers.bind(this)
				});

				// Stop the event
				Event.stop(event);
			}
			else if (!confirm(confirmMessage)) {
				// If the user clicked on 'Cancel', stop the event
				Event.stop(event);
			}
		}
	}
},
submitConfirm: function(event) { },
showInfo: function(event) {
	// Get the element that caused the event
	var e = Event.element(event);

	// Show the model window with the information
	Modalbox.show($(e.parentNode).select('.info')[0], {
		title: e.readAttribute('title'),
		width: 400,
		autoFocusing: false,
		afterLoad: (function() {
			// After the modal window loads
			this.activateField();
		}).bind(this)
	});
},
findPosY: function(obj) {
	var curtop = 0;

	if(obj.offsetParent)
		while(1) {
		  curtop += obj.offsetTop;

		  if(!obj.offsetParent) break;

		  obj = obj.offsetParent;
		}
	else if(obj.y) curtop += obj.y;

	return curtop;
},
// to set dimming (pageDim) DIV to complete height of the page and not just the browser window
adjustPageDim: function() {
	var divDim = ($$('div.pageDimOff').length > 0) ? $$('div.pageDimOff')[0] : $$('div.pageDimOn')[0];
	var pageHeight = this.findPosY(document.getElementById('endMarker')) + 30;
	var screenHeight = this.getViewportHeight() + 30;

	if (parseInt(screenHeight) > parseInt(pageHeight)) $(divDim).setStyle({ 'height': screenHeight + 'px' });
	else $(divDim).setStyle({ 'height': pageHeight + 'px' });
	var editFormExists = ($$('.addForm').length > 0) ? true : false;
    
	if (editFormExists) {
		divDim.writeAttribute('class', 'pageDimOn');
  
		if ($$('.addForm').length > 0) {
			$$('.addForm')[0].setStyle({'position': 'relative'});

			$$('.addItem').invoke('writeAttribute', 'class', 'addItemSelected');
		}
	}
	else {
		divDim.writeAttribute('class', 'pageDimOff');
	}
},
getViewportHeight: function() {
	var viewportwidth;
	var viewportheight;

	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (typeof window.innerWidth != 'undefined')
	{
	  viewportwidth = window.innerWidth,
	  viewportheight = window.innerHeight
	}
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	else if (typeof document.documentElement != 'undefined'
	 && typeof document.documentElement.clientWidth !=
	 'undefined' && document.documentElement.clientWidth != 0)
	{
	   viewportwidth = document.documentElement.clientWidth,
	   viewportheight = document.documentElement.clientHeight
	}
	// older versions of IE
	else
	{
	   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
	   viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}

	return viewportheight;
}
});

// Create an instance of the object after the page has loaded
document.observe("dom:loaded", function() {
	adminUtilitiesInstance = new adminUtilities();
});
