var nn6;
var x, y;
var dobj;
var zone = Object();
var allNotes;
var newLeft;
var newTop;
var noteCount = 0;
var newNote = false;

var m_names = new Array("January", "February", "March", 
"April", "May", "June", "July", "August", "September", 
"October", "November", "December");


function initStickyNotes()
{
  //alert('initStickyNotes()');
  nn6=document.getElementById && !document.all;
  isdrag=false;
  zone.left = 10;
  zone.top = 10;
  zone.right = 2500;
  zone.bottom = 2500; 
  allNotes = document.createElement("div");
  allNotes.id = "allNotes";
  allNotes.style.left = -10+"px";
  allNotes.style.top = -10+"px";
  allNotes.style.width = 1+"px";
  allNotes.style.height = 1+"px";
/*
  allNotes.style.opacity = (100 / 100); 
  allNotes.style.MozOpacity = (100 / 100); 
  allNotes.style.KhtmlOpacity = (100 / 100); 
  allNotes.style.filter = "alpha(opacity="+100+")"; 
*/
  document.body.appendChild(allNotes);
}



function closeCitation(node) {
	allNotes.removeChild(node);
}

function copyCitationToClipboard(citation) {
  if (window.clipboardData) {
    window.clipboardData.setData("Text",citation);
  } else {
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="swf/_clipboard.swf" FlashVars="clipboard='+escape(citation)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
  }
}

function drawCitation(id) {
	
  var newDiv = document.createElement('div');
  var noteId = id;
  
  var now = new Date();
  
  var body = 'Stahl, S. M. (2008). Essential Psychopharmacology Online. Retrieved ' +
  		 m_names[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear() +
  		 ' from ';
  		 
  var url = window.location;
  
  var citation = body + ' ' + url;


if(!document.getElementById('citation_dragger')){
  newDiv.id = "citation_draggable";
  newDiv.className = "draggable";
  newDiv.onselectstart = new Function("return false;");
  newDiv.innerHTML = "<div id=\"citation_dragger\" class=\"dragger\">"+ 
  "<div id=\"citation_title\" onmouseup=\"setCurrent("+ noteCount +")\" >Citation</div>"+
  "<div style=\"position: absolute;  left: 530px; top: -1px; width:15px; height:10px; cursor: pointer; font: normal 20px Arial;\" onclick=\"closeCitation(this.parentNode.parentNode);\" title=\"close\">&#215;</div></div>"+
  "<div id=\"citation_note\" class=\"sticky-note\"><br>"+
  "<p id=\"citebody\">" + body + "</p>" +
  "<p id=\"citeurl\">" + url + "</p>" +
  //"<p>" +
  "<a style=\"float:left; width:30%;\"><div id=\"clipboard\">Copy</div></a>" + 
  //"<a style=\"cursor: pointer; float: left;\" onClick=\"javascript:copyCitationToClipboard('" + citation + "');\">Copy</a>" +  
  "<a style=\"cursor: pointer; float: right;\" onClick=\"window.open('http://www.apastyle.org/elecmedia.html');\">Visit apastyle.org</a>" +
  //"</p>" + 
  "<div style=\"clear: both;\"></div></div>";
  newDiv.style.left = 250+"px";
  newDiv.style.top = 250+"px";
  
  noteCount += 1;
  


  var elemAllNotes = document.getElementById("allNotes");
  if (elemAllNotes == null) {
  	initStickyNotes();
  	elemAllNotes = document.getElementById("allNotes");
  }
  elemAllNotes.appendChild(newDiv);
  
  initZero();
}


}


//sticky notes-------------

function drawNotes(){
	drawNote('','','','');
}

function drawNote(id, body, xposition, yposition){
	
	if(newNote) return;
		
	var newDiv = document.createElement('div');
  	var icon = 'sticky_pin_grey.gif';
	var function_ = trim(body).length != 0 ? 'closeNote(deleteNote(' + id + '), this.parentNode.parentNode);' : 'defaultCloseNote(this.parentNode.parentNode);'
	//default
	xposition = xposition == '' ? '170' : xposition;
	yposition = yposition == '' ? '335' : yposition;
	
  	newDiv.className = "draggable";
  	newDiv.onselectstart = new Function("return false;");
  
  	newDiv.innerHTML = 
  	//header area
  	"<div class=\"dragger\">" +
  		"<div style=\"position: absolute; left: 0px; top: 0px; width: 180px; height: 50px; padding-top: 2px; padding-left: 10px\" onmouseup=\"screenPosition('" + noteCount + "');\"></div>" +
  		"<div style=\"position: absolute; left: 160px; top: 2px; width:10px; height:10px; cursor: pointer;\" title=\"save\"> " + 
  			"<img id=\"img_" + noteCount + "\" open_id=\"" + noteCount + "\" open=\"close\" src=\"images/" + icon + "\"  note_id=\"" + id + "\" xpos=\"" + xposition + "\"  ypos=\"" + yposition + "\" onclick=\"javascript:void(0);\" />" +  
  		"</div>" +
  		"<div id=\"del_" + noteCount + "\" style=\"position: absolute; left: 180px; top: -1px; width:15px; height:10px; cursor: pointer; font: normal 20px Arial;\" title=\"delete\" onclick=\"" + function_ + "\" >" + 
  			"&#215;" + 
  		"</div>" + 
  	"</div>" +
  
  	//note area
  	"<div class=\"sticky-note\">" +
  		"<textarea wrap=\"yes\" id=\"note_" + noteCount + "\" style=\"border-style: none; padding: 0px 4px; background-color: #fefd9a; overflow:auto;  width:195px; height:175px;\" " + 
  			"onchange=\"imposeMaxLength(this, 300);addToNote(" + noteCount + ")\" " +
  			"onkeyup=\"imposeMaxLength(this, 300);addToNote(" + noteCount + ")\" >" + 
  			body + 
  		"</textarea> " +
  	"</div>";
  	 
  	newDiv.style.left = xposition + "px";
  	newDiv.style.top = yposition+"px";
  	
  	newNote = id == '' ? true : false;
 	noteCount += 1;
  	document.getElementById("allNotes").appendChild(newDiv);
}

function screenPosition(id){
	this.img = document.getElementById('img_' + id);
	this.img.xpos = newLeft;
	this.img.ypos = newTop;
	
	addToNote(id);	
}

function addToNote(id){
	
	var note = getNoteContent(id);
	if(note.length != 0){
		enableSave(id, note);
		enableDelete(id);
	}else{
		disableSave(id);
		disableDelete(id);
	}	
}

function trim(value) { 
	var _ret = value.replace(/^\s+|\s+$/g, ''); 
	return _ret.replace(/^(\&nbsp\;)+|(\&nbsp\;)+$/g, ''); 
}

function noteXPostion(id){
	this.img = document.getElementById('img_' + id);
	
	var x = this.img.xpos;
	if(x == undefined)
		x = this.img.getAttribute('xpos');
	
	return x;
}

function noteYPostion(id){
	this.img = document.getElementById('img_' + id);
	
	var y = this.img.ypos;
	if(y == undefined)
		y = this.img.getAttribute('ypos');
		
	return y;
}

function getNoteId(id){
	this.img = document.getElementById('img_' + id);
	
	var noteId = this.img.note_id;
	if(noteId == undefined)
		noteId = this.img.getAttribute('note_id');
	
	return noteId;
}

function setNoteId(id, noteId){
	this.img = document.getElementById('img_' + id);
	this.img.note_id = noteId;
}

function getNoteContent(id){
	this.note = document.getElementById('note_' + id);
	var note = trim(this.note.value);
		
	return note;
}
	
function enableSave(id, note){
	var x = noteXPostion(id);
	var y = noteYPostion(id);
	var noteId = getNoteId(id);
	
	enableIcon(id);
	this.img = document.getElementById('img_' + id);
	this.img.onclick = function onclick(event){
							saveNotes(id, noteId, note, x , y);
					   }
}

function disableSave(id){
	disableIcon(id);
	this.img = document.getElementById('img_' + id);
	this.img.onclick = function onclick(event){void(0);}
}
	
function enableIcon(id){
	this.img = document.getElementById('img_' + id);
	this.img.src = 'images/sticky_pin_icon.gif';
	this.img.open = 'open';
}

function disableIcon(id){
	this.img = document.getElementById('img_' + id);
	this.img.src = 'images/sticky_pin_grey.gif';
	this.img.open = 'close';
}

function enableDelete(id){
	var noteId = getNoteId(id);
	this.del = document.getElementById('del_' + id);
	
	this.del.onclick = function onclick(event){
					 		if(deleteNote(noteId)){
								closeNote(true,this.parentNode.parentNode);
								newNote = false;
							}
						}
}

function disableDelete(id){
	this.del = document.getElementById('del_' + id);
	this.del.onclick = function onclick(event){
							if(confirm('Delete Note?')){
								closeNote(true, this.parentNode.parentNode);
								newNote = false;
							}
					   }
}

function defaultCloseNote(val){
	closeNote(true, val);
	newNote = false;
}

function disableNote(id, noteId){
	disableSave(id);
	disableIcon(id);
	
	setNoteId(id, noteId);
	enableDelete(id);
}

function checkUnsavedNotes(){
	var images = document.getElementsByTagName("img");
	var open_id = new Array();
	var ctr = 0;
	
	for(var i=0; i<images.length; i++)
		if(images[i].getAttribute('open') != null && images[i].open == 'open')
			open_id[ctr++] = images[i].getAttribute('open_id');
		
	if(open_id.length > 0){
		if(confirm('Save notes before leaving?')){
			for(var j=0; j<open_id.length; j++)
				addToNotes(getNoteId(open_id[j]), getNoteContent(open_id[j]), noteXPostion(open_id[j]), noteYPostion(open_id[j]));
			
			saveAllNotes();
		}
	}
		
}

function closeNote(answer, node){
	if(answer){
		allNotes.removeChild(node)
		document.onmouseover='';
	}	
}

function movemouse(e)
{
	
  if (isdrag)
  {
  
    newLeft = nn6 ? tx + e.clientX - x : tx + event.clientX - x;
    newTop = nn6 ? ty + e.clientY - y : ty + event.clientY - y;
   	
    if (newLeft>zone.left && newLeft<zone.right && newTop>zone.top && newTop<zone.bottom)
    {
      dobj.style.left = newLeft+"px";
      dobj.style.top  = newTop+"px";
      return false;
    }
  }
}

function selectmouse(e)
{
	try { 
	  var fobj       = nn6 ? e.target : event.srcElement;
	  var topelement = nn6 ? "HTML" : "BODY";
	  while (fobj.tagName != topelement && fobj.className != "dragger" && (nn6 ? fobj.parentNode.className : fobj.parentElement.className != "draggable"))
	  {
	    fobj = nn6 ? fobj.parentNode : fobj.parentElement;
	  }
	  if (fobj.className=="dragger")
	  {
	    isdrag = true;
	    dobj = nn6 ? fobj.parentNode : fobj.parentElement;
	    tx = parseInt(dobj.style.left+0,10);
	    ty = parseInt(dobj.style.top+0,10);
	    x = nn6 ? e.clientX : event.clientX;
	    y = nn6 ? e.clientY : event.clientY;
	    document.onmousemove=movemouse;
	    return false;
	    
	  }
	} catch (err) {}
  
}

function imposeMaxLength(Object, MaxLen)
{
  var max = !(Object.value.length <= MaxLen);
  if(max){
  	return Object.value = Object.value.substring(0, MaxLen);
  }
}


function rePosition(){

	var ctr = document.getElementsByTagName('div');

	
		for(var i=0;i<ctr.length;i++){
			if(ctr[i].className=='draggable'){
				ctr[i].style.left = (document.documentElement.clientWidth/2-250) + 'px';
				ctr[i].style.top = (document.documentElement.clientHeight/2+50) + 'px';
			}
		}
	
}

var clip = null;


//Zeroclipboard.js 
//Copy to clipboard for Flash 10



function initZero() {
ZeroClipboard.setMoviePath("swf/ZeroClipboard.swf");
clip = new ZeroClipboard.Client();
clip.setHandCursor( true );
clip.addEventListener('mouseOver', my_mouse_over);
clip.addEventListener('onmouseup',my_mouse_up);
clip.glue( 'clipboard' );
document.onmouseover=clipReposition;
}

function my_mouse_over(client) {
	
	if (navigator.userAgent.match(/MSIE/)) {
		clip.setText( document.getElementById('citebody').innerText + document.getElementById('citeurl').innerText);
	}else{
		clip.setText( document.getElementById('citebody').textContent + document.getElementById('citeurl').textContent);		
	}	
}

function my_mouse_up(){
		Tip('Citation copied', STICKY, true, DURATION, 3000, BORDERCOLOR, '#A6CF4D', BGCOLOR, '#DBECB7');
	if (navigator.userAgent.match(/MSIE/)){	
		top.document.title = "Stahl's Essential Psychopharmacology - Cambridge University Press";
	}
}

function clipReposition() {
clip.reposition();
}

document.onmousedown=selectmouse;
document.onmouseup=new Function("isdrag=false");

window.onresize=rePosition;
