// Scrapbook javascript file: scrapbook.js v1.0, Wed Dec 08 2006

// uses the prototype and script.aculo.us
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/


/************
    the document Fragment
*/
var docFragment = document.createDocumentFragment();
/************
    End the document Fragment
*/


/************
    the state
*/
var stageState = {
        isReorder: false,
        addItem: true,
        currentSbook: 0
        };

/************
    End the state
*/



/************
    all the ajax variables are defined here
*/
var inlineSbookTitleOpt = {
        formClassName: "titleForm",
        okText:			"Save",
        callback:    function(form,value) {
                        var id=form.id;
                        id = id.substring(0,id.indexOf('-inplaceeditor'));
                        var t = id.substring((id.indexOf('_')+1));
                        return 'a=eST&nid='+t+'&value='+value;
                    },
        onComplete: function(t,e) {
                        if(t != null) {          
	                        var id = e.id.substring(e.id.indexOf("_")+1);
	                        updateElements(id,t.responseText);
	                    }
                    }
};
var inlineSbookHeadingOpt = {
        formClassName: "headingForm",
        okText:			"Save",
        callback:    function(form,value) {
                        var id=form.id;
                        id = id.substring(0,id.indexOf('-inplaceeditor'));
                        var t = id.substring((id.indexOf('_')+1));
                        return 'a=eST&nid='+t+'&value='+value;
                    },
        onComplete: function(t,e) {
                        if(t != null) {
							var id = e.id.substring(e.id.indexOf("_")+1);
	                        updateElements(id,t.responseText);						  
						}

                    }
};

var inlineClipTitleOpt = {
        formClassName: "titleForm",
        okText:			"Save",
        size: "60",
        callback:    function(form,value) {
                        var id=form.id;
                        id = id.substring(0,id.indexOf('-inplaceeditor'));
                        var t = id.substring((id.indexOf('_')+1));
                        return 'a=eCT&nid='+stageState.currentSbook+'&id='+t+'&value='+value;
                    }
};

/************
    end all the ajax variables are defined here
*/



/************
    first function called
*/
function preparePage() {

	if(pageType == 'organizePage') {
        for(var i=0; i<$("scrapList").childNodes.length; i++) {
            if($("scrapList").childNodes[i].tagName == "LI"){
                var id = $("scrapList").childNodes[i].id.substring(($("scrapList").childNodes[i].id.indexOf('_')+1));
                new Ajax.InPlaceEditor('sbookTitle_'+id, modulePath,inlineSbookTitleOpt);
            }
        }
        highlightActions("scrapList");
    } else {
        stageState.currentSbook = currentSbook;
        createSbookArray();
        new Ajax.InPlaceEditor('sbookHeading_'+currentSbook, modulePath,inlineSbookHeadingOpt);
        var clipCount;
        clipCount = 0;
		for(var i=0; i<$("clipList").childNodes.length; i++) {
            if($("clipList").childNodes[i].tagName == "LI"){
                var id = $("clipList").childNodes[i].id.substring(($("clipList").childNodes[i].id.indexOf('_')+1));
                var tmp = new Ajax.InPlaceEditor('clipTitle_'+id, modulePath,inlineClipTitleOpt);
				clipCount++;
            }
        }
        if(clipCount == 1) {
			if($("clipTitle_"+id).firstChild.nodeValue == "Click here to change the title" && $("clipData_"+id).firstChild.nodeValue == "Paste the content of your clipping here") {
				tmp.enterEditMode('click');
				editHtmlItem('clipData_'+id,'clipContentForm_'+id,'clipContentEdit_'+id);
			}
		}
        highlightActions("clipList");
    }

}
/************
    End first function called
*/


/************
    functions for Add New Item
*/
function createForm(formType) {
    if(stageState.addItem) {
        stageState.addItem = false;
        var newForm = getForm(formType);
        $("addNew").appendChild(newForm);
        if(formType == "newHtmlClip") {
			tinyMCE.execCommand('mceAddControl', false, "clipContent");
        }
        Effect.BlindDown("tempId",{duration:1.5,scaleContent:false });
        $("tempId").removeAttribute("id");

    } else {
      showMessage("Add New option is already open!",true);
    }
}


function getForm(formType) {
  var tmpIdStr = "";
  if(tmpId != 0) {
    tmpIdStr = ",'"+tmpId+"'";
  }
  switch(formType) {
    case "newSbook":
        var newForm = Builder.node("form",{id:"tempId",className:"addSbookForm",method:"post",action:modulePath,onsubmit:"getNewItem(this,'newSbook','scrapList'); return false;",style:"display:none"},[
                        Builder.node("input",{type:"text",name:"sbookTitle",size:"40",value:"My New Scrapbook"}),
                        Builder.node("br"),
                        Builder.node("br"),
						Builder.node("div",{id:"savingDiv",style:"display:none; width:100%"},[
							Builder.node("span","Saving... "),
							Builder.node("img",{src:imagePath+"/ajaxloader.gif"})
							]),                        
						Builder.node("div",{id:"saveControl"},[
	                        Builder.node("input",{type:"submit",value:"Save"}),
	                        "  ",
	                        Builder.node("a",{href:"javascript:;",onclick:"removeForm(this.parentNode.parentNode)"},"Cancel")                        	
							])
                        ]);
        break;
    case "newHtmlClip":
        var newForm = Builder.node("form",{id:"tempId",className:"addClipForm",method:"post",action:modulePath,onsubmit:"getNewItem(this,'newHtmlClip','clipList'"+tmpIdStr+"); return false;",style:"display:none"},[
                        Builder.node("strong","Title"),
                        "  ",
                        Builder.node("input",{type:"text",name:"clipTitle",size:"40",value:"Click here to change the title"}),
                        Builder.node("br"),
                        Builder.node("br"),
                        Builder.node("textarea",{name:"clipContent",id:"clipContent",rows:"10",cols:"55"},"Paste the content of your clipping here"),
                        Builder.node("br"),
                        Builder.node("br"),
                        Builder.node("div",{id:"savingDiv",style:"display:none; width:100%"},[
							Builder.node("span","Saving... "),
							Builder.node("img",{src:imagePath+"/ajaxloader.gif"})
							]),                        
						Builder.node("div",{id:"saveControl"},[
	                        Builder.node("input",{type:"submit",value:"Save",className:"buttonStyle"}),
	                        "  ",
	                        Builder.node("a",{href:"javascript:;",onclick:"removeForm(this.parentNode.parentNode,'newHtmlClip')"},"Cancel")                        	
							])
                        ]);
        break;
  }
  return newForm;
}


function removeForm(theForm,formType,newAdded) {
  stageState.addItem = true;
  new Effect.Highlight(theForm, {
	  									startcolor:'#FFFFDD', 
										endcolor:'#FFFFFF',
										duration:".5",
										afterFinish: function(){
								  				new Effect.BlindUp(theForm, {
												    duration:'.5',
													afterFinish:function(){
															if(formType == "newHtmlClip") {
																tinyMCE.execCommand('mceFocus', false, "clipContent");
															    tinyMCE.execCommand('mceRemoveControl', false, "clipContent");
																if(newAdded) {
																  showMessage(createClipMsg,true);
																}												    
															} else {
															  	if(newAdded) {
															      showMessage(createSbookMsg,true);
															    }
															}
															theParent = theForm.parentNode;
															theParent.removeChild(theForm);
															}
												})
										}
						});
}

function getNewItem(theForm,formType,myid) {
    $("saveControl").style.display = "none";
  	$("savingDiv").style.display = "block";  
	var thepostBody = "";
    switch(formType) {
        case "newSbook":
            thepostBody = "a=aSB&value=" + theForm.sbookTitle.value;
            break;
        case "newHtmlClip":
			tinyMCE.execCommand('mceFocus', false, "clipContent");
            var content = tinyMCE.getContent("clipContent");
            if(tmpId == 0) {
				thepostBody = "a=aC&nid="+stageState.currentSbook+"&ty=html&title="+theForm.clipTitle.value+"&value=" + escape(content);
			} else {
				clipNum++;
				thepostBody = "a=aLC&tmp="+tmpId+"&id="+clipNum+"&ty=html&title="+theForm.clipTitle.value+"&value=" + escape(content);
			}
            break;
    }
    var newItemOpt = {
            method: 'post',
            postBody: thepostBody,
            onSuccess: function(t) {
                var temp = eval("("+ t.responseText +")");
                $("savingDiv").style.display = "none";
                addNewItem(temp,formType,myid);
				removeForm(theForm,formType,true);
            },
            on404: function(t) {
                removeForm(theForm);
                alert('Error 404: location "' + t.statusText + '" was not found.');
                alert('Error ' + t.status + ' -- ' + t.statusText);

            },
            onFailure: function(t) {
               removeForm(theForm);
                alert('Error ' + t.status + ' -- ' + t.statusText);
            }
        }

        new Ajax.Request(modulePath, newItemOpt);

  return false;
}

function addNewItem(itemObject,formType,myid) {
    switch(formType) {
      case "newSbook":
        var firstElement = getFirstElement(myid);
        elementNew = formatItem(formType,itemObject.scrapTab);
        $(myid).insertBefore(elementNew,firstElement);
        highlightActions("scrapList");        
        addNewTabElement(itemObject.scrapTab);
        break;
      case "newHtmlClip":
        var firstElement = getFirstElement(myid);       
        elementNew = formatItem(formType,itemObject.clipping);
        $(myid).insertBefore(elementNew,firstElement);
        highlightActions("clipList"); 
		//showMessage(createClipMsg,true);		
        break;
    }
}



// for html
function editHtmlItem(fromElement,toElement,htmlContainer) {
    $(fromElement).style.display = "none";
    tinyMCE.execCommand('mceAddControl', false, htmlContainer);
    tinyMCE.execCommand('mceFocus', false, htmlContainer);
    $(toElement).style.display = "";
}

function cancelHtmlSave(resetElement,hideElement,showElement) {
    $(hideElement).style.display = "none";
    tinyMCE.execCommand('mceFocus', false, resetElement);
    tinyMCE.execCommand('mceRemoveControl', false, resetElement);
    $(showElement).style.display = "";
    removeHighlightClip($(showElement));
    $(resetElement).value = $(showElement).innerHTML;
}

function saveHtmlItem(theForm,contentId,pushToId) {
    var i = contentId.substring(contentId.lastIndexOf("_")+1,contentId.length);
    $("saveControl_"+i).style.display = "none";
  	$("savingDiv_"+i).style.display = "block";  
    tinyMCE.execCommand('mceFocus', false, "clipContent");
	var content = tinyMCE.getContent(contentId);
	if(tmpId != 0) {
		var thePostBody = "a=eLCD&ty=html&tmp="+tmpId+"&id="+i+"&value="+escape(content); // eLCD editLoginClipData
	} else {
	  	var thePostBody = "a=eCD&nid="+stageState.currentSbook+"&ty=html&id="+i+"&value="+escape(content); // eCD editClipData
	}
    var opt = {
        method: "post",
        postBody: thePostBody,
        onSuccess: function(t) {
            $("savingDiv_"+i).style.display = "none";  
			//var temp = t.responseText;

            //if(temp.indexOf("clipEditSuccess") >= 0) {
                theForm.style.display = "none";

                $(pushToId).innerHTML = t.responseText;
                $(contentId).firstChild.nodeValue = t.responseText;

                $(pushToId).style.display = "";
                //removeHighlightClip($(pushToId));
				$("saveControl_"+i).style.display = "block";
            //} else {
              //alert("Operation Failed!");
            //}
			tinyMCE.execCommand("mceFocus", true, contentId);
            tinyMCE.execCommand("mceRemoveControl", false, contentId);
        },
        on404: function(t) {
            alert("Error 404: location " + t.statusText + " was not found.");
            alert("Error " + t.status + " -- " + t.statusText);
            tinyMCE.execCommand("mceFocus", false, $(contentId));
            tinyMCE.execCommand("mceRemoveControl", false, contentId);

        },
        onFailure: function(t) {
            alert("Error " + t.status + " -- " + t.statusText);
            tinyMCE.execCommand("mceFocus", false, contentId);
            tinyMCE.execCommand("mceRemoveControl", false, contentId);
        }
    }

    new Ajax.Request(modulePath, opt);

    return false;
}

function formatItem(type,itemObject) {
  var tmpIdStr = "";
  if(tmpId != 0) {
    tmpIdStr = ",'"+tmpId+"'";
  }
  switch(type) {
    case "newSbook":
        var sbookId = itemObject.tabId;
        var sbookTitle = itemObject.tabTitle;
        var sbookLi = Builder.node("li",{id:"sbook_"+sbookId,className:"sbookListStyle"},[
                            Builder.node("div",{id:"sbookTitle_"+sbookId,className:"sbookStyle"},sbookTitle),
                            Builder.node("ul",{className:"sbookCtrl"},[
                                Builder.node("li",[
									Builder.node("a",{href:"node/"+sbookId+"/"+cleanTitle(sbookTitle),title:"Open",onmouseover:"showTooltip(this,event)",onmousemove:"moveTooltip(this,event)",onmouseout:"removeTooltip(this)"},"Open")								
								]),
								Builder.node("li","|"),
								Builder.node("li",[
	                                Builder.node("a",{href:"node/"+sbookId+"/print",title:"Print",target:"_blank",onmouseover:"showTooltip(this,event)",onmousemove:"moveTooltip(this,event)",onmouseout:"removeTooltip(this)"},"Print")								
								]),
								Builder.node("li","|"),
								Builder.node("li",[
	                                Builder.node("a",{href:"node/"+sbookId+"/export",title:"Export",onmouseover:"showTooltip(this,event)",onmousemove:"moveTooltip(this,event)",onmouseout:"removeTooltip(this)"},"Export")
								]),
								Builder.node("li","|"),
								Builder.node("li",[
									Builder.node("a",{href:"javascript:;",id:"delete_"+sbookId,title:"Delete",onclick:"showDialog(this,'deleteSbook',event)",onmouseover:"showTooltip(this,event)",onmousemove:"moveTooltip(this,event)",onmouseout:"removeTooltip(this)"},"Delete")
								])
							])		
                        ]);
        new Ajax.InPlaceEditor(sbookLi.firstChild, modulePath,inlineSbookTitleOpt);
        return sbookLi;
        break;
    case "newHtmlClip":
        var clipId = itemObject.clipId;
        var clipType = itemObject.clipType;
        var clipTitle = itemObject.clipTitle;
        var clipData = itemObject.clipData;
        var clipLi = Builder.node("li",{id:"clip_"+clipId,className:"clipListStyle clearfix"},[
        					Builder.node("img",{src:imagePath+"/open.gif",onclick:"toggleVisible(this,'clipDataWrapper_"+clipId+"')"}),
        					Builder.node("br"),
                            Builder.node("div",{id:"clipTitle_"+clipId,className:"clipTitleStyle"},clipTitle),
                            Builder.node("ul",{className:"clipCtrl"},[
	                            	Builder.node("li",[
										Builder.node("img",{src:imagePath+"/clippingmove.gif",title:"Move",id:"move_"+clipId,onclick:"prepareMove(this,'moveForm_"+clipId+"')"}),
		                                Builder.node("form",{id:"moveForm_"+clipId,style:"display:none",onsubmit:"moveItem('moveForm_"+clipId+"','select_"+clipId+"'); return false;"},[
											Builder.node("select",{id:"select_"+clipId,name:"select_"+clipId}),
											" ",
											Builder.node("input",{type:"submit",className:"buttonStyle",value:"Move"}),
											" ",
											Builder.node("a",{href:"javascript:;",onclick:"cancelMove('move_"+clipId+"','moveForm_"+clipId+"')"},"Cancel")
										])
									]),
									Builder.node("li",[
										Builder.node("img",{src:imagePath+"/clippingdelete.gif",title:"Delete",id:"delete_"+clipId,onclick:"showDialog(this,'deleteClip',event)",onmouseover:"showTooltip(this,event)",onmousemove:"moveTooltip(this,event)",onmouseout:"removeTooltip(this)"})
									])                               
                                ]),
                            Builder.node("div",{id:"clipDataWrapper_"+clipId,className:"clipDataWrapper"},[
								Builder.node("div",{id:"clipData_"+clipId,className:"clipDataStyle",onclick:"javascript: editHtmlItem('clipData_"+clipId+"','clipContentForm_"+clipId+"','clipContentEdit_"+clipId+"')",onmouseover:"highlightClip(this)",onmouseout:"removeHighlightClip(this)"}),
	                            Builder.node("form",{id:"clipContentForm_"+clipId,style:"display:none",onsubmit:"javascript: saveHtmlItem(this,'clipContentEdit_"+clipId+"','clipData_"+clipId+"'"+tmpIdStr+"); return false;"},[
	                                Builder.node("textarea",{id:"clipContentEdit_"+clipId,rows:"10",cols:"55"},clipData),
	                                Builder.node("br"),
	                                Builder.node("br"),
	                                Builder.node("div",{id:"savingDiv_"+clipId,style:"display:none; width:80%"},[
										Builder.node("span","Saving... "),
										Builder.node("img",{src:imagePath+"/ajaxloader.gif"})
										]),                        
									Builder.node("div",{id:"saveControl_"+clipId},[
				                        Builder.node("input",{type:"submit",value:"Save",className:"buttonStyle"}),
				                        "  ",
				                        Builder.node("a",{href:"javascript:;",onclick:"cancelHtmlSave('clipContentEdit_"+clipId+"','clipContentForm_"+clipId+"','clipData_"+clipId+"')"},"Cancel")                        	
										])
	                            ])
							])
                        ]);
        clipLi.childNodes[4].firstChild.innerHTML = clipData;
        if(tmpId == 0) {
		    new Ajax.InPlaceEditor(clipLi.childNodes[2], modulePath,inlineClipTitleOpt);
		} else {
			new Ajax.InPlaceEditor(clipLi.childNodes[2], modulePath,loginClipTitleOpt);			
			while (clipLi.childNodes[3].childNodes.length >= 1) {
				clipLi.childNodes[3].removeChild(clipLi.childNodes[3].firstChild);
			}			
			var tmpElement = Builder.node("img",{src:imagePath+"/clippingmove.gif",title:"Move",id:"move_"+clipId,onclick:"showDialog(this,'loginMsg',event)",onmouseover:"showTooltip(this,event)",onmousemove:"moveTooltip(this,event)",onmouseout:"removeTooltip(this)"});
			clipLi.childNodes[3].appendChild(tmpElement);
			tmpElement = document.createTextNode("  ");
			clipLi.childNodes[3].appendChild(tmpElement);
			tmpElement = Builder.node("img",{src:imagePath+"/clippingdelete.gif",title:"Delete",id:"delete_"+clipId,onclick:"showDialog(this,'loginMsg',event)",onmouseover:"showTooltip(this,event)",onmousemove:"moveTooltip(this,event)",onmouseout:"removeTooltip(this)"});
			clipLi.childNodes[3].appendChild(tmpElement);		  	
		}
        return clipLi;
        break;
  }

}

/************
    End functions for Add New Item
*/


/************
    functions for sorting Elements
*/

function makeSortable(myid,mytag){
    Sortable.create(myid,{ tag: mytag || "li", handle:"handle", ghosting: true});
    $(myid+"_sort").style.display = "none";
    $(myid+"_savesort1").style.display = "";
    $(myid+"_savesort2").style.display = "";
    stageState.isReorder = true;
    manageStyleMove(myid,"add");
    return false;
}

function saveSortable(myid){
    switch(myid) {
		case "scrapList":
			var thePostBody = "a=rS&"+Sortable.serialize(myid);
			break;
		case "clipList":
			var thePostBody = "a=rC&nid="+stageState.currentSbook+"&"+Sortable.serialize(myid);
			break;
	}


	var sortOpt = {
        method: "post",
        postBody: thePostBody,
        onSuccess: function(t) {
            $(myid+"_saving1").style.display = "none";
            $(myid+"_saving2").style.display = "none";
            $(myid+"_sort").style.display = "";
            manageStyleMove(myid,"remove");
            if(myid == "scrapList") {
              reorderTabs(t.responseText);
              showMessage(reorderSbookMsg,true);
            } else {
              showMessage(reorderClipMsg,true);
            }
        },
        on404: function(t) {
            manageStyleMove(myid,"remove");
            alert('Error 404: location "' + t.statusText + '" was not found.');
            alert('Error ' + t.status + ' -- ' + t.statusText);
            $(myid+"_saving1").style.display = "none";
            $(myid+"_saving2").style.display = "none";
            $(myid+"_sort").style.display = "";
        },
        onFailure: function(t) {
            manageStyleMove(myid,"remove");
            alert('Error ' + t.status + ' -- ' + t.statusText);
            $(myid+"_saving1").style.display = "none";
            $(myid+"_saving2").style.display = "none";
            $(myid+"_sort").style.display = "";
        }
    }

    new Ajax.Request(modulePath, sortOpt);


    Sortable.destroy(myid);
    $(myid+'_savesort1').style.display = 'none';
    $(myid+'_savesort2').style.display = 'none';
    $(myid+'_saving1').style.display = '';
    $(myid+'_saving2').style.display = '';
    stageState.isReorder = false;
    return false;
}

function manageStyleMove(myid,action) {
	if(action == "add") {
		var myLists = $(myid).getElementsByTagName("LI");
        for(i = 0; i < myLists.length; i++){
			if(myLists[i].parentNode.id == "clipList") {
				myLists[i].addClassName("moveItem");
	            var liID = myLists[i].id.substring(myLists[i].id.lastIndexOf('_')+1);
	            // title
				var tempDiv = Builder.node("div",{id:"temp_"+liID,className:"clipTitleStyle"},$("clipTitle_"+liID).firstChild.nodeValue);
				myLists[i].insertBefore(tempDiv,$("clipTitle_"+liID));
				$("clipTitle_"+liID).style.display = "none";
				if($("clipTitle_"+liID+"-inplaceeditor") != undefined) {
				  $("clipTitle_"+liID+"-inplaceeditor").style.display = "none";
				}
				// delete
				var tempDel = Builder.node("img",{id:"deleteTmp_"+liID,src:imagePath+"/clippingdelete-disabled.gif"});
				$("delete_"+liID).parentNode.insertBefore(tempDel,$("delete_"+liID));
				$("delete_"+liID).style.display = "none";
				// move
				var tempMove = Builder.node("img",{id:"moveTmp_"+liID,src:imagePath+"/clippingmove-disabled.gif"});
				$("move_"+liID).parentNode.insertBefore(tempMove,$("move_"+liID));	
				$("move_"+liID).style.display = "none";	
				if($("moveForm_"+liID) != undefined) {
				  $("moveForm_"+liID).style.display = "none";	
				}
				// toggle
	            var childCountLi = myLists[i].childNodes.length;
				for(j=0; j<childCountLi; j++) {
					if(myLists[i].childNodes[j].tagName == 'IMG'){
					  	toggleVisible(myLists[i].childNodes[j],'clipDataWrapper_'+liID,true);
						break;	
					}
				}
			}
				
        }
    } else if(action == "remove") {
        var myLists = $(myid).getElementsByTagName("li");
        for(i = 0; i < myLists.length; i++){
          	if(myLists[i].parentNode.id == "clipList") {
	            myLists[i].removeClassName("moveItem");
	            var liID = myLists[i].id.substring(myLists[i].id.lastIndexOf('_')+1);
	            // title
				myLists[i].removeChild($("temp_"+liID));
				if($("clipTitle_"+liID+"-inplaceeditor") != undefined) {
				  $("clipTitle_"+liID+"-inplaceeditor").style.display = "block";
				} else {
					$("clipTitle_"+liID).style.display = "block";   			  
				}			
	
				// delete         
	            $("deleteTmp_"+liID).parentNode.removeChild($("deleteTmp_"+liID));
	            $("delete_"+liID).style.display = "";
				// move         
	            $("moveTmp_"+liID).parentNode.removeChild($("moveTmp_"+liID));
	            $("move_"+liID).style.display = "";
				// toggle
				var childCountLi = myLists[i].childNodes.length;
				for(j=0; j<childCountLi; j++) {
					if(myLists[i].childNodes[j].tagName == 'IMG'){
					  	toggleVisible(myLists[i].childNodes[j],'clipDataWrapper_'+liID);
						break;	
					}
				}
			}
        }
    }
}
/************
    End functions for sorting Elements
*/


/************
    Add New Tab Item Functions
*/
function addNewTabElement(itemObject) {
    var tabId = itemObject.tabId;
    var tabTitle = itemObject.tabTitle;
    var tabLi = Builder.node("li",{id:"tab_"+tabId,title:tabTitle},[
                                Builder.node("div",{id:"title_"+tabId},[
														Builder.node("a",{href:"node/"+tabId+"/"+cleanTitle(tabTitle),title:tabTitle},tabTitle)
											])
                            ]);
    var tabEditDiv = Builder.node("div",{id:"edit_"+tabId,style:"display:none; font-weight:bold"},tabTitle);
    //new Ajax.InPlaceEditor(tabEditDiv, modulePath,editTabsOptions);
    tabLi.appendChild(tabEditDiv);
    $("tabMenu").insertBefore(tabLi,$("tab_add").nextSibling);
    createSbookArray();
}

/************
    End functions for Add New Tab Item
*/


/************
    functions for Move Clip
*/
function cancelMove(showThis,hideThis) {
  $(showThis).style.display = "";
  $(hideThis).style.display = "none";
}

function prepareMove(hideElement,theFormId) {
  if(tmpId == 0) {
		// create the options
		var id = theFormId.substring(theFormId.indexOf("_")+1);
		emptyElement("select_"+id);
		for(var i=0; i<sbookArray.length; i++) {
			if(stageState.currentSbook != sbookArray[i][0]) {
			  var tmpOpt = Builder.node("option",{value:sbookArray[i][0]},sbookArray[i][1]);
			  $("select_"+id).appendChild(tmpOpt);
			}
		}
		
		$(theFormId).style.display = "inline";
		hideElement.style.display = "none";		  
	}
}

function moveItem(theFormId,selectionName) {

  var id = selectionName.substring(selectionName.indexOf("_")+1);
  var thePostBody = "a=mC&nid="+$(selectionName).value+"&id="+id;

  var moveOpt = {
            method: "post",
            postBody: thePostBody,
            onSuccess: function(t) {
              window.location = t.responseText;
/*
                $("clipList").removeChild($("clip_"+id));
                showMessage(moveClipMsg,true);
                highlightActions("clipList");
*/
            },
            on404: function(t) {
                cancelMove("move_"+id,theFormId)
                alert('Error 404: location "' + t.statusText + '" was not found.');
                alert('Error ' + t.status + ' -- ' + t.statusText);

            },
            onFailure: function(t) {
               cancelMove("move_"+id,theFormId)
                alert('Error ' + t.status + ' -- ' + t.statusText);
            }
	};
  new Ajax.Request(modulePath, moveOpt);
  return false;
}

/************
    End functions for Move Clip
*/


/************
    Delete Functions
*/
function deleteThis(delType,theElement) {
  if(tmpId == 0) {

        var i = theElement.substring(theElement.lastIndexOf("_")+1,theElement.length);

        switch(delType) {
            case "sbook":
                var thePostBody = 'a=dS&nid='+i;
                break;
            case "clipping":
                var thePostBody = 'a=dC&nid='+stageState.currentSbook+'&id='+i;
                break;
        }

        var delOpt = {
            method: "post",
            postBody: thePostBody,
            onSuccess: function(t) {
                var temp = t.responseText;
                if(temp.indexOf('deleteSuccess') >= 0) {
                    if(delType == "sbook") {
						new Effect.Highlight(theElement, {
	  									startcolor:'#FFFFDD', 
										endcolor:'#FFFFFF',
										duration:".5",
										afterFinish: function(){
								  				new Effect.BlindUp(theElement, {
												    duration:"1",
													afterFinish:function(){
													  		$("scrapList").removeChild($(theElement));
															$("tabMenu").removeChild($("tab_"+i));
															showMessage(deleteSbookMsg,true);
															createSbookArray();
															highlightActions("scrapList");
															}
												})
										}
						});
                    } else {
                      	new Effect.Highlight(theElement, {
	  									startcolor:'#FFFFDD', 
										endcolor:'#FFFFFF',
										duration:".5",
										afterFinish: function(){
								  				new Effect.BlindUp(theElement, {
												    duration:'.5',
													afterFinish:function(){
									    					$("clipList").removeChild($(theElement));
									                        showMessage(deleteClipMsg,true);
									                        highlightActions("clipList");
															}
												})
										}
						});
                    }

                } else {
                  alert('Operation Failed!');
                }
            },
            on404: function(t) {
                alert('Error 404: location "' + t.statusText + '" was not found.');
                alert('Error ' + t.status + ' -- ' + t.statusText);

            },
            onFailure: function(t) {
                alert('Error ' + t.status + ' -- ' + t.statusText);
            }
        }

        new Ajax.Request(modulePath, delOpt);
    	
  } else {
  	loginAlert(loginMsg)  ;
  }
    return false;
}

/************
    End Delete Functions
*/


/************
    functions for Message
*/
function showMessage(message,autoHide) {
  emptyElement("messageArea");
  $("messageArea").innerHTML = "<h4 class='info'>"+message+"</h4>";
    //$("messageArea").style.display = "block";
    Effect.BlindDown("messageArea", {duration:1});
    if(autoHide) {
        setTimeout(removeMessage,messageDuration);
    }
}

function removeMessage() {
    Effect.Fade("messageArea", {duration:.3});
}

/************
    End functions for Message
*/


/************
    functions for Tooltip
*/
function showTooltip(theElement,e) {
	if($("tooltip") != undefined) {
		$("tooltip").parentNode.removeChild($("tooltip"));
	}
	if(theElement.title != undefined) {
			//var leftPos = getPosition(theElement,'x',e.clientX);
			//var topPos = getPosition(theElement,'y',e.clientY);
			var tooltip = Builder.node("span",{id:"tooltip", className:"tooltip", style:"display:none"},theElement.title);
			theElement.title = "";		
			$("stage").appendChild(tooltip);
			var leftPos = getPosition(theElement,'x',e.clientX,"tooltip");
			var topPos = getPosition(theElement,'y',e.clientY,"tooltip");
	
			$("tooltip").style.zIndex = 101;
			$("tooltip").style.position = "absolute";
			if(leftPos == 'left') {
				$("tooltip").style.left = (e.clientX+10)+"px";
			} else {
				var rightPos = getWindowWidth()-(e.clientX+10);
				$("tooltip").style.right = rightPos+"px";
			}
			$("tooltip").style.top = topPos+"px";
			setTimeout('if($("tooltip") != undefined){$("tooltip").style.display = ""}',500);
		} else {
			return false;
		}  
}

function moveTooltip(theElement,e) {
	if($("tooltip") != undefined) {
		var leftPos = getPosition(theElement,'x',e.clientX,"tooltip");
		var topPos = getPosition(theElement,'y',e.clientY,"tooltip");
		if(leftPos == 'left') {
			$("tooltip").style.left = (e.clientX+10)+"px";
		} else {
			var rightPos = getWindowWidth()-(e.clientX+10);
			$("tooltip").style.right = rightPos+"px";
		}
		$("tooltip").style.top = topPos + "px";
	}
}


function removeTooltip(theElement) {
	var titleText = $("tooltip").firstChild.nodeValue;
	theElement.setAttribute("title",titleText);
	$("tooltip").parentNode.removeChild($("tooltip"));
}

/************
    End functions for Tooltip
*/


/************
    functions for Dialog
*/
function showDialog(theElement,dialogType,e) {
	if($("dialogBox") != undefined) {
		$("dialogBox").parentNode.removeChild($("dialogBox"));
	}
	switch(dialogType) {
		case 'deleteSbook':
			createSbookArray();
			if(sbookArray.length < 2) {
				var dialogBox = Builder.node("div",{id:"dialogBox",className:"dialogBox",style:"display:none"},[
											Builder.node("div",{className:"dialogHeader"},[
																   Builder.node("a",{href:"javascript:;", onclick:"dialogClose()"},[
																   		Builder.node("img",{src:imagePath+"/dialog-close.gif",alt:"Close", className:"dialogClose"})
																		])
																   ]),
											Builder.node("div",{className:"dialogTxt"},deleteSbookAlert),
											Builder.node("input",{type:"button",id:"yesButton", onclick:"dialogClose()",className:"dialogAction",value:"Ok"})
											]);
				showDialogBox(dialogBox,"yesButton");	  
				
			} else {
				var sID = theElement.id.substring(theElement.id.lastIndexOf("_")+1);
				var dialogBox = Builder.node("div",{id:"dialogBox",className:"dialogBox",style:"display:none"},[
											Builder.node("div",{className:"dialogHeader"},[
																   Builder.node("a",{href:"javascript:;", onclick:"dialogClose()"},[
																   		Builder.node("img",{src:imagePath+"/dialog-close.gif",alt:"Close", className:"dialogClose"})
																		])
																   ]),
											Builder.node("div",{className:"dialogTxt"},deleteSbookConfirm),
											Builder.node("input",{type:"button",id:"yesButton", onclick:"deleteThis('sbook','sbook_"+sID+"'); dialogClose()",className:"dialogAction",value:"Yes"}),
											Builder.node("input",{type:"button",id:"noButton", onclick:"dialogClose()",className:"dialogAction",value:"No"})
											]);
				
				showDialogBox(dialogBox,"yesButton");
		  
			}

			break;
		case 'deleteClip':
			var clipCount;
	        clipCount = 0;
			for(var i=0; i<$("clipList").childNodes.length; i++) {
	            if($("clipList").childNodes[i].tagName == "LI"){
					clipCount++;
					if(clipCount == 2) {
					  break;
					}
	            }
	        }
	        if(clipCount < 2) {
					var dialogBox = Builder.node("div",{id:"dialogBox",className:"dialogBox",style:"display:none"},[
												Builder.node("div",{className:"dialogHeader"},[
																	   Builder.node("a",{href:"javascript:;", onclick:"dialogClose()"},[
																   		Builder.node("img",{src:imagePath+"/dialog-close.gif",alt:"Close", className:"dialogClose"})
																		])
																	   ]),
												Builder.node("div",{className:"dialogTxt"},deleteClipAlert),
												Builder.node("input",{type:"button",id:"yesButton", onclick:"dialogClose()",className:"dialogAction",value:"Ok"})
												]);

				showDialogBox(dialogBox,"yesButton");
						
			} else {
			  		var clipID = theElement.id.substring(theElement.id.lastIndexOf("_")+1);
					var dialogBox = Builder.node("div",{id:"dialogBox",className:"dialogBox",style:"display:none"},[
												Builder.node("div",{className:"dialogHeader"},[
																	   Builder.node("a",{href:"javascript:;", onclick:"dialogClose()"},[
																   		Builder.node("img",{src:imagePath+"/dialog-close.gif",alt:"Close", className:"dialogClose"})
																		])
																	   ]),
												Builder.node("div",{className:"dialogTxt"},deleteClipConfirm),
												Builder.node("input",{type:"button",id:"yesButton", onclick:"deleteThis('clipping','clip_"+clipID+"'); dialogClose()",className:"dialogAction",value:"Yes"}),
												Builder.node("input",{type:"button",id:"noButton", onclick:"dialogClose()",className:"dialogAction",value:"No"})
												]);

				showDialogBox(dialogBox,"yesButton");

			}			
			break;
		case 'moveAlertClip':
					var cID = theElement.id.substring(theElement.id.lastIndexOf("_")+1);
					var dialogBox = Builder.node("div",{id:"dialogBox",className:"dialogBox",style:"display:none"},[
												Builder.node("div",{className:"dialogHeader"},[
																	   Builder.node("a",{href:"javascript:;", onclick:"dialogClose()"},[
																   		Builder.node("img",{src:imagePath+"/dialog-close.gif",alt:"Close", className:"dialogClose"})
																		])
																	   ]),
												Builder.node("div",{className:"dialogTxt"},[
													"You have only one Scrapbook! ",
													Builder.node("br"),
													Builder.node("br"),
													"Would you like to create a new Scrapbook and move this clip?"
													]),
												Builder.node("input",{type:"button",id:"yesButton", onclick:"window.location = '"+addSbookPath+cID+"'; dialogClose()",className:"dialogAction",value:"Yes"}),
												Builder.node("input",{type:"button",id:"noButton", onclick:"dialogClose()",className:"dialogAction",value:"No"})
												]);

				showDialogBox(dialogBox,"yesButton");

			break;
		case 'loginMsg':
				var dialogBox = Builder.node("div",{id:"dialogBox",className:"dialogBox",style:"display:none"},[
												Builder.node("div",{className:"dialogHeader"},[
																	   Builder.node("a",{href:"javascript:;", onclick:"dialogClose()"},[
																   		Builder.node("img",{src:imagePath+"/dialog-close.gif",alt:"Close", className:"dialogClose"})
																		])
																	   ]),
												Builder.node("div",{className:"dialogTxt"},[
													"You have to ",
													Builder.node("a",{href:"#sbRegister",title:"Login",onclick:"dialogClose()"},"login"),
													" or ",
													Builder.node("a",{href:"#sbLogin",title:"Register",onclick:"dialogClose()"},"register"),
													" to perform this operation"
													]),
												Builder.node("input",{type:"button",id:"yesButton", onclick:"dialogClose()",className:"dialogAction",value:"Ok"})
												]);

				showDialogBox(dialogBox,"yesButton");

			break;
	}	
}


function showDialogBox(dialogBox,defaultButton) { 				
		var pageSizeArray = getPageSize();
		var overLay = Builder.node("div",{id:"dialogCover"});
		var theBody = document.getElementsByTagName("body")[0];
		theBody.insertBefore(overLay,theBody.firstChild);
		$("dialogCover").style.position = "absolute";
		$("dialogCover").style.left = "0px";
		$("dialogCover").style.top = "0px";
		$("dialogCover").style.height = pageSizeArray[1]+"px";
		$("dialogCover").style.width = "100%";
		$("dialogCover").style.zIndex = 100;
		$("dialogCover").style.display = "block";
		
		theBody.appendChild(dialogBox);
		$("dialogBox").style.display = "block";
		$("dialogBox").style.position = "absolute";
		$("dialogBox").style.left = ((pageSizeArray[2]-$("dialogBox").offsetWidth)/2)+"px";
		$("dialogBox").style.top = ((pageSizeArray[3]-$("dialogBox").offsetHeight)/2)+"px";
		$("dialogBox").style.zIndex = 101;
		
		if(defaultButton != undefined){
		  $(defaultButton).focus();
		}
		
}


function dialogClose() {
  	$("dialogBox").parentNode.removeChild($("dialogBox"));
	$("dialogCover").parentNode.removeChild($("dialogCover"));
}

/************
    End functions for Dialog
*/

/************
    functions and objects for Login Page
*/

function toggleForm(theElementId,theState) {
	if(theState == 1) { // show
		Effect.BlindDown(theElementId, {duration:0.5});
	} else { // hide
		Effect.BlindUp(theElementId, {duration:0.5});
	}
}


/************
    End functions and objects for Login Page
*/


/************
    Functions for share Scrapbook
*/

function sbookStatus(sId) {
       thePostBody = 'a=sP&nid='+sId;
	   var statusOpt = {
            method: "post",
            postBody: thePostBody,
            onSuccess: function(t) {
                var temp = t.responseText;
                if(temp.indexOf('.gif') >= 0) {
                    var theIcon = $('sbookStatus_'+sId);
                    var srcArr = theIcon.src.split('/');
                    srcArr[(srcArr.length) - 1] = temp;
                    theIcon.src = srcArr.join('/');
                    if(temp == 'private-scrapbook.gif') {
                        showMessage('The Scrapbook is now Private!',true);					  
					} else {
                        showMessage('The Scrapbook is now Shared!',true);					  
					}
                } else {
                  alert('Operation Failed!');
                }
            },
            on404: function(t) {
                alert('Error 404: location "' + t.statusText + '" was not found.');
                alert('Error ' + t.status + ' -- ' + t.statusText);

            },
            onFailure: function(t) {
                alert('Error ' + t.status + ' -- ' + t.statusText);
            }
        }

        new Ajax.Request(modulePath, statusOpt);  
}

/************
    End functions for share Scrapbook
*/

/************
    Misc Functions
*/
var sbookArray = new Array();

function createSbookArray() {
    sbookArray = new Array();
    var s = 0;
    for(var i=0; i<$("tabMenu").childNodes.length; i++) {
        var t = $("tabMenu").childNodes[i].id;
        var id = t.substr(t.indexOf("_")+1);
        if(!isNaN(id)) {
            sbookArray[s] = new Array(id,$("title_"+id).firstChild.nodeValue);
            s++;
        }
    }
}

function emptyElement(elementId) { // empty a node
    var TabPlane = document.getElementById(elementId);
    while (TabPlane.childNodes.length >= 1) {
    	TabPlane.removeChild(TabPlane.firstChild);
    }
}


function getFirstElement(myid) {
    var myLists = $(myid).getElementsByTagName("li");
    return myLists[0];
}

function updateElements(id,theText) {
    if($("title_"+id) != undefined) {
        $("title_"+id).firstChild.nodeValue = theText;
        $("title_"+id).title = theText;
        var tmpUrl = $("title_"+id).href.substring(0,$("title_"+id).href.lastIndexOf('/'));
        $("title_"+id).href = tmpUrl + '/' + cleanTitle(theText);        
    }
    if($("open_"+id) != undefined) {
        var tmpUrl = $("open_"+id).href.substring(0,$("open_"+id).href.lastIndexOf('/'));
        $("open_"+id).href = tmpUrl + '/' + cleanTitle(theText);
    }
}

function cleanTitle(theTitle) {
  return theTitle.replace(/([^0-9a-zA-Z])+/g,"-");
}


function toggleVisible(theImg,elementId,allClose) {
	var tmpArray = theImg.src.split("/");
	if(tmpArray[(tmpArray.length)-1] == "open.gif") {
		tmpArray[(tmpArray.length)-1] = "close.gif";
		theImg.src = tmpArray.join("/");
		$(elementId).style.display = "none";
	} else if((allClose == undefined || allClose == false) && stageState.isReorder == false) {
		tmpArray[(tmpArray.length)-1] = "open.gif";
		theImg.src = tmpArray.join("/");
		$(elementId).style.display = "";
	}	
}


function highlightActions(listType) {
    var countList;
    countList = 0;
	for(var i=0; i<$(listType).childNodes.length; i++) {
		if($(listType).childNodes[i].nodeName == 'LI') {
			countList++;
			if(countList >1){
			  break;
			}
		}
	}
	if(countList == 1){
		switch(listType) {
		  case 'scrapList':
		  	$("addSbookControl").setAttribute("class","highlightedAction");
		  	break;
		  case 'clipList':
		  	$("addClipControl").setAttribute("class","highlightedAction");							  
		  	break;					  	
		}
	} else {
		switch(listType) {
		  case 'scrapList':
		  	$("addSbookControl").setAttribute("class","");
		  	break;
		  case 'clipList':
		  	$("addClipControl").setAttribute("class","");							  
		  	break;					  	
		}	  
	}
}

function highlightClip(theElement) {
	theElement.style.backgroundColor ="#FFFF99";	  
}

function removeHighlightClip(theElement,event) {

	var related = event.toElement || event.relatedTarget;
	

	while (related != theElement && related.nodeName != 'BODY' && related.nodeName != 'HTML') {
		related = related.parentNode;
	}
	if(related.nodeName != 'BODY' && related.nodeName != 'HTML') {
		if (related != theElement) return;
	} else {
	  new Effect.Highlight(theElement, 
	    { startcolor:'#FFFF99',
	      endcolor:'#FFFFFF',
	      duration: 1,
	      afterFinish: function(){theElement.style.backgroundColor = "#FFFFFF";} 
		});
	}

}

function getPosition(theElement,posFor,posEvt,showElement) {
	if(posFor == 'x') {
		switch(showElement) {
			case'tooltip':
				var element_width = theElement.offsetWidth;
				if ((posEvt + (2*element_width)) < getWindowWidth()) {
					return 'left';
				} else {
					return 'right';
				}
				break;
			case'dialogBox':
				var show_width = 300;
				if (posEvt < show_width) {
					return 'left';
				} else {
					return 'right';
				}
				break;
		}
	} else {
		var element_height = theElement.offsetHeight;
		if ((element_height + posEvt) >= (getWindowHeight() - 15) ) {
			posEvt = posEvt + getScrollYOffset() - 15;
		} else {
			posEvt = posEvt + getScrollYOffset() + 15;
		} 
		return posEvt;
	}
}

function getWindowWidth(){
	if (window.innerWidth) {
		theWidth = window.innerWidth
	} else if (document.documentElement && document.documentElement.clientWidth) {
		theWidth = document.documentElement.clientWidth
	} else if (document.body) {
		theWidth = document.body.clientWidth
	}
	return theWidth;
}

function getWindowHeight(){
	if (window.innerHeight) {
		theHeight = window.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		theHeight = document.documentElement.clientHeight;
	} else if (document.body) {
		theHeight = document.body.clientHeight;
	}
	return theHeight;
}

function getScrollYOffset() {
	if (window.pageYOffset) {
		  pos = window.pageYOffset
	} else if (document.documentElement && document.documentElement.scrollTop) {
		pos = document.documentElement.scrollTop
	} else if (document.body) {
		  pos = document.body.scrollTop
	}
	return pos;
}

function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function clipAnchorBehaviour(e) {
	if(document.all) {
		e.cancelBubble = true;
	} else {
		e.stopPropagation();
	} 
}

/************
    End Misc Functions
*/

