//=======================================
// Debugging enabling and viewing
//=======================================
function jsDebug() { }

jsDebug.cssIdContainer = 'jsDebugContainer';
jsDebug.cookieName = 'debug';

jsDebug.init = function() {
	var enabled = this.isEnabled();
	log.options.debugDisabled = !enabled;
	log.options.warningDisabled = !enabled;
}

jsDebug.isEnabled = function() {
	return (getCookie(this.cookieName) != null);
}

jsDebug.setEnabled = function(turnOn) {
	if (turnOn) {
		setCookie(this.cookieName, "1");
		log.options.debugDisabled = false;
		log.options.warningDisabled = false
		log.debug("Debugging is now enabled");
	}
	else {
		log.debug("Disabling debugging...");
		deleteCookie(this.cookieName);
		log.options.debugDisabled = true;
		log.options.warningDisabled = true;
	}
}

jsDebug.display = function(evt) {
	if (evt.ctrlKey) {
		if (evt.altKey) {
			var statusDiv = document.getElementById('jsDebugStatus');
			statusDiv.innerHTML = "Debug status: " + (this.isEnabled() ? "on" : "off");
			
			var curobj = document.getElementById('headerLogo');
			return overlay(curobj, this.cssIdContainer);
		}
		else {
			// just ctrl-click toggles messages
			this.setEnabled(!this.isEnabled());
		}
	}
}

jsDebug.hide = function() {
	overlayclose(this.cssIdContainer);
}

jsDebug.init();

/*****************************************
 Misc utility methods
 *****************************************/
function hideEl(elementId) {
	var el = document.getElementById(elementId);
	
	if (el)
		el.style.display = 'none';
}

function showEl(elementId) {
	var el = document.getElementById(elementId);
	
	if (el)
		el.style.display = '';
}

// for edit favorites form
function hideFavorite(id) {
	var el = document.getElementById(id).getElementsByTagName('input')[0];
	el.checked = false;
	hideEl(id);
}

function popup(url, width, height, showScrollbars) {
	var x = (screen.width - width) / 2;
	var y = (screen.height - height) / 2;
	var params = ',status=no,toolbar=no,menubar=no,location=no,resizeable=yes';

	if(showScrollbars)
		params = params + ',scrollbars=yes';

	var wnd = window.open(url, Math.round(1000000 * Math.random()),'height=' + height + ',width=' + width + params + ',top='+y+',screenY='+y+',left='+x+',screenX='+x);

	if (wnd)
		wnd.focus();
	
	return wnd;
}

/*****************************************
 Cookies
 *****************************************/
/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/*****************************************
 Rich text editor
 *****************************************/
var picChooserUrl;
var _entities = "34,quot,38,amp,39,#39,60,lt,62,gt,160,nbsp";	// #2290

function initBlogEditor(contentCssPath, choosePictureUrl) {
	picChooserUrl = choosePictureUrl;
	
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		width: 590,
		height: 500,
		content_css: contentCssPath,
		setupcontent_callback : "setupBlogEditorContent",

		// Couldn't get the CSS to work for some reason
		// plugins : "preview",
		// plugin_preview_pageurl: "/css/tinymce/jscripts/tiny_mce/plugins/preview/blogPreview.html",
		plugins : "inlinepopups,contextmenu,media,safari,simplepaste",
		theme_advanced_buttons1 : "formatselect,fontselect,fontsizeselect,|,undo,redo,|,code",
		theme_advanced_buttons2 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,numlist,bullist,|,indent,outdent,blockquote,|,forecolor,backcolor,|,link,unlink,|,image",
		theme_advanced_buttons3 : "",

		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		
		theme_advanced_resize_horizontal : false,
		theme_advanced_resizing : true,
		theme_advanced_statusbar_location : "bottom",
		
		paste_as_plain_text: false,		// #2499
		
		file_browser_callback : "fileBrowserCallback",
		relative_urls : false,
		extended_valid_elements : "object[*],embed[*],param[*],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|obj|param|embed]",	// Flash players

  		entities : _entities
	});
	
	addIsRichTextHiddenParam(document.getElementsByTagName("textarea"));
}

var commentEditorInitted = false;

function initCommentEditor(choosePictureUrl) {
	picChooserUrl = choosePictureUrl;

	tinyMCE.init({
		mode : "textareas",
		theme: "advanced",
		width: "100%",
		height: "150",
		content_css: "/css/zoji-common.css",	// TODO: use the CSS of the current page's skin
		setupcontent_callback : "setupCommentEditorContent",
		editor_selector : "comment",

		plugins : "inlinepopups,contextmenu,safari,simplepaste",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,justifyleft,justifycenter,numlist,bullist,blockquote,forecolor,link,unlink,image",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",

		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		
		paste_as_plain_text: false,		// #2499
		
		file_browser_callback : "fileBrowserCallback",
		relative_urls : false,

  		entities : _entities
	});
	
	commentEditorInitted = true;
	addIsRichTextHiddenParam(document.getElementsByTagName("textarea"));
}

function initEventDescEditor(choosePictureUrl) {
	picChooserUrl = choosePictureUrl;
	
	tinyMCE.init({
		mode : "textareas",
		theme : "advanced",
		width: 315,
		height: 150,
		content_css: "/css/zoji-common.css",	// TODO: use the CSS of the current page's skin
		setupcontent_callback : "setupEventDescEditorContent",
		editor_selector : "mceEditor",

		plugins : "inlinepopups,contextmenu,safari,simplepaste",
		theme_advanced_buttons1 : "bold,italic,underline,strikethrough,justifyleft,justifycenter,numlist,bullist,blockquote,forecolor,link,unlink,image",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",

		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		
		theme_advanced_resize_horizontal : false,
		theme_advanced_resizing : true,
		theme_advanced_statusbar_location : "bottom",
		
		paste_as_plain_text: false,		// #2499

		file_browser_callback : "fileBrowserCallback",
		relative_urls : false,
		
  		entities : _entities
	});
	
	addIsRichTextHiddenParamSingle(document.getElementById("createEvent_desc"));
}

// Insert param to let us know this item is rich text
function addIsRichTextHiddenParam(textareas) {
	for (i = 0; i < textareas.length; i++) {
		var hiddenParam = document.createElement("input");
		hiddenParam.setAttribute("type", "hidden");
		hiddenParam.setAttribute("name", "isRichText");
		hiddenParam.setAttribute("value", "1");
		textareas[i].parentNode.appendChild(hiddenParam);
	}
}

function addIsRichTextHiddenParamSingle(taObj) {
  var hiddenParam = document.createElement("input");
  hiddenParam.setAttribute("type", "hidden");
  hiddenParam.setAttribute("name", "isRichText");
  hiddenParam.setAttribute("value", "1");
  taObj.parentNode.appendChild(hiddenParam);
}



function focusCommentEditor(textareaId, richTextId) {
	if (commentEditorInitted)
		tinyMCE.execCommand('mceFocus', false, richTextId);
	else
		document.getElementById(textareaId).focus();
}

function setupBlogEditorContent(editor_id, body, doc) {
	body.className += " blogEditorBody editorBody";
}

function setupCommentEditorContent(editor_id, body, doc) {
	body.className += " commentEditorBody editorBody";
}

function setupEventDescEditorContent(editor_id, body, doc) {
	body.className += " eventDescEditorBody editorBody";
}

var imgUrlElement;

function fileBrowserCallback(field_name, url, type, win) {
	if (picChooserUrl && type == "image") {
		var wnd = displayPictureChooser(picChooserUrl);
		imgUrlElement = win.document.getElementById(field_name);
	}
}

/*****************************************
 Controls
 *****************************************/
function TabControl(currentTabId, currentContentsId, contentsContainerId) {	
	var currentTab = document.getElementById(currentTabId);
	var currentContents = document.getElementById(currentContentsId);
	
	this.displayTab = function(newTabLink, tabContentsId, ajaxUrl) {
		if (!ajaxUrl)
			swapTabs(newTabLink, tabContentsId);
		else {
			updateElement(ajaxUrl, {
				elementId: tabContentsId,
				statusElementId: contentsContainerId,
				afterCallback: function() {
					swapTabs(newTabLink, tabContentsId);
				}
			});			
		}
	}
	
	function swapTabs(newTabLink, tabContentsId) {	
		newTab = newTabLink.parentNode;
		currentTab.className = currentTab.className.replace('selected', '');
		newTab.className += ' selected';
		currentTab = newTab;
		
		currentContents.style.display = 'none';
		currentContents = document.getElementById(tabContentsId);
		currentContents.style.display = '';
		
		return false;
	}
}


/*****************************************
 Menus
 *****************************************/
var _idMenuContainer = 'menuContainer';
var _idMenuContent = 'menuContent';
var _clsMenuSep = 'menuSep';
var _clsMenuSelected = 'menuSelected';

var menuContainerEl;
var mouseIsInMenu;
var menuDisplayed;
var menuParent;
var origCssClass;
var attached = false;

//
// initCallback		(opt) function to be invoked when the menu is first shown
//
function Menu(menuHeaderId, menuPopupId, initCallback) {
	this.items = new Array();
	this.visible = false;
	this.lockedVisible = false;
	
	this.ulEl;	// lazily instantiated
	
	this.addLink = function(text, href, cssClass) {
		var index = this.items.length;
		
		if (cssClass == null)
			cssClass = "";
		else
			cssClass = " class='" + cssClass + "'";
			
		this.items[index] = "<a href='" + href + "'" + cssClass + ">" + text + "</a>";
	}
	
	this.addItem = function(html) {
		this.items[this.items.length] = html;
	}

	this.addSeparator = function() {
		this.addItem('<div class="' + _clsMenuSep + '"></div>');
	}
	
	this.show = function(menuEl) {
		if (menuDisplayed == this)
			return;

		// hide every top-level element first
		var menuContEl = document.getElementById(_idMenuContent);
		
		if (menuContEl.hasChildNodes) {
			var menuEls = menuContEl.childNodes;
			
			for (var i = 0; i < menuEls.length; i++) {
				if (menuEls[i].nodeType == 1)
					menuEls[i].style.display = 'none';
			}
		}
		
		// show this menu
		if (this.ulEl != null)
			this.ulEl.style.display = '';
		else {
			// create the menu
			this.ulEl = document.createElement("ul");
			
			if (menuPopupId)
				this.ulEl.id = menuPopupId;
			
			for (var i = 0; i < this.items.length; i++) {
				var liEl = document.createElement("li");
				liEl.innerHTML = this.items[i];
				this.ulEl.appendChild(liEl);
			}
				
			menuContEl.appendChild(this.ulEl);
			
			if (initCallback)
				initCallback();
		}
		
		// the parent node should be the containing li
		var parentNode = menuEl.parentNode;
		
		// display the menu
		var xOffset = 0;
		var yOffset = parentNode.offsetHeight;
		
		if (typeof(isV2Page) == "undefined") {
			// v1 pages are slightly misaligned due to the placement of the popup HTML
			xOffset -= 10;
			yOffset -= 10;
		}
		
		overlayMenu(parentNode, _idMenuContainer, xOffset, yOffset);
		if (menuDisplayed)
			menuDisplayed.setVisibleLock(false);
			
		menuDisplayed = this;

		if (menuParent != null)
			menuParent.className = origCssClass;

		menuParent = parentNode;
		origCssClass = menuParent.className;
		menuParent.className += " " + _clsMenuSelected;
	}
	
	// If true, locks the menu in visible state, so mouseouts are ignored.
	this.setVisibleLock = function(locked) {
		this.lockedVisible = locked;
	}
	
	function headerMouseover(evt) {
		mouseIsInMenu = true;
		that.show(this);	// "this" is the calling element
		return false;
	}
	
	function headerMouseout(evt) {
		if (that.lockedVisible)
			return;
			
		delayedHide();
	}

	// init
	var that = this;
	var menuHeaderEl = document.getElementById(menuHeaderId);
	menuHeaderEl.onmouseover = headerMouseover;
	menuHeaderEl.onmouseout = headerMouseout;
	
	// global stuff--event handlers for the menu container div
	menuContainerEl = document.getElementById(_idMenuContainer);
	
	if (!attached) {
		menuContainerEl.onmouseover = menuMouseover;
		menuContainerEl.onmouseout = menuMouseout;
		attached = true;
	}
}

function menuMouseover(evt) {
	mouseIsInMenu = true;
	return false;
}

function menuMouseout(evt) {
	if (menuDisplayed.lockedVisible)
		return;
	
	if (evt) {
		// Firefox
		if (evt.currentTarget != evt.relatedTarget && !contains(evt.currentTarget, evt.relatedTarget))
			delayedHide();
	}
	else {
		// IE
		if (!menuContainerEl.contains(window.event.toElement))
			delayedHide();
	}
	
	return false;
}

function overlayMenu(curobj, subobj, xoffset, yoffset) {
	if(xoffset == null)
		xoffset = 0;

	if(yoffset == null)
		yoffset = 0;

	var subobj=document.getElementById(subobj);
	subobj.style.left = (getposOffset(curobj, "left") + xoffset) + "px";
	subobj.style.top = (getposOffset(curobj, "top") + yoffset) + "px";
	subobj.style.display = '';
}

function hideAllMenus() {
	if (!mouseIsInMenu) {
		document.getElementById(_idMenuContainer).style.display = 'none';
		
		if (menuDisplayed != null) {
			menuDisplayed.setVisibleLock(false);
			menuDisplayed = null;
		}
		
		if (menuParent != null) {
			menuParent.className = origCssClass;
			menuParent = null;
		}
	}
}

function delayedHide() {
	mouseIsInMenu = false;
	setTimeout(hideAllMenus, 250);
}

function contains(a, b) {
	if (!b || !b.parentNode)
		return false;
	
	b = b.parentNode;

	while (b) {
		if (b == a)
			return true;
			
		b = b.parentNode;
	}
			
	return false;
}
	

/*****************************************
 Misc
 *****************************************/
// Picture chooser
function displayPictureChooser(url) {
	return popup(url, 770, 630, true);
}
 
// For ajax friend requests.  Code that calls this must include the friend popup HTML code.
var friendPopupId = 'friendPopup';
function showFriendPopup(curEl, friendUrl, firstName) {
	var idToUpdate = curEl.parentNode.id;
	
	// presence of yes link means it's after an event so we first ask if user met friend at an event, and if no
	// display how met form.  If it's not after an event, we only display the how met form.
	var yesLink = document.getElementById('friendLink');
	
	// prep popup
	if (yesLink) {
		// it's after the event, so we hide the how met form by default
		setVisibility('requestFriendshipForm', false);
	}
		
	document.getElementById('requestFriendshipForm_howWeMetText').value = "";
	
	// insert person's name into the popup
	var friendPopup = document.getElementById(friendPopupId);
	var friendNameEls = getElementsByClass('friendName', friendPopup, 'span');
	
	for (var i = 0; i < friendNameEls.length; i++) {
		friendNameEls[i].innerHTML = firstName + " ";
	}

	if (yesLink) {
		// not present if it's before an event
		yesLink["friendUrl"] = friendUrl;
		yesLink["idToUpdate"] = idToUpdate;
	}
	
	var formEl = document.getElementById('requestFriendshipForm');
	formEl.getAttributeNode('action').value = friendUrl;
	formEl["idToUpdate"] = idToUpdate;
	
	overlay(curEl, friendPopupId);
	return false;
}

// Event comments
var commentPopupId = 'commentPopup';
function showEventCommentPopup(curEl, submitUrl) {
	var formEl = document.getElementById('eventCommentOnResponseForm');
	formEl.setAttribute('action', submitUrl);
	overlay(curEl, commentPopupId);
	
	setTimeout(function() { formEl.eventCommentOnResponseForm_comments.focus(); }, 100);
	return false;
}

// View larger picture lightbox
var lightboxBgId='lightboxBg';
var lightboxPicId='lightboxPic';
function showLightbox() {
	setVisibility(lightboxBgId, true);
	setVisibility(lightboxPicId, true);
	
	var bodyHeight = document.body.offsetHeight;
	var windowHeight = window.innerHeight;
		
	if (!windowHeight)
		windowHeight = document.documentElement.clientHeight;
		
	document.getElementById(lightboxBgId).style.height = (Math.max(bodyHeight, windowHeight) + 190) + "px";
	
	var picEl = document.getElementById(lightboxPicId).getElementsByTagName("img")[0];
	picEl.style.marginTop = Math.max(0, (windowHeight - picEl.offsetHeight) / 2) + "px";	
}

function hideLightbox() {
	setVisibility(lightboxBgId, false);
	setVisibility(lightboxPicId, false);
}

// Popup warning for trying to use Yahoo e-mail address
function checkForBadEmailProviders(obj) {
  if(obj.value.indexOf("@yahoo.com") > -1) {
    setVisibility('badEmailProviderPopup', true);
  } else {
    setVisibility('badEmailProviderPopup', false);
  }
}

// Status messages
var statusEl;
var statusOrigHeight;

function showStatus(el) {
	statusEl = getElementsByClass('statusMsgSm', el)[0];
	statusOrigHeight = statusEl.style.height;
	statusEl.style.height = "auto";
	statusEl.style.whiteSpace = 'normal';
}

function hideStatus(el) {
	statusEl.style.height = statusOrigHeight;
	statusEl.style.whiteSpace = 'nowrap';
}