var ffBaseURL = (typeof ffBaseURL == 'undefined') ? '' : ffBaseURL;

function ffRewriteAnchorLinks() {
    if (document.getElementsByTagName("base").length > 0) {
        var base = document.getElementsByTagName("base")[0].href;
        var url = window.location.href;
        if (url.indexOf("#") > 0) url = url.substr(0, url.indexOf("#"));
        var links = document.getElementsByTagName("a");
        for (var i = 0; i < links.length; i++) {
            if (links[i].href) {
                var poundPos = links[i].href.indexOf("/#");
                if (poundPos > 0) {
                    links[i].href = url + links[i].href.substr(poundPos + 1);
                }
            }
        }
    }
}

// page build tools - only run on page, with jquery
if (!(typeof $ == 'undefined') && !(typeof ffPageID == 'undefined')) {
    $(function() {

        // setup component edit
        $('div.componentedit').each(function() {
            setupComponentEdit(this);
        });
        // set up nav edit
        $('li.navitem.editable').hover(function() {
            $('>span.pageedit', this).css('display', 'inline');
        }, function() {
            $('>span.pageedit', this).css('display', '');
        });
        // set styles on modify tools
        $('span.pageedit a').css({ margin: 0, border: 0, padding: 0, display: 'inline' });
        // set up general reveals
        $('.parent-reveal').each(function() {
            var me = $(this);
            me.parent().hover(function() {
                me.css('visibility', 'visible');
            }, function() {
                me.css('visibility', 'hidden');
            });
        });
        // wire up search
        var searchform = $('form[action="search.aspx"]');
        if (searchform.length > 0) {
            var site_id = $('input[name="site_id"]', searchform);
            if (site_id.length > 0)
                site_id = site_id[0].value;
            else
                site_id = -1;

            var query = $('input[name="query"]', searchform);
            var offsetleft = Math.round((query.outerWidth() - query.width()) / 2);
            var offsettop = 0;
            var border = (getStyle(query[0], 'borderBottomColor'));
            var bg = (getStyle(query[0], 'backgroundColor'));
            function showSearching() {
                var html = '<div class="minor-help-text">Searching...</div>';
                if ($('div#ffQuickSearch').length == 0) {
                    if (html == '') return;
                    node = $('<div id="ffQuickSearch">' + html + '</div>');
                    node.css({ 'position': 'absolute', 'top': (getTop(query[0]) + query.outerHeight() - offsettop) + 'px', 'left': (getLeft(query[0]) + offsetleft) + 'px' });
                    if (border)
                        node.css({ 'border-bottom': '1px solid ' + border, 'border-left': '1px solid ' + border, 'border-right': '1px solid ' + border, 'border-top': '0px solid ' + border });
                    if (bg && (bg.toUpperCase() != 'TRANSPARENT'))
                        node.css({ 'background-color': bg });
                    node.css('width', query.width());
                    $('body').append(node);
                    $('body').click(function() {
                        node.hide();
                    });
                } else {
                    $('div#ffQuickSearch').html(html);
                    $('div#ffQuickSearch').show();
                }
            }
            function hideSearching() {
                $('div#ffQuickSearch').hide();
            }
            function showResults(xml) {
                var html = '';
                var results = $('results > page', xml);
                for (var i = 0; i < results.length; i++) {
                    html += '<a href=\"' + results[i].getAttribute('href') + '\">' + results[i].getAttribute('title') + '</a>';
                }
                html += '';
                html += '<div class="minor-help-text">For more results, click Search.</span>';
                if (results.length == 0) html = '';
                var node = $(html);
                var posdata = query.position();

                $('div#ffQuickSearch').html(html);
                if (html == '') $('div#ffQuickSearch').hide();
                else $('div#ffQuickSearch').show();
            }
            var lastSearchQuery = '';
            liveChange(query[0], function() {
                if (query[0].value.length > 2 && query[0].value != lastSearchQuery) {
                    $.ajax({
                        url: "quicksearch.aspx?site_id=" + site_id + "&query=" + escape(query[0].value),
                        dataType: 'xml',
                        type: "GET",
                        data: {},
                        success: function(data, text) {
                            showResults(data);
                        },
                        error: function() { }
                    });
                    lastSearchQuery = query[0].value;
                }
            }, 500, function() {
                if (query[0].value.length > 2) {
                    if (query[0].value != lastSearchQuery)
                        showSearching();
                } else {
                    hideSearching();
                }
            });
        }
        // set up dashboard if there
        $('div.dashboard-feed li').hover(function() {
            $(this).addClass('hover');
        }, function() {
            $(this).removeClass('hover');
        });
        $('div.dashboard-subscriptions li').hover(function() {
            $('button', this).show();
        }, function() {
            $('button', this).hide();
        });
        $('div.dashboard-subscriptions li button').click(function() {
            var t = this;
            DashboardUnsubscribe(this.parentNode.id.substring(14), function() {
                $('li.' + t.parentNode.id).hide(500);
                $(t.parentNode).hide(500);
            });
        });
        $('div.dashboard-subscriptions li').hover(function() {
            $('li.' + this.id).addClass('hover');
        }, function() {
            $('li.' + this.id).removeClass('hover');
        });
        // wireup special edit in MS Office tools if supported
        try {
            var openDoc = new ActiveXObject("SharePoint.OpenDocuments.3");
            if (openDoc == null) openDoc = new ActiveXObject("SharePoint.OpenDocuments.2");
            if (openDoc) {
                $('a:link').live('click', function() {
                    if ($(this).attr('href').substring(0, 13) == "resource.aspx") {
                        $(this).attr('href', $(this).attr('href') + "&officeint=on");
                    }
                });
            }
        } catch (e) { }
    })
};
function ffStoreData(t, n, d) {
	$(t + ':last').data(n, d);
}
function ffGetData(id, n) {
	return $('#' + id).data(n);
}
function setupTextValidation(el, regex) {
	if (!regex) { regex = /[0-9]/; };
	$(el).bind("keypress", function(evt) { 
		var charCode = evt.which;
		if (charCode < 13) return true;
		var keyChar = String.fromCharCode(charCode); 
		return regex.test(keyChar);
	});
}
function pulselight(el) {
    highlight(el, true);
    setTimeout(function() { highlight(el, false); }, 200);
}
function liveChange(el, fn, delay, immediatefn) {
    var timer;
	if (!delay) delay = 500;
	$(el).keyup(function() {
	    if (immediatefn) immediatefn();
	    if (timer) clearTimeout(timer);
	    var me = $(this);
	    if (!fn) fn = function() { me.trigger('change'); };
	    timer = setTimeout(fn, delay);
	});
}
function makeResourceList(id, sort_type, sort_reverse) {
    $(function() {
        var container = $('#' + id);
        $('tr.resource-list-folder', container).live('click', function(e) {
            if ($(e.target).parents('tr')[0] != $(this)[0]) return;
            var id = $(this).get(0).id.substring(20);
            var el = $('td', this)[1];
            var tb = $('table', el);
            if (tb.length > 0) {
                tb.toggle(300);
                return false;
            }
            $.ajax({
                url: "Admin/editor/serverside/resourcelist.aspx?fid=" + id + "&st=" + sort_type + "&sr=" + sort_reverse,
                dataType: 'xml',
                type: "POST",
                success: function(data, text) {
                    var items = data.getElementsByTagName('resource');
                    var folders = data.getElementsByTagName('resourcefolder');
                    var html = '<table class="resource-list" id="ffResourceListFolder' + id + '" style="display: none">';
                    for (var i = 0; i < folders.length; i++) {
                        html += '<tr class="resource-list-folder" id="ffResourceListFolder' + folders[i].getAttribute('id') + '"><td valign="top"><img src="' + escape(folders[i].getAttribute('icon')) + '"></td><td valign="top"><a href="#">' + folders[i].getAttribute('name') + '</a></td><td valign="top"></td></tr>';
                    }
                    for (var i = 0; i < items.length; i++) {
                        html += '<tr><td valign="top"><img src="' + escape(items[i].getAttribute('icon')) + '"></td><td valign="top"><a href="resource.aspx?id=' + items[i].getAttribute('id') + '">' + items[i].getAttribute('name') + '</a></td><td valign="top">' + items[i].getAttribute('description') + '</td></tr>';
                    }
                    html += '</table>';
                    var node = $(html);
                    $(el).append(node);
                    node.ffShow(300);

                },
                error: function() { },
                data: {}
            });
            return false;
        });
    });
}
function buildToolbox(tools, extendheight) {

	var COMPONENT_HELPER_URL = 'Admin/editor/serverside/componentproperties.aspx?id=';
	
	var componentTypes = {};
	var componentDirty = true;
	if (!extendheight) extendheight = '';
	var selectedComponent = -1;
	var selectedPage = -1;
	var pageWrite = false;
	
	var html = '<div id=\'ffToolbox\'>';
	html += '<h2>Edit Toolbox</h2>';
	for (var i = 0; i < tools.length; i++) {
		if (tools[i].items) {
			html += '<h3><img src=\'Templates/acc-expand.gif\'> ' + tools[i].l + '</h3>';
			html += '<div style=\'display: none\'>';
			for (var j = 0; j < tools[i].items.length; j++) {
			    var accesskey = '';
			    if (tools[i].items[j].ak && (tools[i].items[j].ak != '')) { accesskey = ' accesskey="' + tools[i].items[j].ak + '"'; }
				html += '<a href=\'' + tools[i].items[j].u + '\' title="' + tools[i].items[j].h + '"' + accesskey + '>' + tools[i].items[j].l + '</a>';
			}
			html += '</div>';
		}
		else {
		    var accesskey = '';
		    if (tools[i].ak && (tools[i].ak != '')) { accesskey = ' accesskey="' + tools[i].ak + '"'; }
			if (tools[i].u.substring(0,5) == 'http:')
			    html += '<a href=\'' + tools[i].u + '\' class=\'promote-tool\' target=\'_new\' title="' + tools[i].h + '"' + accesskey +'>' + tools[i].l + '</a>';
			else
			    html += '<a href=\'' + tools[i].u + '\' class=\'promote-tool\' title="' + tools[i].h + '"' + accesskey + '>' + tools[i].l + '</a>';
		}
	}
	
	html += '<h3 id=\'ffTBC\'><img src=\'Templates/acc-expand.gif\'> Component</h3>';
	html += '<div style=\'display: none\' id=\'ffTBCD\'><span>Click a component to select it</span><span style=\'display: none\'>';
	html += '<a href=\'#\' id=\'ffTBCM\' title=\'Change the contents of this component\'>Modify component</a>';
	html += '<span id=\'ffTBCPW\'><a href=\'#\' id=\'ffTBCD\'>Delete component</a>';
	html += '<a href=\'#\' id=\'ffTBCP\' title=\'Change who can see or edit this component\'>Modify permissions</a>';
	html += '<label for=\'ffTBCH\' title=\'Optionally enter some header text to appear above the component in the page\'>Header</label>';
	html += '<input id=\'ffTBCH\' type=\'text\' title=\'Optionally enter some header text to appear above the component in the page\'>';
	html += '<label for=\'ffTBCW\' title=\'Choose whether other components on the page should wrap around this one\'>Wrapping</label>';
	html += '<select id=\'ffTBCW\' title=\'Choose whether other components on the page should wrap around this one\'><option>No wrapping</option><option>Wrap to right</option><option>Wrap to left</option></select>';
	html += '<span id=\'ffTBCWs\'><label for=\'ffTBCWw\'>Width</label>';
	html += '<input id=\'ffTBCWw\' type=\'text\' size=\'3\' style=\'width: 50px; float: left; margin-right: 3px\'> pixels</span>';
	html += '<label for=\'ffTBCT\' title=\'Select the style of this component - this will affect how it is displayed in the page, as determined by the template\'>Style</label>';
	html += '<select id=\'ffTBCT\' title=\'Select the style of this component - this will affect how it is displayed in the page, as determined by the template\'></select>';
	html += '<span id=\'ffTBCCc\'><label for=\'ffTBCC\'>Container</label>';
	html += '<select id=\'ffTBCC\'></select></span>';
	html += '</span></span></div>';
	
		
	function selectComponent(id) {
		if (selectedComponent == id) return;
		else componentDirty = true;
		selectedComponent = id;
		if ($('h3#ffTBC + div').is(':visible') && expanded)
			selectComponentLive();
		$('h3#ffTBC + div > span:last').hide();
		if (selectedComponent > -1) {
			$('h3#ffTBC + div > span:first').text('Loading...').show();
		}
		else
			$('h3#ffTBC + div > span:first').text('Click an editable component to select it').show();
         		 
	}
	function selectComponentLive() {
	 $.ajax({
               			   url: ffBaseURL + COMPONENT_HELPER_URL + selectedComponent,
               			   dataType: 'xml',
                		  type: "GET",
                		  cache: false,
                		  success: function(data) { fillProperties(data); },
               			   error: function(){  }
         		 });
        componentDirty = false;
	}
	
	
	
	function updateWrapDisplay() {
	    document.getElementById('ffTBCWs').style.display = (document.getElementById('ffTBCW').selectedIndex > 0) ? '' : 'none';
	    if ((document.getElementById('ffTBCWs').style.display == '') && (document.getElementById('ffTBCWw').value == '')) {
		var width = 200;
	        document.getElementById('ffTBCWw').value = width;
	    }
	}
	
	function fillProperties(xml) {

		document.getElementById('ffTBCH').value = $('header', xml).text();
		selectedPage = $('component', xml).attr('page_id');
		pageWrite = ($('component', xml).attr('page_write') == 'yes');
				
		if (pageWrite) {
		
			$('span#ffTBCPW').show();
		
			document.getElementById('ffTBCW').selectedIndex = parseInt($('float', xml).text());
			document.getElementById('ffTBCWw').value = ($('width', xml).text() == '0') ? '' : parseInt($('width', xml).text());
			updateWrapDisplay();
			
			var types = document.getElementById('ffTBCT');
			types.options.length = 0;
			var i = 0;
			var sel = 0;
			componentTypes = {};
			$('type', xml).each(function() {
				types.options[types.options.length] = new Option(this.getAttribute('label'), this.getAttribute('id'));
				componentTypes['ff' + this.getAttribute('id')] = this.getAttribute('cssclass');
				if (this.getAttribute('selected') == 'yes') { sel = i; prevtype = this.getAttribute('id'); }
				i++;
			});
			types.selectedIndex = sel;
			
			var containers = document.getElementById('ffTBCC');
			containers.options.length = 0;
			i = 0;
			sel = 0;
			$('container', xml).each(function() {
				containers.options[containers.options.length] = new Option(this.getAttribute('label'), this.getAttribute('id'));
				if (this.getAttribute('selected') == 'yes') { sel = i; prevtype = this.getAttribute('id'); }
				i++;
			});
			containers.selectedIndex = sel;
			
		} else {
			$('span#ffTBCPW').hide();
			// only show the modify button if you can't write the page
		}
		
		$('h3#ffTBC + div > span:last').show();
		$('h3#ffTBC + div > span:first').hide();
	}
	
	function setContainer(cont) {
		if (selectedComponent == -1) return;
		var c = $('#ffComponent_' + selectedComponent);
		var existing = c.parent()[0].id.substring(11);
		if (existing != cont) {
			$('#ffContainer' + cont).append(c);
			c[0].scrollIntoView();
			updateTargetContainer(selectedPage, document.getElementById('ffContainer' + cont), true);
			ffEventHandler.pushEvent('dominsert');
		}
		pulselight(c[0]);
	}
	
	function setWrap(type, width) {
		if (selectedComponent == -1) return;
		var c = $('#ffComponent_' + selectedComponent);
		if (type == 0) {
			c.removeClass('floatedcomponent');
			c.removeClass('floatedcomponentedit');
			c.css({ 'width': '', float : '' });
		} else {
			c.addClass('floatedcomponent');
			c.addClass('floatedcomponentedit');
			var floater = 'right';
			if (type == 1) floater = 'left';
			if (width == '') width = '0';
			c.css({ 'float': floater, 'width': width + 'px' });
		}
		pulselight(c[0]);
	}
	var prevtype = '';
	function setType(tag, type) {
		if (selectedComponent == -1) return;
		var c = $('#ffComponent_' + selectedComponent);
		
		// run an unwireup function if there is one
		if (c[0].ffComponentChangeType)
		    c[0].ffComponentChangeType(c[0]);
		    
		c.removeClass(componentTypes['ff'+prevtype]);
		c.addClass(componentTypes['ff' + type]);
		ffEventHandler.pushEvent('dominsert');
		prevtype = type;
		pulselight(c[0]);
	}
	
	
	html += '</div>';
	$('body').append(html);

	$('select#ffTBCW, input#ffTBCWw').change(function() {
	    var val = document.getElementById('ffTBCWw').value;
	    if (val == '') val = '200';
	    setWrap(document.getElementById('ffTBCW').selectedIndex, val);
	    updateWrapDisplay();
	});
	
	updateWrapDisplay();
	$('select#ffTBCT').change(function() {
		setType('div', this.options[this.selectedIndex].value);
	});
	$('select#ffTBCC').change(function() {
		setContainer(this.options[this.selectedIndex].value);
	});
	liveChange('input#ffTBCWw', function() { setWrap(document.getElementById('ffTBCW').selectedIndex, document.getElementById('ffTBCWw').value); });
	
	// post back handling for everything except container change
	$('input#ffTBCH, select#ffTBCW, input#ffTBCWw, select#ffTBCT').change(function () {
		$.ajax({
			url: ffBaseURL + COMPONENT_HELPER_URL + selectedComponent,
			dataType: 'script',
			type: 'POST',
			data: 'header=' + escape(document.getElementById('ffTBCH').value) + '&type=' + escape(document.getElementById('ffTBCT').options[document.getElementById('ffTBCT').selectedIndex].value) + '&float_type=' + document.getElementById('ffTBCW').selectedIndex + '&float_width=' + escape(document.getElementById('ffTBCWw').value),
			error: function(){ alert('Error saving component properties.  Check your internet connection and try refreshing the page.');  }			
         });
	});
	
	var txt = document.getElementById('ffTBCH');
	liveChange('input#ffTBCH', function() { 
		if (selectedComponent == -1) return;
		var c = $('#ffComponent_' + selectedComponent);
		var header = $('h2.componentheader', c);
		if (header.length == 0) {
			if (txt.value != '')
				$('.componentedit', c).after('<h2 class=\'componentheader\'>' + txt.value + '</h2>');
		} else {
			if (txt.value == '')
				header.remove();
			else
				header.text(txt.value);
		}
	});
	setupTextValidation('#ffTBCWw');
	
	var pos = {};
	var tb = $('div#ffToolbox');
	var origheight = $('div#ffToolbox').outerHeight();
	var scrollAdjust = false;
	var expanded = false;

	function getcatid(obj) {
	    var text = obj.text();
	    text = text.replace(/\s/g, "");
	    if (text.indexOf("(") > -1)
	        text = text.substring(0, text.indexOf("("));
	    return text;
	}
	
	function place() {
		if ($.browser.msie && ($.browser.version < 7)) {
			// very strange IE6 bug only moves on a dom change, so we alter by a random number
    	    tb.css({ 'right': Math.round(10 + Math.random()) + 'px', 'bottom': Math.round(10 + Math.random()) + 'px' });
		}
		else
			tb.css({ 'right': (10-$(window).scrollLeft()) + 'px', 'bottom': (10-$(window).scrollTop()) + 'px' });
	}
	
	$('a#ffTBCD').click(function() {
		if (PageMakeupDelete(selectedPage, document.getElementById('ffComponentEdit' + selectedComponent)))
			selectComponent(-1);
		return false;
	});
	
	$('a#ffTBCP').click(function() {
		ShowDialog('Admin/permissionsHtml.aspx?id=' + selectedComponent);
		return false;
	});
	
	$('a#ffTBCM').click(function(event) {
		ModifyComponent(document.getElementById('ffComponentEdit' + selectedComponent), ffGetData('ffComponent_' + selectedComponent, 'ffcomponenttype'), event);
		return false;
	});
	
	function toggle(force) {
		if (force) {
		    expanded = true;
			tb.css({ 'height': 'auto' });
		} else {
			if (!expanded)
				tb.css({ 'height': 'auto' });
			else
				tb.css({ 'height': origheight + 'px' });
			expanded = !expanded;

        }
        if (expanded) {
            $($("h2", tb)[0]).addClass('expanded');
        } else {
            $($("h2", tb)[0]).removeClass('expanded');
        }
		setTempCookie('ffToolboxOpen', expanded);
		if (!expanded)
			setTempCookie('ffToolbox', '');
	}
	
	$('div#ffToolbox h2').click(function() {
		toggle();
	});

	$('div#ffToolbox h3').click(function(ev) {
	    setTempCookie('ffToolbox', '');
	    var show = $(this).next();
	    $('div#ffToolbox div').each(function() {
	        if (($(this).prev().is(':visible')) && ($(this).get(0) == show.get(0)) && ((!$(this).is(':visible')) || ($(this).prev().data('ffforceshow')))) {
	            $(this).prev().data('ffforceshow', false);
	            $(this).prev().find('img')[0].src = 'Templates/acc-expanded.gif';
	            $(this).ffShow(100);
			setTempCookie('ffToolbox', getcatid($(this).prev()));
	        }
	        else {
	            $(this).prev().find('img')[0].src = 'Templates/acc-expand.gif';
	            $(this).hide(20);
	        }
	    });
	    if ($(this).is('h3#ffTBC') && componentDirty) {
	        if (selectedComponent == -1) {
	            $('h3#ffTBC + div > span:last').hide();
	            $('h3#ffTBC + div > span:first').text('Click an editable component to select it').show();
	        }
	        else selectComponentLive();
	    }
	});

	if ((document.compatMode == "BackCompat") || ($.browser.msie && ($.browser.version < 7))) {
		tb.css('position', 'absolute');
		scrollAdjust = true;
		$(function() { place(); });
		$(window).scroll(function() {
			place();
		});
	}
	
	var anyEditable = false;
	$('.component, .floatedcomponent').each(function() {
	    var id = $(this)[0].id.substring(12);
	    var thisEditable = document.getElementById('ffComponentEdit' + id);
	    if (thisEditable) anyEditable = true;
	    this.ffSelect = function(force) {
	        if (thisEditable) {
	            var newid = $(this)[0].id.substring(12);
	            if (force) selectedComponent = -1;
	            selectComponent(newid);
	        } else {
	            selectComponent(-1);
	        }
	    };
	}).click(function() {
	    this.ffSelect();
	});
    
	if (!anyEditable)
		$('h3#ffTBC').hide().next().hide();

    var sel = getCookie('ffToolbox');
	if (sel) {
	    $('div#ffToolbox h3').each(function() {
	        if (getcatid($(this)) == sel) { $(this).click(); }
	    }); }
		
	var open = getCookie('ffToolboxOpen');
	if (open == 'true')
		toggle(true);
		
	
		
	window.ComponentProperties = function(comp) {
		$('h3#ffTBC').data('ffforceshow', true);
		$('h3#ffTBC').trigger('click');
		if (!expanded)
			$('div#ffToolbox h2').trigger('click');
		
		highlightComponent(comp, false);
	};
}
function makeListExpandable(node) {
	$(function() {	
		var ul, toggleLink;
		$("li",node).each(
		function()
		{
			if(this.parentNode != node) return;
			ul = $("ul",this).get(0);
			if(ul)
			{
				$("ul",this).hide();
				toggleLink = document.createElement("a");
				toggleLink.href = "#";
				$(toggleLink).addClass("toggle");
				$(ul.parentNode.childNodes[0]).wrap(toggleLink);
				$("a.toggle", ul.parentNode).click(
					function()
					{
						$(">ul",this.parentNode).toggle(500);
						return false;
					}
				);
				makeListExpandable(ul);
			}
		}
	);
	});
}
function updateTargetContainer(page_id, container, forcerefresh) {
	ffOrderComponents();				
	 $.ajax({
		   url: "Admin/componentsMove.aspx",
		   dataType: 'script',
		  type: "POST",
		  data: 'page_id=' + page_id + '&container=' + $(container).get(0).id + '&' +$(container).sortable("serialize"),
		   error: function(){ alert('Error moving component.  Check your internet connection and try refreshing the page.'); }
	});
	if (forcerefresh) container.sortable('refresh');
}
function makeContainerSortable(page_id) {
    $(function() {
        // workaround IE overflow bug
        if ($.browser.msie) {
            $('.ff-container').each(function() {
                var p = this.parentNode;
                while (p && (p.tagName.toLowerCase() != 'body') && (p.tagName.toLowerCase() != 'html')) {
                    var overflow = getStyle(p, 'overflowY');
                    if ((overflow == 'auto') || (overflow == 'scroll')) {
                        p.style.position = 'relative';
                    }
                    p = p.parentNode;
                }
            });
        }

        $('.ff-container').sortable({ cursor: 'move', connectWith: $('.ff-container'), tree: true, revert: true, scroll: true, handle: '.ffDragHandle',
            tolerance: 'pointer',
            items: '>.component,>.floatedcomponent',
            placeholder: 'ff-containerplaceholder',
            start: function(e, ui) {
                $('.ff-container').css('border', 'dashed 2px #eeeeee');
                highlight(ui.item.get(0), false, true); highlightLockDrag = true; ui.item.find("script").remove();
            },
            stop: function(e, ui) {
                $('.ff-container').css('border', '');
                highlightLockDrag = false;
            },
            over: function(e, ui) {
                $(this).css('border', 'dashed 2px #bbbbbb');
            },
            out: function(e, ui) {
                $(this).css('border', 'dashed 2px #eeeeee');
            },
            change: function(e, ui) {
                var floatsetting = ui.item.css('float').toUpperCase();
                if ((floatsetting == 'LEFT') || (floatsetting == 'RIGHT')) {
                    ui.placeholder.css('float', floatsetting);
                    ui.placeholder.css('width', ui.item.width() + 'px');
                    ui.placeholder.css('height', ui.item.height() + 'px');
                }
            },
            update: function(e, ui) {
                if (ui.sender || (ui.item.parent().get(0).id == $(this).get(0).id)) {
                    updateTargetContainer(page_id, this);
                    // force 'select' the new component to help the properties dialog
                    ui.item[0].ffSelect(true);
                    if (($.browser.msie) && ($.browser.version < 8)) {
                        // ie bug
                        ui.item[0].style.position = 'relative';
                        ui.item[0].style.position = '';
                    }
                }
            }
        });
    });
}
var ffEventHandler = {
	eventList: {},
	registerEvent: function(name, fn, runNow) {
		if (this.eventList[name]) {
			this.eventList[name].push(fn);
		} else {
			this.eventList[name] = [ fn ];
		}
		if (runNow) fn();
	},
	pushEvent: function (name) {
		var me = this;
		if (me.eventList[name]) {
			for (var i = 0; i < me.eventList[name].length; i++)
				me.eventList[name][i]();
		}
	}
};

$(function() {
    ffEventHandler.registerEvent("dominsert", function() {
        ffRewriteAnchorLinks();
    }, true);
});
        
function checkStyles(href) {
	for (var i = 0; i < document.styleSheets.length; i++) {
		if (document.styleSheets[i].href && (document.styleSheets[i].href.length >= href.length)) {
			if (document.styleSheets[i].href.substring(document.styleSheets[i].href.length - href.length).toUpperCase() == href.toUpperCase())
				return;
		}
	}
	// not found, attach
	var l = this.document.createElement('link');
	l.setAttribute('type', 'text/css');
	l.setAttribute('href', href);
	l.setAttribute('rel', 'stylesheet');
	this.document.getElementsByTagName('head')[0].appendChild(l);   
}
function getStyle(o, prop){
	if (o.currentStyle) return o.currentStyle[prop]
	else if (document.defaultView && document.defaultView.getComputedStyle) return document.defaultView.getComputedStyle(o, "")[prop]
	else return o.style[prop];
}
function showEdit(id, over) {
	if (document.getElementById(id)) {
		document.getElementById(id).style.visibility = over ? '' : 'hidden';
	}
}
function setupComponentEdit(obj) {
    var p = $(obj).parent()[0];
    $(obj).parent().hover(function(e) { showComponentEdit(p, true); }, function(e) { showComponentEdit(p, false); });
    $(obj).dblclick(function() { showComponentEdit(p, false); });
    $('img', $(obj)).hover(function() { highlight(p, true) }, function() { highlight(p, false) });
}
if (window.jQuery) {
    jQuery.fn.ffShow = function(timing) {
        return this.each(function() {
            $(this).show(timing, function() { $(this).css('zoom', ''); });
        });
    };
}
function setupSeeMore(container) {
    $(function() {
        var items = $('.see-more', container).length;
        var el = $("<a href='#' class='see-more-button'>See " + items + " more...</a>");
        el.click(function() {
            $('.see-more', container).ffShow(500);
            $(this).hide();
            return false;
        });
        $(container).append(el);
    });
}
function setupCollapsibleButtons(classname, firstsel) {
    $(function() {
        var selectedButton;
        var allitems = $('.' + classname + ' button');
        var btnclicker = function() {
            if ($(this).is('.depressed')) {
                $(this).removeClass('depressed');
                $(this).next().hide();
            }
            else {
                $(this).addClass('depressed');
                $(this).next().show();
                $(this)[0].scrollIntoView();
                if ($(this).data('reveal')) {
                    $(this).data('reveal')();
                }
            }
        }
        allitems.each(function() {
            $(this).click(btnclicker);
        });
        window.showPageEdit = function(on) {
            if (!on) {
                allitems.each(function() {
                    if ($(this).is('.depressed')) {
                        $(this).removeClass('depressed');
                        $(this).next().hide();
                    }
                });
            }
        };
        if (firstsel) {
            $(allitems[0]).addClass('depressed');
            $(allitems[0]).next().show();
        }
    });
}
function showComponentEdit(pobj, show) {
    var obj = $('>.componentedit', pobj)[0];
	if(!obj) return;
    obj.style.display = show ? 'inline' : 'none';
    if (show) {
        var t = getTop(obj);
        var tp = getTop(pobj);
        var tpmt = parseInt($(pobj).css('margin-top'));
        tpmt = (isNaN(tpmt)) ? 0 : tpmt;
        var squeeze = t - (tp+tpmt);
        obj.style.marginTop = (-squeeze) + 'px';
    }
}

function isChildOf(parent, child) {
	if (parent == child) return false;
      
	while (child && child != parent)
		child = child.parentNode;

   return child == parent;
}
function getEventTarget(e) {
   if (e.target) {
      return e.target;
   } else if (e.srcElement) {
      return e.srcElement;
   }
   return null;
}
function getComponentIdFromElement(obj) {
	var id = -1;
	var i = 0;
	while ((i < 10) && obj.parentNode) {
		if (obj.id.substring(0, 15) == 'ffComponentEdit') {
			id = obj.id.substring(15);
			break;
		}
		obj = obj.parentNode;
		i++;
	}
	return id;
}
function highlightComponent(obj, show) {
	var id = getComponentIdFromElement(obj);
	if (id > -1) highlight(document.getElementById('ffComponent_' + id), show);
}
function highlightPage(id, show) {
	highlight(document.getElementById('ffPage' + id), show);
}
function highlightComment(id, show) {
	highlight(document.getElementById('ffComment' + id), show);
}
function createAjax() {
	if(typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
    }
    else if(window.ActiveXObject) {
            var aVersions =
               [
                "MSXML2.XmlHttp.5.0",
                "MSXML2.XmlHttp.4.0",
                "MSXML2.XmlHttp.3.0",
                "MSXML2.XmlHttp",
                "Microsoft.XmlHttp"
					];
           for(var i = 0; i < aVersions.length; i++)
           {
              try
           {
              var oXhr = new ActiveXObject(aVersions[i]);
              return oXhr;
           }
              catch(oError) {}
           }
            
            return null;
      }
      else
         return null;
 }
var ffDeleteObj = null;
function ffMovedComponent(id, direction) {
	location.reload();
}
var ffBlogPageData = new Object();
function ffBlogPage(id, pageid) {
	for (tag in ffBlogPageData[''+id]) {
		for (var i = 0; i < ffBlogPageData[''+id][tag].length; i++)
			xBrowserGetElement(ffBlogPageData[''+id][tag][i]).style.display = (tag == pageid) ? '' : 'none';
	}
}
function ffReloadComponent(oldid, newid) {
	var ajax = createAjax();
	if (ajax != null) {
		ajax.open('GET', ffBaseURL + 'blank.aspx?id=' + newid + '&view=xml', true);
		ajax.onreadystatechange = function() {
		    if (ajax.readyState == 4) {
		        if ((ajax.status >= 200) && (ajax.status < 300)) {
		            if (ajax.responseXML.getElementsByTagName('component').length > 0) {
		                var editNode;
		                var headerNode;
		                var inplace = true;
		                if (savedNodes) {
		                    for (var i = 0; i < savedNodes.length; i++) {
		                        if (savedNodes[i].id == 'ffComponentEdit' + oldid)
		                            editNode = savedNodes[i];
		                        else if (savedNodes[i].className == 'componentheader')
		                            headerNode = savedNodes[i].cloneNode(true);
		                    }
		                } else {
		                    inplace = false;
		                    if (!highlightObj) highlightObj = document.getElementById('ffComponent_' + oldid);
		                    for (var i = 0; i < highlightObj.childNodes.length; i++) {
		                        if (highlightObj.childNodes[i].id == 'ffComponentEdit' + oldid) {
		                            editNode = highlightObj.childNodes[i];
		                        }
		                        else if (highlightObj.childNodes[i].className == 'componentheader')
		                            headerNode = highlightObj.childNodes[i].cloneNode(true);
		                    }
		                }
		                var newEditNode = editNode.cloneNode(true);
		                newEditNode.id = 'ffComponentEdit' + newid;
		                highlightObj.innerHTML = ajax.responseXML.getElementsByTagName('component')[0].firstChild.nodeValue;
		                if (headerNode)
		                    highlightObj.insertBefore(headerNode, highlightObj.firstChild);
		                highlightObj.insertBefore(newEditNode, highlightObj.firstChild);
		                setupComponentEdit(newEditNode);
		                ffEventHandler.pushEvent('dominsert');
		                highlightObj.id = 'ffComponent_' + newid;
		                // 'select' the new component to help the properties dialog
		                if (highlightObj.ffSelect)
		                    highlightObj.ffSelect();
		                if (inplace) {
		                    highlightLock = false;
		                    showComponentEdit(highlightObj, false);
		                    highlight(highlightObj, false);
		                } else {
		                    HideDialog();
		                }
		            }
		        }
		        else
		            location.reload();
		    } else return false;
		}
		ajax.send(null);
	} else {
		location.reload();
	}
}
function ffScrollTicker(id) {

	var div = document.getElementById('ffTickerContents' + id);
	if (div) {
		if (div.style.left == '') {
			div.style.visibility = '';
			div.style.left = document.getElementById('ffTickerFrame' + id).offsetWidth + 'px';
			div.style.width = document.getElementById('ffTickerSpan' + id).offsetWidth + 'px';
		}
		var left = parseInt(div.style.left);
		left -= 1;
		if (left < -div.offsetWidth) {
			left = document.getElementById('ffTickerFrame' + id).offsetWidth;;
		}
		div.style.left = left + 'px';
	}

}
function ffOrderComponents() {
	$('.ff-container').each(function() {
		$(this).children(':even').removeClass('even').addClass('odd');
		$(this).children(':odd').removeClass('odd').addClass('even');
	});		
}
function ffDeletedComponent(id) {
	deleteAnim(document.getElementById('ffComponent_' + id), ffOrderComponents);
}
function ffDeletedComment(id) {
	deleteAnim(document.getElementById('ffComment' + id));
}
function deleteAnim(obj, fn) {
	if (!obj) { obj = ffDeleteObj; }
	if (ffDeleteObj == null) {
		//alert('constructing');
		ffDeleteObj = obj;
		obj.style.height = obj.offsetHeight + 'px';
		obj.style.overflow = 'hidden';
		//alert('hi');
		obj.heightStep = Math.round(obj.offsetHeight / 20);
		//alert(obj.heightStep);
	}
	var height = parseInt(obj.style.height);
	height -= obj.heightStep;
	if (height <= 0) {
		obj.parentNode.removeChild(obj);
		ffDeleteObj = null;
		if (fn) fn();
	} else {
		obj.style.height = height + 'px';
		setTimeout(function() { deleteAnim(obj, fn) }, 50);
	}
}
function highlight(obj, show, noanimate) {

    ffLog('highlight ' + show);
    
	if (highlightLockDrag)
		return;
		
	// check the whole DOM is ready in IE (avoids IE bug)
	if(typeof document.documentElement.doScroll != 'undefined') {
	try {	
		document.documentElement.doScroll('left');
	} catch (e) {
		return;
    } 
    }

    highlightDirection = show;
   
	if (!show && !highlightLock) {
	    clearTimeout(highlightTimer);
		highlightAnimation(false, noanimate);
		highlightObj = null;
		return;
	} else if (!highlightLock) {
		try {
			clearTimeout(highlightTimer);
		} catch(e) {}
	}
	if (!show)
	    return;

    highlightObj = obj;

    var top = getTop(obj); var left = getLeft(obj); var width = $(obj).outerWidth(true); var height = $(obj).outerHeight(true);

	if (obj.id.substring(0,6) == 'ffPage') {
		// special width calculation
		var editicons = document.getElementById('ffPageEdit' + obj.id.substring(6));
		if (editicons) {
		var specleft = getLeft(editicons) - left;
		if ((specleft + editicons.offsetWidth) > width) {
			width = specleft + editicons.offsetWidth;
		} }
	}

	var bodyHeight = ffGetDimensions().pageHeight;
	var bodyWidth = ffGetDimensions().pageWidth - 1;


	appendMaskingDiv(createMaskingDiv(0, 0, bodyWidth, top, 'above'));
	appendMaskingDiv(createMaskingDiv(top+height, 0, bodyWidth, bodyHeight-(top+height), 'below'));
	appendMaskingDiv(createMaskingDiv(top, 0, left, height, 'left'));
	appendMaskingDiv(createMaskingDiv(top, width+left, bodyWidth-(width+left), height, 'right'));
	
	highlightAnimation(true, noanimate);

}
function SendFeedback() {
	ShowDialog('Admin/sendfeedback.aspx?url=' + escape(location.href));
}
function ffGetScrollTop () {
    //if (document.body.parentNode.scrollTop) return document.body.parentNode.scrollTop; else	return document.body.scrollTop;
    return $(window).scrollTop();
}

function ffGetScrollLeft() {
    //if (document.body.parentNode.scrollLeft) return document.body.parentNode.scrollLeft; else	return document.body.scrollLeft;
    return $(window).scrollLeft();
}

function ffGetDimensions() {
	var ret = {};
	if (document.compatMode == "BackCompat") {
		ret.viewportWidth = document.body.clientWidth;
		ret.viewportHeight = document.body.clientHeight;
		ret.pageHeight = Math.max(document.body.scrollHeight, document.body.clientHeight);
		ret.pageWidth = Math.max(document.body.scrollWidth, document.body.clientWidth);
	
	} else {
	if (document.documentElement && document.documentElement.clientHeight) {
		ret.viewportWidth = document.documentElement.clientWidth;
		ret.viewportHeight = document.documentElement.clientHeight;
	}
	else {
		ret.viewportWidth = document.body.clientWidth;
		ret.viewportHeight = document.body.clientHeight;
	}
	if (document.body.scrollHeight > document.body.offsetHeight) {
		ret.pageWidth = document.body.scrollWidth;
		ret.pageHeight = document.body.scrollHeight;
	} else {
		ret.pageWidth = document.body.offsetWidth;
		ret.pageHeight = document.body.offsetHeight;
	}
	if (document.documentElement.scrollHeight > document.documentElement.offsetHeight) {
		ret.pageWidth = document.documentElement.scrollWidth;
		ret.pageHeight = document.documentElement.scrollHeight;
	} else {
		ret.pageWidth = document.documentElement.offsetWidth;
		ret.pageHeight = document.documentElement.offsetHeight;
	}
}

    /* IE 8 fixes */

    if (((ret.viewportWidth - ret.pageWidth) < 5) && ((ret.viewportWidth - ret.pageWidth) > 0)) ret.pageWidth = ret.viewportWidth;
    if (((ret.viewportHeight - ret.pageHeight) < 5) && ((ret.viewportHeight - ret.pageHeight) > 0)) ret.pageHeight = ret.viewportHeight;

	if (ret.pageWidth < ret.viewportWidth) ret.pageWidth = ret.viewportWidth;
	if (ret.pageHeight < ret.viewportHeight) ret.pageHeight = ret.viewportHeight;
	return ret;
}

function ffInplaceHeightHint(height, fn) {
	if ((!dialogNode) || (dialogNode.style.display == 'none')) return;
	var newheight = 300;
	var offset = 50;
	if (height > newheight) newheight = Math.min(height, (ffGetDimensions().viewportHeight+ffGetScrollTop()) - getTop(dialogNode));
	var node = highlightObj;
	dialogNode.height = newheight;
	highlight(highlightObj, false, true);
	highlight(node, true, true);
	if (fn) fn();
}

var highlightObj;
var highlightMaxOpacity = 0.2;
var highlightSteps = 4;
var highlightTimer;
var highlightHelperObj;
var highlightLock = false;
var highlightLockDrag = false;
var highlightDirection = true;

function highlightAnimation(forward, noanimate) {

    ffLog('highlightAnimation ' + forward + ' ' + highlightDirection);
    if (forward != highlightDirection) { return; }

	var again = true;
	var opacity;
		
	if (noanimate) {
		if (forward) {
			opacity = highlightMaxOpacity;
			again = false;

    } else {
                if (forward != highlightDirection) return;
				if (document.getElementById('ffMaskabove') && document.getElementById('ffMaskbelow') && document.getElementById('ffMaskleft') && document.getElementById('ffMaskright')) {
					document.body.removeChild(document.getElementById('ffMaskabove'));
					document.body.removeChild(document.getElementById('ffMaskbelow'));
					document.body.removeChild(document.getElementById('ffMaskleft'));
					document.body.removeChild(document.getElementById('ffMaskright'));
				}
				return;
		}
	} else {

	    opacity = getOpacity(document.getElementById('ffMaskabove'));
	
		if (forward) {
			opacity += highlightMaxOpacity / highlightSteps;
			if (opacity >= highlightMaxOpacity) again = false;
		} else {
			opacity -= highlightMaxOpacity / highlightSteps;
			if (opacity <= 0) {
			    opacity = 0;
			    if (forward != highlightDirection) return;
				if (document.getElementById('ffMaskabove') && document.getElementById('ffMaskbelow') && document.getElementById('ffMaskleft') && document.getElementById('ffMaskright')) {
					document.body.removeChild(document.getElementById('ffMaskabove'));
					document.body.removeChild(document.getElementById('ffMaskbelow'));
					document.body.removeChild(document.getElementById('ffMaskleft'));
					document.body.removeChild(document.getElementById('ffMaskright'));
				}
				return;
			}
		}
	}

	if (forward != highlightDirection) return;
	setOpacity(document.getElementById('ffMaskabove'), opacity);
	setOpacity(document.getElementById('ffMaskbelow'), opacity);
	setOpacity(document.getElementById('ffMaskleft'), opacity);
	setOpacity(document.getElementById('ffMaskright'), opacity);

	if (again) {
	    if (forward != highlightDirection) return;
		highlightTimer = window.setTimeout(function() { highlightAnimation(forward); }, 5);
	}
}
function getOpacity(obj) {
	try {
		return parseFloat(obj.style.opacity);
	} catch (err) { return 1; }
}
function setOpacity(obj, opacity) {
    if (!obj) return;
	if (obj.style.display.toLowerCase() == 'none') obj.style.display = '';
	if (opacity == null) { obj.style.opacity = ''; obj.style.filter = ''; return; }
	obj.style.opacity = opacity;
	obj.style.filter = 'alpha(opacity=' + (opacity*100) + ')';
}
function createMaskingDiv(top, left, width, height, name) {
	if (top < 0) top = 0;
	if (left < 0) left = 0;
	if (width < 0) width = 0;
	if (height < 0) height = 0;
	var mask = document.getElementById('ffMask' + name);
	if (!mask) mask = document.createElement('div');
	mask.id = 'ffMask' + name;
	mask.style.width = width + 'px';
	mask.style.height = height + 'px';
	mask.style.backgroundColor = 'black';
	mask.style.position = 'absolute';
	mask.style.opacity = '0';
	mask.style.filter = 'alpha(opacity=0)';
	mask.style.left = left + 'px';
	mask.style.top = top + 'px';
	mask.style.zIndex = 500;
	mask.style.display = 'none';
	return mask;
}
function appendMaskingDiv(div) {
	if (!document.getElementById(div.id)) 
		document.body.appendChild(div);
}
function ffGalleryShowFullscreen(id) {
	var height = screen.availHeight * 0.95;
	var width = screen.availWidth * 0.95;
	var top = Math.round((screen.availHeight/2) - (height/2));
	var left = Math.round((screen.availWidth/2) - (width/2));
	var url = "";
	if (ffBaseURL) url = ffBaseURL;
	var newWindow = window.open(url + "slideshow.aspx?id=" + id, "slideshow", "status=no,directories=no,toolbar=no,scrollbars=yes,resizable=yes,location=no,menu=no,width=" + width + ",height=" + height + ",screenX=" + left + ",screenY=" + top + ",top=" + top + ",left=" + left);
	newWindow.focus();
}
function addResizeEvent(func) {	
	var oldonresize = window.onresize;
	if (typeof window.onresize != 'function'){
    	window.onresize = func;
	} else {
		window.onresize = function(){ oldonresize(); func(); };
	}
}
addResizeEvent(function() {
    if (maskNode) {

        var bodywidth = ffGetDimensions().pageWidth;
        var bodyheight = ffGetDimensions().pageHeight;
        maskNode.style.height = bodyheight + 'px';
        maskNode.style.width = bodywidth + 'px';
        if (highlightObj) {
            highlight(highlightObj, false, true);
            highlight(highlightObj, true, true);
        }
        if (dialogNode) {
            var height = parseInt(dialogNode.style.height);
            var width = parseInt(dialogNode.style.width);
            var top = Math.round(ffGetScrollTop() + (ffGetDimensions().viewportHeight / 2) - (height / 2));
            var left = Math.round(ffGetScrollLeft() + (ffGetDimensions().viewportWidth / 2) - (width / 2));
            dialogNode.style.left = left + 'px';
            dialogNode.style.top = top + 'px';
        } if (dialogThrobberNode) {
            var top = Math.round(ffGetScrollTop() + (ffGetDimensions().viewportHeight / 2) - (75 / 2));
            var left = Math.round(ffGetScrollLeft() + (ffGetDimensions().viewportWidth / 2) - (75 / 2));
            dialogThrobberNode.style.left = left + 'px';
            dialogThrobberNode.style.top = top + 'px';
        }

    } 
});
function addLoadEvent(func) {	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){ oldonload(); func(); };
	}
}

function ffSlideShow(container, imageSrc, imageDesc, params) {
	this.container = container;
	this.params = params;
	if (this.params.fullScreen) {
		var min = ffGetDimensions().viewportHeight;
		if (ffGetDimensions().viewportWidth < min)
			min = ffGetDimensions().viewportWidth;
		this.height = (parseInt(min*0.95) - 100);
		this.width = this.height;
		this.container.style.height = this.height + 'px';
		this.container.style.width = this.width + 'px';
		addResizeEvent(function() { location.reload(); });
	} else {
		this.height = this.container.offsetHeight;
		this.width = this.container.offsetWidth;
	}
	this.params.descs = (imageDesc) ? true : false;
	this.panelHeight = 40;
	this.idx = 0;
	this.imgIdx = 0;
	this.moveauto = false;
	this.animTimer = false;
	this.showPanelAnim = false;
	this.animProgress = 0;
	this.imagesList = new Array(imageSrc.length);
	this.hasDescs = false;
	for (var i = 0; i < imageSrc.length; i++) {
		if (imageDesc[i]) this.hasDescs = true;
		if (params.ratio == '' || this.params.fullScreen) {
			this.imagesList[i] = { u: imageSrc[i] + '&thumb=' + this.width, t: (imageDesc[i]) ? imageDesc[i] : ''};
		} else {
			this.imagesList[i] = { u: imageSrc[i] + '&pa=on&height=' + this.height + '&width=' + Math.round(this.height*params.ratio), t: (imageDesc[i]) ? imageDesc[i] : ''};
		}
	}
	for (var i = 0; i < this.imagesList.length; i++) {
		var t = new Image(this.width, this.height);
		t.src = this.imagesList[i].u;
	}
}

ffSlideShow.prototype.addEvent = function(elem, evt, fn) {
	if (elem.addEventListener) {
	 elem.addEventListener(evt, fn, false);
      } else if (elem.attachEvent) {
	 elem.attachEvent('on' + evt, fn);
      }
};

ffSlideShow.prototype.showPanel = function(on) {
	if (this.showPanelAnim) window.clearInterval(this.showPanelAnim);
	this.showPanelAdmin = false;
	this.panel.style.visibility = '';
	var ffs = this;
	this.showPanelAnim = window.setInterval(function() { ffs.showPanelAnimStep(on); }, 50);
};

ffSlideShow.prototype.showPanelAnimStep = function(on) {
	var top = parseInt(this.panel.style.top);
	if (on) {
		if (top <= (this.height - this.panelHeight)) {
			window.clearInterval(this.showPanelAnim);
			this.showPanelAnim = false;
		} else {
			top = top - (this.panelHeight / 10);
			this.panel.style.top = top + 'px';
		}
	} else {
		if (top >= this.height) {
			window.clearInterval(this.showPanelAnim);
			this.showPanelAnim = false;
		} else {
			top = top + (this.panelHeight / 10);
			this.panel.style.top = top + 'px';
		}
	}
};

ffSlideShow.prototype.showPanel2 = function(on) {
	this.panel2.style.visibility = (on) ? 'visible' : 'hidden';
};

ffSlideShow.prototype.move = function(dirn) {
	var ffs = this;
	if (this.moveauto) window.clearTimeout(this.moveauto);
	if (!this.animTimer) {
	var newidx = this.idx + dirn;
	if (newidx < 0)
		newidx = this.imagesList.length - 1;
	else if (newidx >= this.imagesList.length)
		newidx = 0;
	this.setImage(newidx);
	}
	else {
		this.moveauto = window.setTimeout(function() { ffs.move(1); }, 100); 
	}
};

ffSlideShow.prototype.setImage = function(idx) {
	this.title.innerHTML = this.imagesList[idx].t;
	if (this.imgIdx == 0) this.img[1].src = this.imagesList[idx].u;
	else this.img[0].src = this.imagesList[idx].u;
	this.idx = idx;
};

ffSlideShow.prototype.imgLoad = function(idx) {
	if (idx != this.imgIndex) {
		this.animStart();
	}
}

ffSlideShow.prototype.animStep = function() {

	// 1 is fade
	if (this.params.animType == '1') {
		if (this.imgIdx == 0)
			setOpacity(this.img[1], this.animProgress / 100);
		else
			setOpacity(this.img[1], 1-(this.animProgress / 100));
		if (this.animProgress == 0) {
			this.img[1].style.visibility = '';
		}
		this.animProgress = this.animProgress + 1;
	// 2 is box
	} else if (this.params.animType == '2') {
		var height = ((this.animProgress) / 100) * this.height;
		var width = ((this.animProgress) / 100) * this.width;
		if (this.imgIdx == 1) {
			height = this.height - height;
			width = this.width - width;
		}
		this.img[1].style.height = height + 'px';
		this.img[1].style.width = width + 'px';
		if (this.animProgress == 0) {
			this.img[1].style.visibility = '';
		}
		this.animProgress = this.animProgress + 1;
	} else {
		if (this.imgIdx == 0)
			this.img[1].style.visibility = '';
		else
			this.img[1].style.visibility = 'hidden';
		this.animProgress = 101;
	}

	if (this.animProgress > 100) {
		if (this.imgIdx == 0) { this.imgIdx = 1; } else { this.imgIdx = 0; }
		this.animStop();
	}
};

ffSlideShow.prototype.animStart = function() {
	if (this.animTimer) window.clearInterval(this.animTimer);
	this.animProgress = 0;
	var ffs = this;
	this.animTimer = window.setInterval(function() { ffs.animStep(); }, 10);
}

ffSlideShow.prototype.animStop = function() {
	if (this.animTimer)  {
		window.clearInterval(this.animTimer);
		this.animTimer = false;
		var ffs = this;
		if (this.params.autoSeconds > 0) {
			if (this.moveauto) window.clearTimeout(this.moveauto);
			this.moveauto = window.setTimeout(function() { ffs.move(1); }, this.params.autoSeconds * 1000); 
		}
	}
}

ffSlideShow.prototype.stylePanel = function(pan) {
	pan.style.backgroundColor = 'black';
	pan.style.color = 'white';
	pan.style.position = 'absolute';
	setOpacity(pan, 0.5);
}

ffSlideShow.prototype.render = function(fullScreenFn) { 
	var ffs = this;
	this.container.style.position = 'relative';
	this.container.style.overflow = 'hidden';
	this.panel = document.createElement('div');
	this.stylePanel(this.panel);
	this.panel.style.top = (this.height) + 'px';
	this.panel.style.height = this.panelHeight + 'px';
	this.panel.style.width = this.width + 'px';
	this.panel.className = 'ffSlideShowPanel';
	this.container.insertBefore(this.panel, this.container.childNodes[0]);
	if (this.params.showFullScreen && !this.params.fullScreen) {
		this.panel2 = document.createElement('div');
		this.panel2.style.textAlign = 'right';
		this.stylePanel(this.panel2);
		this.panel2.style.width = this.width + 'px';
		this.panel2.style.height = '1.5em';
		this.panel2.innerHTML = 'Show fullscreen';
		this.panel2.style.cursor = 'pointer';
		this.addEvent(this.panel2, 'click', fullScreenFn);
		this.container.insertBefore(this.panel2, this.container.childNodes[0]);
	}
	this.showPanel(this.params.fullScreen);
	if (!this.params.fullScreen && this.params.showFullScreen) {
		this.showPanel2(false);
	}
	if (this.params.navControls) {
	this.left = document.createElement('div');
	this.left.style.cssFloat = 'left';
	this.left.style.styleFloat = 'left';
	this.left.style.width = '26px';
	this.left.style.height = '26px';
	this.left.style.marginTop = '5px';
	this.left.style.backgroundImage = 'url(Templates/left.png)';
	this.left.style.cursor = 'pointer';
	this.addEvent(this.left, 'click', function() { ffs.move(-1); });
	this.panel.appendChild(this.left);
	this.right = document.createElement('div');
	this.right.style.cssFloat = 'right';
	this.right.style.styleFloat = 'right';
	this.right.style.width = '26px';
	this.right.style.height = '26px';
	this.right.style.marginTop = '5px';
	this.right.style.backgroundImage = 'url(Templates/right.png)';
	this.right.style.cursor = 'pointer';
	this.addEvent(this.right, 'click', function() { ffs.move(1); });
	this.panel.appendChild(this.right);
	}
	this.title = document.createElement('div');
	this.title.style.padding = '10px';
	this.title.innerHTML = this.imagesList[0].t;
	this.title.style.textAlign = 'center';
	this.panel.appendChild(this.title);
	if (!this.params.fullScreen) {
		if (this.params.navControls || this.hasDescs) {
			this.addEvent(this.container, 'mouseover', function() { ffs.showPanel(true); });
			this.addEvent(this.container, 'mouseout', function() { ffs.showPanel(false); });
		}
		if (this.params.showFullScreen) {
			this.addEvent(this.container, 'mouseover', function() { ffs.showPanel2(true); });
			this.addEvent(this.container, 'mouseout', function() { ffs.showPanel2(false); });
		}
	}
	this.img = [ this.container.getElementsByTagName('img')[0], document.createElement('img') ];
	this.img[0].width = this.width;
	this.img[0].height = this.height;
	this.img[1].width = this.width;
	this.img[1].height = this.height;
	this.img[1].style.position = 'absolute';
	this.img[1].style.visibility = 'hidden';
	this.addEvent(this.img[1], 'load', function() { ffs.imgLoad(1); });
	this.addEvent(this.img[0], 'load', function() { ffs.imgLoad(0); });
	this.container.insertBefore(this.img[1], this.container.childNodes[0]);
	if (this.params.autoSeconds > 0) {
		this.moveauto = window.setTimeout(function() { ffs.move(1); }, this.params.autoSeconds * 1000); 
	}

};

function ffGalleryLayoutTable(id, cols, rows, size, galimages, descs, controls) {

	size *= 0.5;
	var pages = Math.ceil(galimages.length/(cols*rows));
	document.write("<table width='100%' class='thumbnailtable' cellpadding=5 cellspacing=3>");
	if ((pages > 1) && controls) {
		document.write("<tr><td colspan=" + cols + " class='thumbnailstop'><center><span id='ffGallery" + id + "_top'>Page 1/" + pages + "</span></center></td></tr>");
	}
	for (var i = 0; i < rows; i++) {
		document.write("<tr>");
		var stop = false;
		for (var j = 0; j < cols; j++) {
		
				if (galimages[(cols*i)+j] == null) {
					document.write("<td>&nbsp;</td>");
					stop = true;
				}
				else {
					document.write("<td><center><a href=\"" + galimages[(cols*i)+j] + "\" target='_blank'><img width=" + size + "height=" + size + " border=0 id='ffGallery" + id + "_" + ((cols*i)+j) + "_img' src=\"" + galimages[(cols*i)+j] + "&thumb=" + size + "\"></a>");
					if (descs.length > 0)
						document.write("<div id='ffGallery" + id + "_" + ((cols*i)+j) + "_div' class='thumbnaildesc' style='text-align: center'>" + descs[(cols*i)+j] + "</div>");
					document.write("</center></td>");
				}
		}
		document.write("</tr>");
		if (stop) break;
	}
	if ((pages > 1) && (controls)) {
		document.write("<tr><td colspan=" + cols + "><center><a href='javascript:ffGalleryRelativePage(" + id + ",-1)'>&lt; Back</a> ");
		for (var k = 0; k < pages; k++) {
			document.write("<a href='javascript:ffGalleryPage(" + id + "," + (k) + ")'>" + (k+1) + "</a> ");
		}
		document.write("<a href='javascript:ffGalleryRelativePage(" + id + ",1)'>Forward &gt;</a></center></td></tr>");
	}
	document.write("</table>");
	if (pages > 1)
		ffGalleryPagePreload(id, 1);
	
}

function ffGalleryPage(id, page) {

	if (page < 0) return;
	var galimages = window["ffGallery" + id + "Images"];
	var descs = window["ffGallery" + id + "Descs"];
	var cols = window["ffGallery" + id + "Cols"];
	var rows = window["ffGallery" + id + "Rows"];
	var size = window["ffGallery" + id + "Size"] * 0.5;
	var pages = Math.ceil(galimages.length/(cols*rows));
	if (page >= pages) return;
	var startrow = page*rows;
		
	for (var i = startrow; i < startrow+rows; i++) {
		for (var j = 0; j < cols; j++) {
		
			if (galimages[(cols*i)+j] != null) {
				if (descs.length > 0)
					xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_div").innerHTML = descs[(cols*i)+j];
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").src = "Templates/pixel.gif";
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").src = galimages[(cols*i)+j] + "&thumb=" + size;
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").parentNode.href = galimages[(cols*i)+j];
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").parentNode.style.visibility = "";
			}
			else {
				if (descs.length > 0)
					xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_div").innerHTML = "";
				xBrowserGetElement("ffGallery" + id + "_" + ((cols*(i-startrow))+j) + "_img").parentNode.style.visibility = "hidden";
			}
		}
	}
	
	window["ffGallery" + id + "Page"] = page;
	xBrowserGetElement("ffGallery" + id + "_top").innerHTML = "Page " + (page+1) + "/" + pages;
	if (page < (pages - 1))
		ffGalleryPagePreload(id, page + 1);

}

function ffGalleryRelativePage(id, relpage) {
	ffGalleryPage(id, window["ffGallery" + id + "Page"] + relpage);
}
function ShowDialog(url) {
	ShowDialog(url, "no");
}
function ShowDialog(url, scrollbars, height, width, inplace) {
	if (ffBaseURL) url = ffBaseURL + url;
	if (highlightObj) {
		var t = highlightObj;
		var overflowedDivs = false;
		while (t && (t.tagName.toUpperCase() != 'BODY') && (t.tagName.toUpperCase() != 'HTML')) {
			if (t.style.overflow != '') {
				overflowedDivs = true;
				break;
			}
			t = t.offsetParent;
		}
		if (overflowedDivs) {
			inplace = false;
		}
	}
	
	if (dialogNode) {
		try	{ document.body.removeChild(dialogNode); } catch (e) {  };
	}
	
	var id = Math.random();
	
	if (inplace)
		showPageEdit(false);
	
	if (height == null) height = 470;
	if (width == null) width = 350;
	
	dialogNode = document.createElement('iframe');
	dialogNode.name = 'ffDialogNode' + id;
	dialogNode.id = 'ffDialogNode' + id;
	dialogNode.ffURL = url;
	dialogNode.setAttribute('scrolling', 'no');
	dialogThrobberNode = null;
	
	dialogNode.style.backgroundColor = 'white';
	
	if (!inplace || !highlightObj) {
	
		var bodywidth = ffGetDimensions().pageWidth;
		var bodyheight = ffGetDimensions().pageHeight;
		maskNode = createMaskingDiv(0, 0, bodywidth, bodyheight, 'dialog');
		appendMaskingDiv(maskNode);
		
		var scrolltop = ffGetScrollTop();
		var top = Math.round(ffGetScrollTop() + (ffGetDimensions().viewportHeight/2) - (height/2));
		var left = Math.round(ffGetScrollLeft() + (ffGetDimensions().viewportWidth/2) - (width/2));
		dialogNode.style.position = 'absolute';
		dialogNode.style.left = left + 'px';
		dialogNode.style.top = top + 'px';
		dialogNode.style.zIndex = '501';
		dialogNode.style.border = 'outset 1px rgb(200,200,200)';
		
		dialogNode.style.height = height + 'px';
		dialogNode.style.width = width + 'px';
		dialogNode.setAttribute('height', height);
		dialogNode.setAttribute('width', width);

		var throbber = true;

		if (navigator.appName == 'Microsoft Internet Explorer')
		    window.dialogThrobberInterval = setInterval(function() { if (dialogNode.contentWindow.document.body) { hideThrobber(); } }, 250);
		else {
		    dialogNode.setAttribute('onload', 'hideThrobber()');
		}
				
		dialogNode.dialogOpacity = 0;
		dialogNode.dialogTopStep = (height + top) / 25;

		dialogNode.style.display = 'none';

        if (throbber) {
		    dialogThrobberNode = document.createElement('img');
		    dialogThrobberNode.src = 'Admin/editor/img/throbber.gif';
		    dialogThrobberNode.style.position = 'absolute';
		    var ttop = Math.round(ffGetScrollTop() + (ffGetDimensions().viewportHeight / 2) - (75 / 2));
		    var tleft = Math.round(ffGetScrollLeft() + (ffGetDimensions().viewportWidth / 2) - (75 / 2));
		    dialogThrobberNode.style.left = tleft + 'px';
		    dialogThrobberNode.style.top = ttop + 'px';
		    dialogThrobberNode.style.zIndex = 502;
		    document.body.appendChild(dialogThrobberNode);
		}
		
		document.body.appendChild(dialogNode);
		ShowDialogFade();
		
	} else {
	
		var node = highlightObj;
		
		var offset = 50;

		var height = 300;
			
		dialogNode.setAttribute('height', height);
		dialogNode.setAttribute('width', '100%');
		dialogNode.setAttribute('border', '0');
		dialogNode.setAttribute('frameborder', '0');
		
		
		highlight(highlightObj, false, true);		
		savedNodes = new Array();
		var i = 0;
		while (node.childNodes.length > 0) {
			savedNodes[i] = node.childNodes[0];
			node.removeChild(node.childNodes[0]);
			i++;
		}
		node.appendChild(dialogNode);
		
		highlight(node, true, true);
	
	
	}

	frames['ffDialogNode' + id].location.href = url;
	highlightLock = true;
	
}

var dialogNode;
var dialogThrobberNode;
var maskNode;
var savedNodes;

function hideThrobber() {
    if (dialogThrobberNode) document.body.removeChild(dialogThrobberNode);
    if (window.dialogThrobberInterval) clearInterval(window.dialogThrobberInterval);
    dialogThrobberNode = null;
}

function ShowDialogFade(reverse) {
	if ((!reverse && (dialogNode.dialogOpacity >= 50)) || (reverse && (dialogNode.dialogOpacity <= 0))) {
		ShowDialogFadeFinish(reverse);
	} else {
		dialogNode.dialogOpacity = (reverse) ? dialogNode.dialogOpacity - 10 : dialogNode.dialogOpacity + 10;
	    setOpacity(maskNode, dialogNode.dialogOpacity/100);
		
		window.setTimeout('ShowDialogFade(' + reverse + ')', 10);
	}
}
function ShowDialogFadeFinish(reverse) {
    if (reverse) {
        document.body.removeChild(maskNode);
        if (dialogThrobberNode != null)
            document.body.removeChild(dialogThrobberNode);
        if (dialogNode) {
            try { dialogNode.parentNode.removeChild(dialogNode); } catch (e) {}
        }
        try {
	        highlightLock = false;
		    highlight(highlightObj, false);
		} catch (e) { }
	} else { 
		dialogNode.style.display = '';
		if (dialogNode.contentWindow.placeFocus) dialogNode.contentWindow.placeFocus();
	}
}

function HideDialog(noremove) {

	if (dialogNode.parentNode == document.body) {
		dialogNode.style.display = 'none';
		ShowDialogFade(true);
		try {
			highlightLock = false;
			highlight(highlightObj, false);
		} catch (blah) {}
	} else {
		var node = highlightObj;
		highlightLock = false;
		highlight(highlightObj, false);
		node.removeChild(dialogNode);
		for (var i = 0; i < savedNodes.length; i++) {
			node.appendChild(savedNodes[i]);
		}
		node.editLock = false;
	}
}

function DeleteSection(id) {
	ShowDialog("Admin/sectionsDelete.aspx?id=" + id);
}

function ChangeLayout(id) {
	ShowDialog("Admin/pagesLayout.aspx?id=" + id);
}

function AddSection(id) {
	ShowDialog("Admin/sectionsModify.aspx?parent_id=" + id);
}

function AddToplevelSection(site_id) {
    ShowDialog("Admin/sectionsModify.aspx?site_id=" + site_id);
}


function ModifySection(id) {
	ShowDialog("Admin/sectionsModify.aspx?id=" + id);
}

function ModifyComponent(obj, type, event) {

	var id = getComponentIdFromElement(obj);
	if (id == -1) return;
	
	if (type == "html") {
		var url = "Admin/modifyHtml.aspx?id=" + id;
		
		var width = ffGetDimensions().viewportWidth - 120;
		var height = ffGetDimensions().viewportHeight - 120;
		var inplace = highlightObj && (highlightObj.offsetWidth > 700);
			
		if (event.ctrlKey) inplace = false;
	
		ShowDialog(url, "no", height, width, inplace);
	}

	else if (type == "RSS") {
		var url = "Admin/modifyNewsSummary.aspx?id=" + id;
		var width = 600;
		var height = 380;
		ShowDialog(url, "no", height, width);
	}

	else if (type == "progress") {
		ShowDialog("Admin/modifyProgressCheck.aspx?id=" + id);
	}

	else if (type == "question") {
		var url = "Admin/modifyQuestion.aspx?id=" + id;
		var width = 600;
		var height = 380;
		ShowDialog(url, "no", height, width);
	}

	else if (type == "calendar") {

		var url = "Admin/modifyCalendar.aspx?id=" + id;
		var width = 600;
		var height = 400;
		ShowDialog(url, "no", height, width);
    }

    else if (type == "contact") {

        var url = "Admin/modifyContact.aspx?id=" + id;
        var width = 600;
        var height = 400;
        ShowDialog(url, "no", height, width);
    }	
	
	else if (type == "gallery" || type == "resourcelist") {

		var url = "Admin/modifyGallery.aspx?id=" + id;
		var width = 600;
		var height = 380;
		ShowDialog(url, "no", height, width);

	}
	
	else if (type == "plugin") {

		var url = "Admin/modifyPluginComponent.aspx?id=" + id;
		var width = 550;
		var height = 340;
		ShowDialog(url, "no", height, width);

	}
	
}
function PageMakeupDelete(page, obj) {
	if (window.confirm("Are you sure you want to delete the selected component?")) {
		var id = getComponentIdFromElement(obj);
		if (id == -1) return;
		DoHiddenDialog("Admin/pageMakeupDelete.aspx?page_id=" + page + "&component_id="+ id);
	}
}
function PageMakeupFloat(obj) {
	var id = getComponentIdFromElement(obj);
	if (id == -1) return;
	ShowDialog('Admin/componentsFloat.aspx?id=' + id);
}
function PageMakeupMove(page_id, obj, up, e) {
	var id = getComponentIdFromElement(obj);
	if (id == -1) return;
	var dirn = up ? 'up' : 'down';
	var memobj = up ? pageMakeupMoveUpCounts : pageMakeupMoveDownCounts;
	if (memobj[id]) {
		memobj[id] = memobj[id]+1;
	} else {
		memobj[id] = 1;
	}
	var turbo = (e.ctrlKey) ? '&turbo=yes' : '';
	DoHiddenDialog("Admin/componentsMove.aspx?page_id=" + page_id + "&component_id=" + id + "&action="+ dirn + turbo);
}
var pageMakeupMoveDownCounts = [];
var pageMakeupMoveUpCounts = [];
function DoHiddenDialog(url) {
	// now use AJAX
	var ajax = createAjax();
	if (ajax != null) {
		ajax.open('GET', url + '&u=' + new Date().getTime(), true);
		ajax.onreadystatechange = function() {
		    if (ajax.readyState == 4) {
		        if ((ajax.status >= 200) && (ajax.status < 300)) {
		            if (ajax.responseXML.getElementsByTagName('script').length > 0) {
		                eval(ajax.responseXML.getElementsByTagName('script')[0].firstChild.nodeValue);
		            }
		        }
		        else
		            alert('Unknown error: check your internet connnection and try reloading the page.');
		    } else return false;
		}
		ajax.send(null);
	} else {
		alert('Please use a browser that supports AJAX: try the latest Firefox / Internet Explorer / Safari');
	}
}
function ControlPanel(site_id, section_id, page_id) {
	ShowDialog("Admin/controlpanel.aspx?site_id=" + site_id + "&section_id=" + section_id + "&page_id=" + page_id);
}
function ResourceManager(id) {
	var url = "Admin/editor/resourcesManager.aspx?section_id=" + id;
	if (ffBaseURL) url = ffBaseURL + url;
	var width = 700;
	var height = 450;
	var windowname = "ffRM";
	windowname += Math.round(Math.random() * 10000) + 1;
	var top = Math.round((screen.availHeight/2) - (height/2));
	var left = Math.round((screen.availWidth/2) - (width/2));
	var newWindow = window.open(url, windowname, "status=no,directories=no,toolbar=no,resizable=no,location=no,menu=no,width=" + width + ",height=" + height + ",screenX=" + left + ",screenY=" + top + ",top=" + top + ",left=" + left);
	newWindow.focus();
}
function SiteManager(id, current_id) {
	ShowDialog("Admin/sitemanager.aspx?id=" + id + "&current_id=" + current_id);
}
function ChangePassword() {
	ShowDialog("Admin/changePassword.aspx");
}
function ResetToken() {
    ShowDialog("Admin/resetToken.aspx");
}
function ShowStatus(text) {
	window.status = text;
	return true;
}

function ModifyPage(id) {
	ShowDialog("Admin/pagesModify.aspx?id=" + id);
}

function InsertPage(section_id, newssource_id, parent_id) {
    // newssource_id of -1 means blog post (child of page type "blog")
	if (newssource_id != null)
		ShowDialog("Admin/pagesModify.aspx?section_id=" + section_id + "&newssource_id=" + newssource_id + "&parent_id=" + parent_id);
    else if (parent_id != null)
        ShowDialog("Admin/pagesModify.aspx?section_id=" + section_id + "&parent_id=" + parent_id);
	else
		ShowDialog("Admin/pagesModify.aspx?section_id=" + section_id);
}

function ImportExport(page_id) {
	ShowDialog("Admin/importExport.aspx?page_id=" + page_id);
}

function SectionManager(section_id) {
	ShowDialog("Admin/sectionmanager.aspx?id=" + section_id);
}

function ChooseHtml(page_id) {
	var url = "Admin/chooseHtml.aspx?page_id=" + page_id;
	if (ffBaseURL) url = ffBaseURL + url;
	var width = 700;
	var height = 500;
	var windowname = "ffModify";
	windowname += Math.round(Math.random() * 10000) + 1;
	var top = Math.round((screen.availHeight/2) - (height/2));
	var left = Math.round((screen.availWidth/2) - (width/2));
	var newWindow = window.open(url, windowname, "status=no,directories=no,toolbar=no,resizable=yes,location=no,menu=no,width=" + width + ",height=" + height + ",screenX=" + left + ",screenY=" + top + ",top=" + top + ",left=" + left);
	newWindow.focus();
}


function DeletePage(id) {
	ShowDialog("Admin/pagesDelete.aspx?id=" + id, "auto");
}

function UndeletePage(id) {
	ShowDialog("Admin/pagesUndelete.aspx?id= " + id, "auto");
}

function commentsDelete(page, comment) {
	if (window.confirm("Are you sure you want to delete the selected comment?"))
		DoHiddenDialog("Admin/commentsDelete.aspx?page_id=" + page + "&comment_id="+ comment);
}

function commentsApprove(page, comment) {
	DoHiddenDialog("Admin/commentsApprove.aspx?page_id=" + page + "&comment_id="+ comment);
}

function commentsModify(page, comment) {
	ShowDialog("Admin/commentsModify.aspx?page_id=" + page + "&comment_id=" + comment);
}

function ConfirmURL(url, text) {
	if (window.confirm(text))
		DoHiddenDialog(url);
}

function getCookie(strName) {
	var cookies, bits;
	cookies = document.cookie.split(";");
	for (i = 0; i < cookies.length; i++) {
		cookies[i] = cookies[i].replace(" ", "");
		bits = cookies[i].split("=");
		if (bits[0] == strName) { return bits[1]; }
	}
	return false;
}

function setTempCookie(strName, strValue) {
	document.cookie = strName + "=" + escape(strValue) + "; path=/;";
}

function ffRedirect(url, referrer) {
    if ((url.substr(0, 1) != '/') && (url.substr(0, 7) != 'http://') && (url.substr(0, 8) != 'https://')) {
		if (ffBaseURL) url = ffBaseURL + url;
	}
	location.href = url;
}

function CopyPage(id) { ffRedirect("session.aspx?copypage_id=" + id + "&referrer=" + escape(location.href)); }
function PastePage(id) {
    if (($('.component, .floatedcomponent').length == 0) || window.confirm("Would you like to overwrite the contents of the current page with the copied page?\n\nYou can roll back using the View previous versions tool.")) {
        $.ajax({
            url: "Admin/editor/serverside/pastepage.aspx",
            dataType: 'script',
            type: "POST",
            data: "id=" + id,
            error: function() { alert('Error pasting page.  Please check your internet connection. '); }
        });
    }
}

function xBrowserGetElement(elename) {
	// support for ie4/ie5/ie6/moz5+
	if (document.all) { return document.all[elename]; }
	else { return document.getElementById(elename); }
}

function ffLinkHelper() {
	var contentDiv = xBrowserGetElement("content");
	var leftBar = xBrowserGetElement("ffLB");
	var networkOnlyLinks = 0;

	window.defaultStatus = "Building page links...";

	networkOnlyLinks += ffLinkHelperDoObj(contentDiv);
	networkOnlyLinks += ffLinkHelperDoObj(leftBar);

	if (networkOnlyLinks > 0) {
		contentDiv.innerHTML = "<div style='border: 2px solid red; padding: 3px; margin-top: 3px'><b>This page contains links that will only function correctly when using the intranet from within the school network.  Such links are marked with this icon: <img src='Templates/linkfile.gif'>.</div>" + contentDiv.innerHTML;
	}

	window.defaultStatus = "";
	ffImageHelper(contentDiv);
}
function ffImageHelper(container) {
	var images = container.getElementsByTagName("IMG");
	for (i = 0; i < images.length; i++) {
		if (images[i].style.height && (images[i].src.indexOf("image.aspx") != -1)) {
			images[i].src += "&height=" + parseInt(images[i].style.height) + "&width=" + parseInt(images[i].style.width);
		}
	}
}
function ffLinkHelperDoObj(node) {

	contentLinks = node.getElementsByTagName("A");
	var thisServer = location.protocol + "//" + location.host + location.port + location.pathname;
	var networkOnlyLinks = 0;

	for (i = 0; i < contentLinks.length; i++) {

			if (contentLinks[i].href && contentLinks[i].innerText != "") {
				tsrc = ""; talt = ""; ttarget="";
				if (contentLinks[i].href.length > 7) {
					if (contentLinks[i].href.substring(0,7) == "mailto:") { tsrc = 'Templates/linkmail.gif'; talt='Link to e-mail address'; }
					if (contentLinks[i].href.substring(0,7) == "http:\/\/") { 
						// check no same server link
						if (contentLinks[i].href.length >= thisServer.length) {
							if (contentLinks[i].href.substring(0, thisServer.length) != thisServer) {
								tsrc='Templates/linkext.gif'; talt='Link to external web site (opens in a new window)'; ttarget = "_new";
							}
						} else {
							tsrc= 'Templates/linkext.gif'; talt='Link to external web site (opens in a new window)'; ttarget = "_new";
						}
					}
					if (contentLinks[i].href.substring(0,7) == "file:\/\/") {  networkOnlyLinks++; tsrc='Templates/linkfile.gif'; talt='Link to file on network share (only available on internal network)';  }

				}
				if (tsrc != "") {
					// we have a glyph to add
				if (!document.all) {
					var newglyph = document.createElement("img");
					var src = document.createAttribute("src"); src.value = tsrc; newglyph.setAttributeNode(src);
					var border = document.createAttribute("border"); border.value = "0"; newglyph.setAttributeNode(border);
					var alt = document.createAttribute("alt"); alt.value = talt; newglyph.setAttributeNode(alt);
					contentLinks[i].appendChild(newglyph);
					newglyph.style.marginLeft = "3px";
				}
				else {
					contentLinks[i].innerHTML += "<img src='" + tsrc + "' alt='" + talt + "' border=0 style='margin-left: 3px'>";
				}
					if (ttarget != "") { contentLinks[i].target = ttarget; }
				}
			}

	}
	return networkOnlyLinks;
}


function getTop(obj, abs) {

    //
    // IE BUG workaround
    if (abs && (obj.style.overflow != ""))
        return 0;

    var top = $(obj).position().top;

    if (getStyle(obj, 'position').toLowerCase() == 'fixed')
        left += ffGetScrollLeft();

    if ((obj.tagName.toLowerCase() != "html") && (obj.tagName.toLowerCase() != "body") && ($(obj).offsetParent().length > 0)) {
        top -= obj.scrollLeft;
        var tag = $(obj).offsetParent()[0].tagName.toLowerCase();
        if ((tag != "html") && (tag != "body"))
            top += getTop($(obj).offsetParent()[0], abs);
    }

	
    return top;
}

function getLeft(obj, abs) {

	//
	// IE BUG workaround
	if (abs && (obj.style.overflow != ""))
		return 0;

    var left = $(obj).position().left;
	
	if (getStyle(obj, 'position').toLowerCase() == 'fixed')
		left += ffGetScrollLeft();

    if ((obj.tagName.toLowerCase() != "html") && (obj.tagName.toLowerCase() != "body") && ($(obj).offsetParent().length > 0)) {
        left -= obj.scrollLeft;
        var tag = $(obj).offsetParent()[0].tagName;
	    if ((tag != "html") && (tag != "body"))
		    left += getLeft($(obj).offsetParent()[0], abs);
	}

    return left;
}

function getScrollTop(obj) {

	var top = 0
	if (obj.tagName)
		top = obj.scrollTop;
	
	if (obj.parentElement)
		top += getScrollTop(obj.parentElement);

	else if (obj.parentNode)
		top += getScrollTop(obj.parentNode);

    return top;
}

function getScrollLeft(obj) {

	var left = 0
	if (obj.tagName)
		left = obj.scrollLeft;

	if (obj.parentElement)
		left += getScrollLeft(obj.parentElement);

	else if (obj.parentNode)
		left += getScrollLeft(obj.parentNode);

    return left;
}

function jsError() {

	return true;

}

function ffLog(logtext) {
/*   if (document.getElementById('fflogger')) {
        
    } else {
    var div = document.createElement('div');
    div.style.position = 'absolute';
    div.style.top = '0px';
    div.style.left = '0px';
    div.style.backgroundColor = 'white';
        div.id = 'fflogger';
        document.body.appendChild(div);
    }
    document.getElementById('fflogger').innerHTML = document.getElementById('fflogger').innerHTML + "<br>" + logtext;*/
}

function DashboardSubscribe(page_id) {

    var subscribe = ($('#dashboard-subscribe img')[0].alt == 'Subscribe');

    $.ajax({
        url: "dashboard-subscribe.aspx?page_id=" + page_id + "&on=" + (subscribe ? "yes" : "no"),
        dataType: 'xml',
        type: "POST",
        data: {},
        success: function(data, text) {

            if (subscribe) {
                $('#dashboard-subscribe').html('<img src="Templates/lightning_delete.gif" alt="Unsubscribe"> Unsubscribe');
            }
            else {
                $('#dashboard-subscribe').html('<img src="Templates/lightning_add.gif" alt="Subscribe"> Subscribe');
            }

        },
        error: function() { alert('Error saving subscription.  Check your internet connection and try reloading the page.'); }
    });
}

function DashboardUnsubscribe(subscription_id, successfn) {
    $.ajax({
        url: "dashboard-subscribe.aspx?&on=no&subscription_id="+subscription_id,
        dataType: 'xml',
        type: "POST",
        data: {},
        success: successfn,
        error: function() { alert('Error saving subscription.  Check your internet connection and try reloading the page.'); }
    });
}

window.onerror = jsError;
addLoadEvent(function() { checkStyles('Templates/common.css'); });

// collapsible component type
$(function() {
    ffEventHandler.registerEvent("dominsert", function() {
        $('div.collapsible').each(function() {
            // prevent wiring up twice
            if ($(this).is('.collapsible-wired'))
                return;

            var collapsed = true;
            var height = $('h2.componentheader', this).outerHeight(true);
            $(this).css({ 'height': height + 'px', 'overflow': 'hidden' });

            this.ffComponentChangeType = function(obj) {
                $(obj).removeClass('collapsible-wired');
                $(obj).removeClass('collapsible-open');
                obj.ffComponentChangeType = null;
                $(obj).css({ 'height': '', 'overflow': '' });
            }

            $('h2.componentheader', this).click(function() {
                if (collapsed) {
                    $(this.parentNode).css({ 'height': '', 'overflow': '' });
                    $(this.parentNode).addClass('collapsible-open');
                } else {
                    $(this.parentNode).css({ 'height': height + 'px', 'overflow': 'hidden' });
                    $(this.parentNode).removeClass('collapsible-open');
                }
                collapsed = !collapsed;
            });

            $(this).addClass('collapsible-wired');
        });
    }, true);
});