var capsi_xmlHttp

function isEnter( evt )
{
	var keyCode = evt.which ? evt.which : evt.keyCode
	return (keyCode == 10 || keyCode == 13)
}

function GetXmlHttpObject()
{ 
	var objXMLHttp=null

	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}

	return objXMLHttp
}

function urlEncode( s )
{
        s = s.replace("&", "%26");
        s = s.replace("+", "%2B");

        return s;
}

function htmlSpecialChars( s )
{
        s = s.replace("&", "&amp;");
        s = s.replace("<", "&lt;");
        s = s.replace(">", "&gt;");

        return s;
}

function setVisibleById( id, visible )
{
	updateVisibleById( id, visible, false )
}

function setVisible( div, visible )
{
	updateVisible( div, visible, false )
}

function updateVisibleById( id, visible, now )
{
	var div = document.getElementById(id)
	updateVisible( div, visible, now )
}

function updateVisible( div, visible, now )
{
	if ( !div )
		return

	if ( visible && !isVisible(div) )
	{
		div.className = div.className.replace('hidden', '');
		div.className = div.className.replace('hiding', '');
		if ( div.className.indexOf( 'showing' ) == -1 )
			div.className += " showing";
		if ( now )
		{
			div.style.display = "block";
			div.style.visibility = "visible";
		}
		else
		{
			div.style.display = "none";
			$( '#' + div.id ).slideDown("slow");
		}
	}
	else if ( !visible && isVisible(div) )
	{
		div.className = div.className.replace('showing', '');
		if ( div.className.indexOf( 'hiding' ) == -1 )
			div.className += " hiding";
		if ( now )
		{
			div.style.display = "none";
			div.style.visibility = "hidden";
		}
		else
		{
			$( '#' + div.id ).slideUp();
		}
	}
}

function isVisible( div )
{
	if ( !div )
		return

	return ( div.style.visibility != "hidden" && div.style.display != "none" && div.className.indexOf('hidden') == -1 && div.className.indexOf('hiding') == -1 || div.className.indexOf('showing') != -1 );
}

function showTab( array, id )
{
	for ( var i=0; i<array.length; i++ )
		setVisibleById( array[i], i==id );
}

function clearList( id )
{
	var ul = document.getElementById( id )

	var length = ul.childNodes.length
	for ( var i=0; i<length ; i++ )
		ul.removeChild(ul.childNodes[0])
}

function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

function prependChild(parent, node) {
	parent.insertBefore(node, parent.firstChild);
}

function findPosX(obj)
{
        var curleft = 0;
        if (obj.offsetParent)
        {
                while (obj.offsetParent)
                {
                        curleft += obj.offsetLeft
                        obj = obj.offsetParent;
                }
        }
        else if (obj.x)
                curleft += obj.x;
        return curleft;
}

function findPosY(obj)
{
        var curtop = 0;
        if (obj.offsetParent)
        {
                while (obj.offsetParent)
                {
                        curtop += obj.offsetTop
                        obj = obj.offsetParent;
                }
        }
        else if (obj.y)
                curtop += obj.y;
        return curtop;
}

function arrayJoin( array )
{
	var txt = ""

	for ( var i=0 ; i<array.length ; i++ )
		txt += array[i] + ";"

	return txt
}

function smartJoin( array )
{
	if ( array.length == 0 )
		return "";

	var txt = ""

	for ( var i=0 ; i<array.length ; i++ )
	{
		if ( i== 0 )
			txt += array[i];
		else if ( i==array.length-1 )
			txt += " and " + array[i]
		else
			txt += ", " + array[i]
	}

	return txt
}

function toggleTreeView( id )
{
	var div = document.getElementById( 'tree-' + id + '-details' );

	var li = document.getElementById( 'tree-' + id );
	var img = li.getElementsByTagName('img')[0];
	if ( img.src.indexOf('closed') != -1 || img.src.indexOf('open') != -1 )
	{
		if ( isVisible(div) )
			img.src = "http://content.capsi.com/tmp/closed.gif";
		else
			img.src = "http://content.capsi.com/tmp/open.gif";
	}

	setVisible( div, !isVisible(div) );
}

function addComment( objectId, parentId )
{
	setVisibleById( 'actionBarEdit', false, true );

	$('#actionBarEditContent').html( actionBarCloseButton() );
	$('#actionBarEditStatus').html( ajaxLoadImage() + 'Loading comment form...' );

	setVisibleById( 'actionBarEdit', true );

	var jsonData = { objectId: objectId, parentId: parentId };
        $.post( "/ajax/commentForm.php", jsonData, function(data) { processActionBarForm(data); }, "json" );
	return false;
}

function addPm( userLogin )
{
	setVisibleById( 'actionBarEdit', false, true );

	$('#actionBarEditContent').html( actionBarCloseButton() );
	$('#actionBarEditStatus').html( ajaxLoadImage() + 'Loading private message form...' );

	setVisibleById( 'actionBarEdit', true );

	var jsonData = { userLogin: userLogin };
        $.post( "/ajax/pmForm.php", jsonData, function(data) { processActionBarForm(data); }, "json" );
	return false;
}

function addConcertInvite( concertId )
{
	setVisibleById( 'actionBarEdit', false, true );

	$('#actionBarEditContent').html( actionBarCloseButton() );
	$('#actionBarEditStatus').html( ajaxLoadImage() + 'Loading concert invite/notification form...' );

	setVisibleById( 'actionBarEdit', true );

	var jsonData = { concertId: concertId };
        $.post( "/ajax/concertInviteForm.php", jsonData, function(data) { processActionBarForm(data); }, "json" );
	return false;
}

function processActionBarForm( data )
{
	$('#actionBarEdit').hide();
	$('#actionBarEditContent').html( actionBarCloseButton() + data.html );
	$('#actionBarEditStatus').empty();
	$('#actionBarEdit').slideDown("slow");
}

function postComment( el )
{
	var formEl = el.parentNode.parentNode.parentNode;
	if ( !formEl )
		return true

	var jsonData = { json: true, id: formEl.id };
	$("#" + formEl.id + " :input").each( function () {
		if ( this && this.name )
		{
//			alert( "jsonData." + this.name + " = \"" + this.value + "\"" );
			eval( "jsonData." + this.name + " = \"" + this.value + "\"" );

			if ( this.name.indexOf( "submit_" ) != -1 )
				this.disabled = true;
		}
	} );

	$('#actionBarEditStatus').html( ajaxLoadImage() + 'Saving comment...' );
	$.post( "/user/postcomment.html", jsonData, function(data) { processComment(data); }, "json" );

	return false;
}

function postPm( el )
{
	var formEl = el.parentNode.parentNode.parentNode;
	if ( !formEl )
		return true

	var jsonData = { json: true, id: formEl.id };
	$("#" + formEl.id + " :input").each( function () {
		if ( this && this.name )
		{
//			alert( "jsonData." + this.name + " = \"" + this.value + "\"" );
			eval( "jsonData." + this.name + " = \"" + this.value + "\"" );

			if ( this.name.indexOf( "submit_" ) != -1 )
				this.disabled = true;
		}
	} );

	$('#actionBarEditStatus').html( ajaxLoadImage() + 'Saving private message...' );
	$.post( "/user/pm/send.html", jsonData, function(data) { processPm(data); }, "json" );

	return false;
}

function postConcertInvite( el )
{
	return true;
	var formEl = el.parentNode.parentNode.parentNode;
	if ( !formEl )
		return true

	var jsonData = { json: true, id: formEl.id };
	$("#" + formEl.id + " :input").each( function () {
		if ( this && this.name )
		{
//			alert( "jsonData." + this.name + " = \"" + this.value + "\"" );
			eval( "jsonData." + this.name + " = \"" + this.value + "\"" );

			if ( this.name.indexOf( "submit_" ) != -1 )
				this.disabled = true;
		}
	} );

	$('#actionBarEditStatus').html( ajaxLoadImage() + 'Saving concert invitations...' );
	$.post( "/user/calendar/invite.html", jsonData, function(data) { processConcertInvite(data); }, "json" );

	return false;
}

function processComment( data )
{
	if ( data.errors )
	{
		$('#actionBarEditStatus').html( 'Error saving comment:' + data.errors );
		$('#submit_'+data.submitId).attr("disabled", "");
		return;
	}

	$('#actionBarEditContent').html( actionBarCloseButton() );
	$('#actionBarEditStatus').html( '<p>\nYour comment has been saved.</p>\n' );
}

function processPm( data )
{
	if ( data.errors )
	{
		$('#actionBarEditStatus').html( 'Error saving private message:' + data.errors );
		$('#submit_'+data.submitId).attr("disabled", "");
		return;
	}

	$('#actionBarEditContent').html( actionBarCloseButton() );
	$('#actionBarEditStatus').html( '<p>\nYour private message for ' + data.userLogin + ' has been saved.</p>\n' );
}

function processConcertInvite( data )
{
	if ( data.errors )
	{
		$('#actionBarEditStatus').html( 'Error saving concert invitation:' + data.errors );
		$('#submit_'+data.submitId).attr("disabled", "");
		return;
	}

	$('#actionBarEditContent').html( actionBarCloseButton() );
	$('#actionBarEditStatus').html( '<p>\nYour concert invitation has been saved.</p>\n' );
}

function ActionBar(sel,options)
{
    var _I = this;       
    var _sb = null;
 
    // options    
    this.elementId = "actionBar";
    this.prependMultiline = true;   
    this.afterTimeoutText = null;
 
    this.cssClass = "actionBar";
    this.highlightClass = "actionBarFlash";
    this.errorClass = "error";
    this.additive = false;   
 
    $.extend(this,options);
 
    if (sel)
      _sb = $(sel);
 
    // create actionBar object manually
    if (!_sb)
        _sb = $('#actionBar');
 
    this.show = function(message,timeout,isError)
    {            
        _sb.show();        
 
        if (timeout)
        {
            if (isError)
                _sb.addClass(_I.errorClass);
            else
                _sb.addClass(_I.highlightClass);
 
            setTimeout( 
                function() {
                    _sb.removeClass(_I.highlightClass); 
                    if (_I.afterTimeoutText)
                       _I.show(_I.afterTimeoutText);
                },
                timeout);
        }                
    }  
    this.release = function()
    {
        if(_actionBar)
            $(_actionBar).remove();
    }       
}
// use this as a global instance to customize constructor
// or do nothing and get a default status bar
var _actionBar = null;

function flashStatus(message,timeout,additive,isError)
{
    if (!_actionBar)
        _actionBar = new ActionBar();
    _actionBar.show(message,timeout,additive,isError);
    window.focus();
}

function updateStatus()
{
        var _sb = $('#actionBar');
	if ( !_sb )
		return;

	var jsonData = { json: true };
	$.get( "/ajax/statusbar.php", jsonData, function(data) { processStatus(data); }, "json" );
}

var newMsgs = 0
var friendRequests = 0
function processStatus(data)
{
	var show = 0;
	var friendsIcon = 0;
	var msgIcon = 0;
	var requestsIcon = 0;

	var actionBarTxt = "";

	if ( data.msgsUnread>0 )
	{
		$('#actionBar-messages').text(data.msgsUnread);
		++msgIcon;
		++show;
	}
	else
		$('#actionBar-messages').text('');

	if ( data.msgsNew > newMsgs )
	{
		actionBarTxt = "New private message!";
		++show;
	}
	newMsgs = data.msgsNew;

	if ( data.friendsOnline.length>0 )
	{
		$('#actionBar-friendsOnline').text(data.friendsOnline.length);
		var userLogins = new Array();
		for( var i=0; i<data.friendsOnline.length; ++i )
			userLogins[userLogins.length] = data.friendsOnline[i][1];
		$('#actionBar-friendsOnline').text( data.friendsOnline.length + ": " + smartJoin( userLogins ) );
		++friendsIcon;
		++show;
	}
	else
		$('#actionBar-friendsOnline').text('');

	if ( data.friendRequests.length>0 )
	{
		$('#actionBar-friendRequests').text(data.friendRequests.length);
		var userLogins = new Array();
		for( var i=0; i<data.friendRequests.length; ++i )
			userLogins[userLogins.length] = '<a href="javascript:actionFriendRequest(' + data.friendRequests[i][0] + ", '" + data.friendRequests[i][1] +  "', '" + data.friendRequests[i][2] + "', '" + data.friendRequests[i][3] + "'" + ')">' + data.friendRequests[i][1] + '</a>';
		$('#actionBar-friendRequests').html( data.friendRequests.length + ": " + smartJoin( userLogins ) );
		++requestsIcon;
		++show;
	}
	else
		$('#actionBar-friendRequests').text('');

	if ( data.friendRequests.length > friendRequests )
	{
		actionBarTxt = "New friend request!";
		++show;
	}
	friendRequests = data.friendRequests.length;

	if ( data.text.length>0 )
	{
		++show;
		actionBarTxt = data.text;
	}

	$('#actionBarTime').text( data.time ); 
	$('#actionBarTxt').text(actionBarTxt); 

	if ( data.userId == 1 )
		++show;

	setVisibleById( 'actionBar', show );

	if ( requestsIcon )
		$('#actionBar-friendRequests-icon').slideDown();
	else
		$('#actionBar-friendRequests-icon').hide();
	if ( msgIcon )
		$('#actionBar-messages-icon').slideDown();
	else
		$('#actionBar-messages-icon').hide();
	if ( friendsIcon )
		$('#actionBar-friendsOnline-icon').slideDown();
	else
		$('#actionBar-friendsOnline-icon').hide();

	$('#actionBar').removeClass( "actionBarFlash" );
	if ( actionBarTxt.length>0 )
		flashStatus( actionBarTxt, 2000 ); 

	setTimeout( "updateStatus()", 10000 );
}

function toggleActionBar()
{
	$('#actionBar').toggleClass( "actionBarMini" );
	if ( $('#actionBar').hasClass( "actionBarMini" ) )
		$('#actionBarToggle').attr( 'src', 'http://content.capsi.com/tmp/closed.gif' );
	else
		$('#actionBarToggle').attr( 'src', 'http://content.capsi.com/tmp/open.gif' );
}

function actionBarWrite()
{
        setVisibleById( 'actionBarEdit', false, true );

	var html = actionBarCloseButton();
	html += '<p>\nGot something on your mind? Let it out!</p>\n';
	html += '<ul>';
	html += '<li>Write <a href="/user/journal/edit.html">new journal entry</a></li>';
	html += '<li>Write a <a onclick="return addPm(\'\')" href="/user/pm/send.html">private message to a user</a></li>';
	html += '</ul>';
	$('#actionBarEditContent').html( html );
	$('#actionBarEditStatus').empty();

        setVisibleById( 'actionBarEdit', true );
}

function actionFriendRequest( id, login, url, img )
{
	setVisibleById( 'actionBarEdit', false, true );

	var html = actionBarCloseButton();
	html += '<p><strong>' + login + '</strong> wants to be friends with you!</p>\n';
	$('#actionBarEditContent').html( html );

	$('#tree-wall #userBox-' + id + "_\\S*").remove();
	var newEl = $("#_actionBarFriendRequest").clone().attr( "id", "actionBarFriendRequest-" + id );

	while( newEl.html().indexOf("__userId__") != -1 )
		newEl.html( newEl.html().replace( "__userId__", id ) );
	while( newEl.html().indexOf("/profiles/__userlogin__/") != -1 )
		newEl.html( newEl.html().replace( "/profiles/__userlogin__/", url ) );
	while( newEl.html().indexOf("__userLogin__") != -1 )
		newEl.html( newEl.html().replace( "__userLogin__", login ) );

	newEl.html( newEl.html().replace( "/img/user-default-48.png", img ) );

	newEl.appendTo( "#actionBarEditContent" );
	setVisibleById( 'actionBarFriendRequest-' + id, true );
	setVisibleById( 'actionBarEdit', true );
}

function closeActionBarEdit()
{
	setVisibleById( 'actionBarEdit', false );
	$('#actionBarEditContent').empty();
	$('#actionBarEditStatus').empty();
}

function manageFriends(userId,action)
{
	var statusDiv = document.getElementById( "status-" + userId );
	statusDiv.innerHTML= "<img src=\"http://content.capsi.com/img/crystal/action.gif\" width=\"16\" height=\"16\" alt=\"\" /> Saving..."
	updateVisible( statusDiv, true, true )

	updateVisibleById( "accept-" + userId, false, false )
	updateVisibleById( "reject-" + userId, false, false )
	updateVisibleById( "block-" + userId, false, false )

	var jsonData = { json: action, userId: userId };
	$.post( "/user/friends/manage.html", jsonData, function(data) { processManageFriends(data); }, "json" );

	return false
} 

function processManageFriends( data )
{
	var userId = data.userId;
	var statusTxt = data.statusTxt;
	var hide = data.hide;
	var moveBox = data.moveBox;
	var move = data.move;

	if ( statusTxt != 0 )
	{
		var statusDiv = document.getElementById( "status-" + userId )
		statusDiv.innerHTML=statusTxt
		setVisible( statusDiv, true )
	}

	if ( moveBox != 0 )
	{
		//moveUserBox(userId, moveBox)
		setTimeout( "moveUserBox('"+ userId +"', '" + moveBox + "')", 1000 )
	}
	else if ( hide == 1 )
	{
		setTimeout( "hideUserBox('"+ userId +"')", 1000 )
	}

	if ( $( '#actionBarFriendRequest-' + userId ) )
		setTimeout( 'setVisibleById( "actionBarEdit", false )', 1000 );
}

function hideUserBox( id )
{
	var div = document.getElementById("userBox-" + id  + "_\\S*" );

	// FIXME: only because userBox has min-height, can we remove that?
	div.style.minHeight = '0px';
	setVisible( div, false )
}

function moveUserBox( id, dest )
{
	var containerDiv = document.getElementById("friends-" + dest )
	var manageDiv = document.getElementById( "userBox-" + id + "_\\S*" )
	if ( manageDiv )
	{
		if ( containerDiv )
			containerDiv.appendChild(manageDiv)
		else
		{
			hideUserBox( id )
			return
		}

		var statusDiv = document.getElementById("status-"+id)

		var acceptDiv = document.getElementById("accept-"+id)
		var rejectDiv = document.getElementById("reject-"+id)
		var blockDiv = document.getElementById("block-"+id)

		updateVisible( statusDiv, false, true )

		if ( dest == "confirmed" )
		{
			setVisible( acceptDiv, false )
			var rejectImg = rejectDiv.getElementsByTagName('img')[0]
			rejectImg.alt = "Remove"
			rejectImg.title = "Remove from friends"
			setVisible( rejectDiv, true )
			var blockImg = blockDiv.getElementsByTagName('img')[0]
			blockImg.alt = "Block"
			blockImg.title = "Remove from friends and block"
			setVisible( blockDiv, true )
		}
		else if ( dest == "blockAct" )
		{
			var acceptImg = acceptDiv.getElementsByTagName('img')[0]
			if ( acceptImg )
			{
				acceptImg.alt = "Add to friends"
				acceptImg.title = "Add to friends"
			}
			setVisible( acceptDiv, true );

			var rejectImg = rejectDiv.getElementsByTagName('img')[0]
			rejectImg.alt = "Unblock"
			rejectImg.title = "Unblock user"
			setVisible( rejectDiv, true )

			setVisible( blockDiv, false )
		}
	}
}

function ajaxLoadImage()
{
	return '<img src="/img/ajaxload.gif" alt="" width="16" height="16" />&nbsp;';
}
function ajaxOkImage()
{
	return '<img src="/img/crystal/ok.png" alt="" width="16" height="16" />&nbsp;';
}

function actionBarCloseButton()
{
	return '<div class="floatR"><a href="javascript:closeActionBarEdit();" class="sprite closeSprite" title="Close"></a></div>';
}

$( function()
{
	// Curved corners
	$('.curvedBox').wrap('<div class="clear curveContainer">' + '</div>').corner( {
		tl: { radius: 5 },
		tr: { radius: 5 },
		bl: { radius: 5 },
		br: { radius: 5 },
		antiAlias: true,
		autoPad: false
	} );

	// Tooltips
	var xOffset = 5;
	var yOffset = 10;
	$('a.tooltip').hover(
		function(e)
		{
			this.t = this.title;
			this.title = "";
			$('body').append("<p id='tooltip'>" + this.t +"</p>");

			var top = "auto";
			var right = "auto";
			var bottom = "auto";
			var left = "auto";

			if ( e.pageX > window.innerWidth/2 )
				right = window.innerWidth - e.pageX + xOffset + "px";
			else
				left = e.pageX + xOffset + "px";

//			if ( e.pageY > window.outerHeight/2 )
//				bottom = window.outerHeight - e.pageY + yOffset + "px";
//			else
				top = e.pageY + yOffset + "px";

			$('#tooltip').css("top", top).css("right", right).css("bottom", bottom).css("left", left).fadeIn("slow");
	 	},
		function()
		{
			this.title = this.t;
			$('#tooltip').remove();
		}
	);

	$('a.tooltip').mousemove(
		function(e)
		{
			var top = "auto";
			var right = "auto";
			var bottom = "auto";
			var left = "auto";

			if ( e.pageX > window.innerWidth/2 )
				right = window.innerWidth - e.pageX + xOffset + "px";
			else
				left = e.pageX + xOffset + "px";

//			if ( e.pageY > window.outerHeight/2 )
//				bottom = window.outerHeight - e.pageY + yOffset + "px";
//			else
				top = e.pageY + yOffset + "px";

			$('#tooltip').css("top", top).css("right", right).css("bottom", bottom).css("left", left);
		}
	);

	// Action bar
        var _sb = document.getElementById('actionBar');
	if ( _sb )
	{
		setTimeout( 'updateStatus()', 500 );
		$('#main2, #main3').css( 'margin-bottom', '35px' );
	}
} );

var inputTypes = new Array( 'favArtists', 'seenArtists', 'friends', 'favCities', 'seenCities', 'seenVenues', 'seenConcerts', 'presets' )

function tagInput( name )
{
	for( var i=0 ; i<inputTypes.length ; ++i )
	{
		var link = document.getElementById( 'toggle-' + inputTypes[i] )

		if ( inputTypes[i] == name )
		{
			setVisibleById( inputTypes[i] + 'Tags', true )
			if ( link )
			{
				link.style.color = 'black';
			}
		}
		else
		{
			setVisibleById( inputTypes[i] + 'Tags', false )
			if ( link )
			{
				link.style.color = '#dd3333';
			}
		}
	}
}

function toggleTag( id )
{
	var tags = document.getElementById( 'tags' )
	var item = document.getElementById( id )
	var parent = item.parentNode

	if ( parent.id == 'taggedItems' )
	{
		var posF = id.indexOf('-')
		var posL = id.lastIndexOf('-')
		var objectId = id.substring( posF+1, posL )
		var type = id.substring( posL+1, id.length )

		var ul = document.getElementById( type + 'Tags' )
		ul.appendChild(item)

	        tags.value = tags.value.replace(";" + objectId + ";", "" );
	}
	else
	{
		var posF = id.indexOf('-')
		var posL = id.lastIndexOf('-')
		var objectId = id.substring( posF+1, posL )

		var ul = document.getElementById( 'taggedItems' )
		ul.appendChild(item)

		tags.value += ";" + objectId + ";"
	}
}
