// New javascript functions here: MC 10.02.08

// the admin site uses newRelation to add a new child/partner/family member entry for a new or current artist.
// It adds a new "display line" in the current add/change profile form, and adds a new entry to the family and talent2family tables.

// Note: there are two ways to deal with "adding" a new family member.

// Method 1: First, display the blank line, allow the admin to put the values in the form, then save it. So nothing gets added to the database until the form is saved.

// Method 2: display the blank line and save to the database at the same time. This is the way I'll do it for now, which has the "disadvantage" (not really, but more of a "messy" solution) of
// creating blank entries, but has the advantage of being able to save a database ID directly in the form. 

// newRelation() should only be called on a page which includes a div with the ID of "relationList", since it adds a new line into that div.


function newRelation()
{


}




// saveNote - used on admin's shortlist page to create or update a note for a shortlist.
// we need to save the new note in the database, and change the "Save Note" button to a disabled "Saved" when done.

// refreshNote is called when we change the note field, and does the opposite (but doesn't do any database work).

function saveNote(listid)
{
document.getElementById('savenote-' + listid).disabled=true;
document.getElementById('savenote-' + listid).value='Saved';

note = document.getElementById('listnotes-' + listid).value;
//alert('List: ' + listid + ', note: ' + note);
if (ajax) {

var idvalue=encodeURIComponent(listid)
var notevalue=encodeURIComponent(note)

	ajax.open('get','savenote.php?id=' + idvalue + '&note=' + notevalue);
//	ajax.onreadystatechange = handle_savenote;
	ajax.send(null);
	}
	else
	{
		alert('Cannot save note');
	}


}

function handle_savenote()
{
if ((ajax.readyState == 4) && (ajax.status == 200))
	{
	alert(ajax.responseText);
	}

}


function refreshNote(listid)
{
document.getElementById('savenote-' + listid).disabled=false;
document.getElementById('savenote-' + listid).value='Save Note';
}


// revealdiv - used in list_shortlist.php, when admin is logged in and we display multiple shortlists.
// by default, each list hides its contents, for brevity. We display a "reveal" click, which changes the thumbnail
// display to "block" (and changes itself to "hide", which has the opposite effect, and runs hidediv).

// the thumbnail div has an ID of "list-n"; the click div has an ID of "click-n" where n is the listid passed to the function

// changes Dec 9, 2008. As the number of lists grows, the shortlist page takes longer to load, since we're preloading
// all the thumbnails. This is a waste. I'm going to switch to AJAX to pull up only the thumbnails I want to show.


function revealdiv(listid, adminid)
{
	listname = "list-" + listid;
	clickname = "click-" + listid;
	
//	alert("now looking for thumbnails: listid is " + listid + ", adminid is " + adminid);
	
	if (ajax) {

	ajax.open('get','showthumbs.php?id=' + adminid + '&list=' + listid);
	ajax.onreadystatechange = handle_showthumbs;
	ajax.send(null);
	}
	else
	{
		alert('Cannot show thumbs');
	}
	
	
	
	
	document.getElementById(listname).style.display='block';
	document.getElementById(clickname).innerHTML = '<a href="#" onclick="hidediv(\'' + listid + '\',\'' + adminid  + '\'); return false;" style="text-decoration:none; font-size:10pt; color:red;"> (Hide thumbs)</a>';
}

function handle_showthumbs()
{
if ((ajax.readyState == 4) && (ajax.status == 200))
	{
	// populate the list div with the results we got from the showthumbs PHP script.	
	document.getElementById(listname).innerHTML = ajax.responseText;
	}

}

// we don't technically use adminid in the hidediv function, but we do need to pass it in so we can pass it on to the showdiv function.

function hidediv(listid, adminid)
{
	listname = "list-" + listid;
	clickname = "click-" + listid;
	document.getElementById(listname).style.display='none';
	document.getElementById(clickname).innerHTML = '<a href="#" onclick="revealdiv(\'' + listid + '\',\'' + adminid  + '\'); return false;" style="text-decoration:none; font-size:10pt; color:green;"> (Show thumbs)</a>';
}




function listContacts()
{
if (ajax) {
	ajax.open('get','loadcontacts.php');
	ajax.onreadystatechange = handle_refreshlist;
	ajax.send(null);
	}
	else
	{
		alert('Cannot load contacts');
	}


}

function handle_refreshlist()
{
if ((ajax.readyState == 4) && (ajax.status == 200))
	{
	// populate the list div with the results we got from the loadcontacts PHP script.	
	document.getElementById('contactdiv').innerHTML = ajax.responseText;
	}

}



function deleteContact()
{
// this function is launched when the user clicks "Delete contact" in email2.php (the email shortlist page)
// it needs to retrieve the values in the dropdown list or form fields, delete that entry, clear the form values and
// reload the list.

var myIndex = document.getElementById('contactlist').selectedIndex;
var this_stuff = document.getElementById('contactlist').options[myIndex].value;
var splitstuff = this_stuff.split('|');
this_id = splitstuff[0];
this_name = splitstuff[1];
this_company = splitstuff[2];
this_email = splitstuff[3];
if (confirm ('Are you sure you want to delete ' + this_name + '/' + this_company + '/' + this_email + ' ?'))
{
if (ajax) {
	ajax.open('get','deletecontact.php?uid=' + this_id);
	ajax.onreadystatechange = handle_deletecontact;
	ajax.send(null);
	}
	else
	{
		alert('Cannot delete contact');
	}
}
}


function handle_deletecontact() {

if ((ajax.readyState == 4) && (ajax.status == 200))
	{
	document.sendEmail.email_to.value="";
	document.sendEmail.company_to.value="";
	document.sendEmail.contact_name.value="";
	listContacts();	// refreshes the list
	}
}




function swapContacts()
{
// this function is launched when the user changes the list of pre-populated contacts in the admin's shortlist page.
// it does some parsing and populates the form values accordingly.

var myIndex = document.getElementById('contactlist').selectedIndex;
var this_stuff = document.getElementById('contactlist').options[myIndex].value;
if (this_stuff != "")
{
	var newIndex = myIndex - 2;		// because myIndex is offset by 2 blank lead-in entries, "Choose..." and "-----".

	// this_stuff looks something like "20|matt@30throad.com|Matt's Wonderful Widgets|Matt Clifton"
	var splitstuff = this_stuff.split('|');
	this_id = splitstuff[0];
	this_email = splitstuff[1];
	this_company = splitstuff[2];
	this_name = splitstuff[3];

//	alert ("I have email: " + this_email + ", company: " + this_company + ", name: "+ this_name);
	document.sendEmail.email_to.value=this_email;
	document.sendEmail.company_to.value=this_company;
	document.sendEmail.contact_name.value=this_name;
	
	// also, if the value is not "", display the "delete this contact" option.
	
	document.getElementById('deletecontact').style.display="inline";
	
}
else	// if the value is null, hide the deletecontact option
{
	document.getElementById('deletecontact').style.display="none";
}


}

function newAdminList()
{

// 05.10.09 MC Added encodeURIcomponent to ensure that values containing "&" are transferred correctly.
// 05.11.09 MC Changed to "escape" to deal with apostrophes. It's older and won't handle unicode.

newListName = escape(document.getElementById('newlist').value);
//alert ('In common.js I have: ' + newListName);

if (ajax) {
	ajax.open('get','newadminlist.php?name=' + newListName);
	ajax.onreadystatechange = handle_addlist;
	ajax.send(null);
	}
	else
	{
		alert('Cannot create new shortlist');
	}
}

function handle_addlist()
{
// need to reload the shortlist dropdown to take account of the new entry, and set the selected item
// to be that new entry.

if ((ajax.readyState == 4) && (ajax.status == 200))
	{
	
	// now reload the list.
	document.getElementById('admindiv').innerHTML = ajax.responseText;
	

	}


}


function deleteAdminList(listid)
{
global_listid = listid;
// first, let's make sure we want to do this

	answer = confirm('Are you sure you want to remove this shortlist from the database?');
	
	if (answer)
	{
	if (ajax) {
		ajax.open('get','deleteadminlist.php?listid=' + listid);
		ajax.onreadystatechange = handle_deletelist;
		ajax.send(null);
		}
	}

}

function handle_deletelist()
{
if ((ajax.readyState == 4) && (ajax.status == 200))
	{
	// now hide the div that we're talking about
	thisid = 'listdiv-' + global_listid;
	document.getElementById(thisid).style.display='none';
	}
}




function adminlogin(n)		// where n=login stage
{
// this function swaps the "Admin" text for a login box.


	if (n==1)	// REVEAL LOGIN BOX
	{
	document.getElementById('adminbox').innerHTML = '<input name="login" id="login" type="text" size="8" /> <input type="button" value="Go" onclick="javascript:adminlogin(2); " />';
	}
	
	if (n==2)	//  LOGIN
	{
	
	if (ajax) {

		var password = document.getElementById('login').value; 
	
		ajax.open('get','adminlogin.php?log=in&password=' + password);
		ajax.onreadystatechange = handle_login;
		ajax.send(null);
		
		// for some reason, reloading the page means that the cookie does not get set first.
		// this means that when I reload, the page shows that admin is not logged in.
		
	//	window.location.reload();
		}
		else
		{
		alert('Admin cannot log in from this computer');
		}
		
	}
	
	
	if (n==3)	// LOGOUT
	{
	
	if (ajax) {

		ajax.open('get','adminlogin.php?log=out');
		ajax.onreadystatechange = handle_logout;
		ajax.send(null);
		}
		else
		{
		alert('Admin cannot log out from this computer');
		}	
		
	}
}


function handle_login() {

if ((ajax.readyState == 4) && (ajax.status == 200))
	{
	if (ajax.responseText != "false")
		{
		document.getElementById('adminbox').innerHTML = '<a href="#" onclick="javascript:adminlogin(3); return false;" />Logout admin</a>';

		// this is the div on certain pages which should be visible only to the admin.
		// right now, adminlogin.php returns the shortlist bar only.
		
		//document.getElementById('admindiv').innerHTML = ajax.responseText;

		// we want to reload the page in certain situations.
		
		thisURL = document.location.href;
		if (thisURL.match("list_shortlist.php")!=null)
		{
			window.location.reload();
		}
		

		}
	}
}


function handle_logout() {

if ((ajax.readyState == 4) && (ajax.status == 200))
	{
	if (ajax.responseText == "true")
		{
		document.getElementById('adminbox').innerHTML = '<a href="#" onclick="javascript:adminlogin(1); return false;">Admin login</a>';
		document.getElementById('admindiv').innerHTML = "";
		}
	}
}


// Catch JSON replies
var fN = function callBack(o) {
  myDebug(o.responseText);
  var resp = eval('(' + o.responseText + ')');
  if(resp['debug']) {
    myDebug(resp["debug"]);
  }
  // Put up a Status message and fade it out
  if(resp['status']) {
    div = document.createElement("div");
    div.className='status'; 
    div.innerHTML = resp['status'];
    pos = YAHOO.util.Dom.getXY(resp['elem']);
    div.style.visibility = 'hidden'
    document.body.appendChild(div);
    YAHOO.util.Dom.setXY(div,[pos[0],pos[1]+40]);
    div.style.visibility = 'visible'
    fnc = function() {
      if(resp['reset']) { 
         document.forms[resp['formName']].reset();
      }
      window.location.reload(false);
    }
    fade(div,2,fnc);
  }
  // Flash the field that had the error
  if(resp['validate_error']) {
    var el = document.getElementById(resp['validate_error']);
    var over = el.cloneNode(true);
    over.style.position = 'absolute';
    over.style.zIndex=9999;
    addClass(over,'error');
    over.style.visibility = 'hidden'
    document.body.appendChild(over);
    YAHOO.util.Dom.setXY(over, YAHOO.util.Dom.getXY(el));
    over.style.visibility = 'visible'

    // Whoa - nested onCompletes can look a bit confusing ;)
    fade(over,0.5, function() { 
      unfade(over,0.5, function() { 
        fade(over,2, function() { 
          over.parentNode.removeChild(over);
        } ); 
      } );
    } );
  } 
  // Fill in formName
  if(resp['load_item']) {
    var oForm = document.forms[resp['formName']];
    for(var k in resp.load_item[0]) {
      if(oForm['f_'+k]) {
        if(resp.load_item[0][k].length) 
             oForm['f_'+k].value = resp.load_item[0][k];
        else oForm['f_'+k].value = oForm['desc_'+k].value;
      }
    }
  }
}

var callback = { success:fN }

// Post form fields from formName to target
function postForm(target,formName) {
  YAHOO.util.Connect.setForm(formName);
  YAHOO.util.Connect.asyncRequest('POST',target,callback);
}

function postData(target,data) {
  YAHOO.util.Connect.asyncRequest('POST',target,callback,data);
}

function addClass(o,cls) {
  o.className+=" "+cls;
}

function delClass(o,cls) {
  o.className=o.className.replace(new RegExp(" "+cls+"\\b"), "");
}

function fade(o, dur, fnc) {
  var oAnim = new YAHOO.util.Anim(o, {opacity: {from: 1, to: 0}}, dur);
  if(fnc) oAnim.onComplete.subscribe(fnc);
  oAnim.animate();
}

function unfade(o, dur, fnc) {
  var oAnim = new YAHOO.util.Anim(o, {opacity: {from: 0, to: 1}}, dur);
  if(fnc) oAnim.onComplete.subscribe(fnc);
  oAnim.animate();
}

// Javascript for the item table
function clickItemPost(event) {
  var target = YAHOO.util.Event.getTarget(event, true);
  if(target.nodeName=='TD') target = target.parentNode;
  postData('add.php','formName=fItem&load_item=' + target.id);
}

function mouseoverItem() {
  this.className = 'its';
}

function mouseoutItemEven() {
  this.className = 'it0';
}

function mouseoutItemOdd() {
  this.className = 'it1';
}

function fancyItems() {
  var oT = document.getElementById('tItems');
  var oTr = oT.getElementsByTagName('TR');
  for(var i=0; i<oTr.length; i++){
    YAHOO.util.Event.addListener(oTr[i], "mouseover", mouseoverItem);
    YAHOO.util.Event.addListener(oTr[i], "mouseout", i%2 ? mouseoutItemOdd:mouseoutItemEven);
    YAHOO.util.Event.addListener(oTr[i], "click", clickItemPost);
  }
}

// Javascript for the form entry section

function onfocusFormElem(event) {
  var target = YAHOO.util.Event.getTarget(event, true);
  var descElem = document.getElementById('desc_'+target.name);
  if(document.all) { addClass(this,'iefocus') } 
  if(this.value == descElem.value) { this.value = ''; }

}

function onblurFormElem(event) {
  var target = YAHOO.util.Event.getTarget(event, true);
  var descElem = document.getElementById('desc_'+target.name);
  if(document.all) { delClass(this,'iefocus') }
  if(this.value == '') { this.value = descElem.value; }
}

function addHidden(oElm) {
  var newE = document.createElement("INPUT")
  newE.type = "hidden"; newE.value = oElm.value;
  newE.name = "desc_"+oElm.name; newE.id = newE.name;
  oElm.parentNode.insertBefore(newE, oElm);
}

function fancyForm() {
  var oF = document.forms['fItem'];
  var oElm = oF.getElementsByTagName('INPUT');
  var els = oElm.length;
  for(var i=0; i<els; i++) {
    if(oElm[i].type != 'hidden' && oElm[i].type != 'submit' && oElm[i].type != 'reset') {
      YAHOO.util.Event.addListener(oElm[i], "focus", onfocusFormElem);
      YAHOO.util.Event.addListener(oElm[i], "blur", onblurFormElem);
      addHidden(oElm[i]); i++; els++;
    }
  } 
  oElm = oF.getElementsByTagName('TEXTAREA');
  els = oElm.length;
  for(var i=0; i<els; i++) {
    if(oElm[i].type != 'hidden') {
      YAHOO.util.Event.addListener(oElm[i], "focus", onfocusFormElem);
      YAHOO.util.Event.addListener(oElm[i], "blur", onblurFormElem);
      addHidden(oElm[i]); i++; els++;
    }
  } 
  oElm = oF.getElementsByTagName('SELECT');
  els = oElm.length;
  for(var i=0; i<els; i++) {
    if(oElm[i].type != 'hidden') {
      addHidden(oElm[i]); i++; els++;
    }
  } 
}

function myDebug(msg) {
  var oDebug = document.getElementById('debug');
  if(typeof(msg)=='object') {
    tmp = '';
    for(var i in msg) {
      tmp += i + " = " + msg[i] + "<br />";
    }
  } else tmp = msg;
  oDebug.innerHTML = [oDebug.innerHTML,tmp,'<br />'].join('');
  oDebug.scrollTop = oDebug.scrollHeight * 2;
}


