/*
 * Islet.HoverPanel provides a base class for creating hover panels.
 */
Islet.HoverPanel = function() {
    this.hoverElement = null;
    this.hoverCloseElement = null;
    this.lastHoverTime = 0;
    this.hideAfterHoverIsLooping = false;
    this.insideHoverPanel = false;
    this.showCounter = 0;
    this.showDelayInMilliseconds = 600;
    this.showForRealTimerID = null;

    // Will track if we have left the original over element.
    this.stillInOverElement = false;

    this.hoverOffsetY = 5;
};


Islet.HoverPanel.prototype.show = function(overElement) {
    var self = this;

    this.overElement = overElement;
    this.stillInOverElement = true;

    this.showCounter++;
    var savedShowCounter = this.showCounter;

    // Show after a short delay.

    if (this.showForRealTimerID != null) {
        // Clear old timer if one exists.
        clearTimeout(this.showForRealTimerID);
        this.showForRealTimerID = null;
    }
    this.showForRealTimerID = setTimeout(function() {self.showForReal(savedShowCounter);}, this.showDelayInMilliseconds);
};

Islet.HoverPanel.prototype.cancelShowIfNotShown = function() {
    // Can be used to cancel show call if hover panel has not popped up after the initial delay.
    this.showCounter++;

    // This method is called upon leaving over element, so we clear stillInOverElement here.
    this.stillInOverElement = false;

    if (this.showForRealTimerID != null) {
        // Clear old timer if one exists.
        clearTimeout(this.showForRealTimerID);
        this.showForRealTimerID = null;
    }
};


Islet.HoverPanel.prototype.showForReal = function(savedShowCounter) {

    // See if this is an outdated show call.
    if (savedShowCounter != this.showCounter) {
        return;
    }

    this.showForRealTimerID = null;

    var self = this;
    var overElement = this.overElement;

    // This is to actually show the panel after a built-in delay to avoid showing to quickly after first mouse entry.
    if (this.hoverElement == null) {
        var hoverElement = document.createElement('div');
        hoverElement.className = 'islet-hover-panel';

        hoverElement.onmouseout = function() {
            self.updateLastHoverTime();
            self.insideHoverPanel = false;
        };

        hoverElement.onmouseover = function() {
            self.updateLastHoverTime();
            self.insideHoverPanel = true;
        };

        this.updateLastHoverTime();

        document.body.appendChild(hoverElement);
        this.hoverElement = hoverElement;

        var hoverCloseElement = document.createElement('div');
        hoverCloseElement.className = 'islet-hover-panel-closer';

        var hoverCloseImage = document.createElement('img');
        hoverCloseImage.style.border = 'none';
        hoverCloseImage.style.margin = '0';
        hoverCloseImage.style.padding = '0';
        hoverCloseImage.src = Islet.Paths.root + '/theme/islet-standard/pix/hover-close.gif';
        hoverCloseImage.onclick = function() {
            self.closeHoverPanel();
        };

        hoverCloseElement.appendChild(hoverCloseImage);

        document.body.appendChild(hoverCloseElement);
        this.hoverCloseElement = hoverCloseElement;
    }

    var overElementBounds = YAHOO.util.Dom.getRegion(overElement);
    this.hoverElement.style.left = overElementBounds.left + 'px';
    this.hoverElement.style.top = (overElementBounds.bottom + this.hoverOffsetY) + 'px';
    this.hoverCloseElement.style.left = (overElementBounds.left - 20) + 'px';
    this.hoverCloseElement.style.top = (overElementBounds.bottom + this.hoverOffsetY) + 'px';

    this.hoverElement.innerHTML = "Loading...";

    this.updateLastHoverTime();
    this.insideHoverPanel = false;
    this.hoverElement.style.display = 'block';
    this.hoverCloseElement.style.display = 'block';
    if (!this.hideAfterHoverIsLooping) {
        this.hideAfterHover();
    }

    if (this.onShowing) {
        // onShowing should be provided by derived classes to set hover element content.
        this.onShowing();
    }
};


Islet.HoverPanel.prototype.updateLastHoverTime = function() {
    this.lastHoverTime = (new Date()).getTime();
};

Islet.HoverPanel.prototype.closeHoverPanel = function() {
    this.hoverElement.style.display = 'none';
    this.hoverCloseElement.style.display = 'none';
};

Islet.HoverPanel.prototype.hideAfterHover = function() {
    var self = this;

    // The following is to keep multiple copies from being triggered.
    this.hideAfterHoverIsLooping = true;

    var retry = true;
    if (!this.insideHoverPanel && !this.stillInOverElement) {

        // See if we hide based on non-hover time.
        if (this.hoverElement.style.display == 'block') {
            var time = (new Date()).getTime();
            if ((time - this.lastHoverTime) > 2000) {
                this.closeHoverPanel();
                retry = false;
            }
        }
    }
    else {
        // We're either in hover panel or on the overElement.
        this.updateLastHoverTime();
    }

    if (retry) {
        setTimeout(function() {self.hideAfterHover();}, 500);
    }
    else {
        this.hideAfterHoverIsLooping = false;
    }
};



var d = YAHOO.util.Dom;
var $ = d.get;
	
window.$log = YAHOO.log;

(function() {
    var okButtons = [
		{ 	
			text:'Ok', 
			handler: function() {
				this.hide();
			} 
		}
	];
	 
    Islet.extend = function(target, destination) {
	 	for(var property in target)
	 		destination[property] = target[property];
	 	return destination;
	}
	 
	Islet.getUrlParam = function(strParamName){
        strParamName = escape(unescape(strParamName));

        var returnVal = new Array();
        var qString = null;
		  
			
        if (window.location.search.search(strParamName) > -1 ){
            qString = window.location.search.substr(1,window.location.search.length).split("&");
        }
		  	
		  
        if (qString==null) return null;
		  
		  
        for (var i=0;i < qString.length; i++){
            if (escape(unescape(qString[i].split("=")[0])) == strParamName){
                returnVal.push(qString[i].split("=")[1]);
            }
        }
		  
		  
        if (returnVal.length==0) return null;
        else if (returnVal.length==1) return returnVal[0];
        else return returnVal;
    };
	
    Islet.String = {
        htmlEncode : function (s) {
	 		// from: http://bytes.com/groups/javascript/469812-encoding-string-html-safe-characters
	 		if (s != null) {				 		
				return s.replace(/&(?!\w+([;\s]|$))/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
			}
			else {
				return '';
			}
		},

        htmlEncodeWithQuotes : function (s) {
	 		// from: http://bytes.com/groups/javascript/469812-encoding-string-html-safe-characters
	 		if (s != null) {
				return Islet.String.htmlEncode(s).replace('"', "&quot;").replace("'", "&apos;");
			}
			else {
				return '';
			}
		}
    };
	 
	 
    Islet.Notemarks = {};
	 
	 Islet.Notemarks.addNotemark = function() {
		 window.open(Islet.Paths.root + "/notemark/edit.php?" +					 					 				
	 				"course_context=" + Islet.Contexts.courseID + 
	 				"&cmid_context=" + Islet.Contexts.cmid, "_blank",
	 				"location=1,status=1,scrollbars=1,width=700,height=600");
	 };
	 
	 Islet.Notemarks.viewNotemarks = function() {
		 window.open(Islet.Paths.root + "/notemark/index.php?" +					 					 				
				 	"course_context=" + Islet.Contexts.courseID + 
					"&cmid_context=" + Islet.Contexts.cmid, "_blank",
		 			"location=1,status=1,scrollbars=1,width=700,height=600");
	 };
	 
	 
	 Islet.UI = {};
	 Islet.UI.Dialog = function(id, options) {
	 		this.dialog = null;
		 	this.id = id;
		 	this.options = options;
	 }
	 
	 $log('made to dialog prototype');
	 
	 Islet.UI.Dialog.prototype = {
	 	init: function() {
	 		if(YAHOO) {
		 		var options = {
		 			width: "600px", 
			        fixedcenter:true,  
			        close:false,  
			        draggable:false,  
			        zindex:1000, 
			        modal:true, 
			        visible:false, 
					'buttons': okButtons,
					title: "",
					body: "<div id='" + this.id + "-body' class='dialog-content'></div>"
				 };
		 		
		 		Islet.extend(this.options || {}, options);
		 		this.dialog = new YAHOO.widget.Dialog(this.id, options);
                this.dialog.isletDialog = this;
                this.dialog.parentHide = this.dialog.hide;
                this.dialog.hide = function() {                    
                    this.isletDialog.onHiding();
                    this.parentHide();
                };

		 		this.dialog.setHeader(options.title || "");
		 		this.dialog.setBody(options.body || "");
		 		this.dialog.render(document.body);
 			}
	 	},
		show: function() {
			
			if(this.dialog == null)
				this.init();
			this.onShowing();
			this.dialog.show();
		},
		onShowing: function() {
		 	
		},
	 	onHiding: function() {
			 	
		},
		hide: function() {
			if(this.dialog != null)
			{						
				this.dialog.hide();
			}	
		}
	 }
	 
	 YAHOO.util.Event.onDOMReady(function() {

		 Islet.UI.Window = new Islet.UI.Dialog('window-dialog', {width: "700px"});
		 w = Islet.UI.Window;
	 	
		 w.baseInit = w.init;
	 	
		 w.init = function() {
			 w.baseInit();
			 this.dialog.setBody("<iframe width='640px' height='100%' id='" + this.id + "-body' class='dialog-content'></iframe>");
		 }
	 	
		 w.show = function(options) {
			 if(!this.dialog)
				 this.init();
	 		
			 options = options || {};
	 		
			 var title = options.title || "Window";
			 var url = options.url;
	 		
			 if(options.event)
				 YAHOO.util.Event.stopEvent(options.event);
	 		
			 this.dialog.setHeader(title);
			 var dlgBody = document.getElementById("window-dialog-body");
			 dlgBody.src =  url;
			 this.dialog.show();
			 return false;
		 }
	 	
	
 		Islet.UI.ActivityDialog = new Islet.UI.Dialog("activity-dialog", {title: "Activity Wall", width: "700px"});
		Islet.UI.ActivityDialog.onShowing = function() {
				asyncPrintRecentActivityTableToDiv('activity-dialog-body', Islet.Paths.root, Islet.UI.ActivityDialog.courseID);		
		}
		Islet.UI.OnlineUsersDialog = new Islet.UI.Dialog("online-users-dialog", {title: "Online Users"});
		Islet.UI.OnlineUsersDialog.onShowing = function() {
			var el = $('online-users-dialog-body');
			if(!el.isset)
			{
				el.innerHTML = $('online-users-all').innerHTML;
				el.isset = true;	
			}
		}
		 
		 				 	
		Islet.UI.GlossaryDialog = new Islet.UI.Dialog('glossary-dialog', {title: "Glossary Highlight"});
 		var g = Islet.UI.GlossaryDialog;
 		 
 		g.findContext = function(words) {
 		 	
            window.location = Islet.Paths.root + '/blocks/moca/search.php?courseid=' + Islet.Contexts.courseID +
                '&keyword=' + encodeURIComponent(words);

            /*
 		 	if(this.dialog == null)
 		 		this.init();
 		 	this.dialog.setHeader("Context for &quot;" + words + "&quot;");
 		 	
 		 	var filter = {
 		 		word: words, 
 		 		highlightSpanClass: "highlight",
 		 		courseID: Islet.Contexts.courseID
 		 	};			

			FlowBasis.rpc.invoke(
				Islet.Paths.root + "/jsonservices/GlossaryContextService.php",
				"getContexts",
				[ filter ],
				function (response) {
					if (response.error == null)
					  	g.buildContext(response.result.records);				
					else 
						g.setContent("Response Error: " + response.error.message);	
				}
			);
			
			g.show();
            */
 		}
		 
		g.buildContext = function(records){
		 	var html = "No contexts available.";
		 	
		 	if(records && records.length > 0) {
		 		html = "<ul>\n";
			 	for (var i = 0; i < records.length; i++) {
						var context = records[i];
						var handleJson = YAHOO.lang.JSON.stringify(context.handle);
						handleJson = handleJson.replace(/\"/g, '\\\"');
						html += "<li>"
						html +=  "<a href='javascript:void(0);' onclick='Islet.UI.GlossaryDialog.highlight(\"" + handleJson + "\")'>";
						html += context.previewText;
						html += "</a>";					
						html += "</li>";
				}
				html += "</ul>";
			}
			g.setContent(html);
		}
 		 
 		g.onShowing = function() {
 			g.setProgress();
 		}
 		 
 		g.setContent = function(content) {
 			document.getElementById('glossary-dialog-body').innerHTML = content;
 		}
 		 
 		g.getContent = function() {
 		 	return document.getElementById('glossary-dialog-body').innerHTML;
 		}
 		 
 		g.setProgress = function() {
 		 	g.setContent("<span class='ajax-progress'>Loading</span>");
 		}
 		 
 		g.showRecords = function() {
 		 	g.setContent(g.records);
 		}
 		 
 		g.highlight = function(handleJson) {
 		 	g.records = g.getContent();
 		 	g.setProgress();
 		 	
 		 	var handle = YAHOO.lang.JSON.parse(handleJson);
 		 	
 		 	FlowBasis.rpc.invoke(Islet.Paths.root + "/jsonservices/GlossaryContextService.php",
				"getContextContentsAsHtml",
				[ handle, {highlightSpanClass : "highlight"} ],
				function (response) {
					if (response.error == null) {
						g.setContent("<ul class='layout'><li>" + response.result + 
						"</li><li><a href='javascript:void(0);' onclick='Islet.UI.GlossaryDialog.showRecords();'>&lt;&lt; back to results</a></li></ul>");
					} else {
						g.setContent("Response Error: " + response.error.message);
					}				
				}
			 );
 		} 

 		
	});						
	 
    Islet.Logout = {};
    
    Islet.Logout.doLogout = function() {
		window.location = Islet.Paths.root + '/login/logout.php?sesskey=' + Islet.sessionKey;
	};
    
    Islet.Logout.showLogoutDialog = function() {
    	        	
    	if (!Islet.Logout.dialog) {
	    	Islet.Logout.dialog = new Islet.UI.Dialog(
				'islet-logout-dialog', 
				{
					title: "Logout",
					width: null,
					close: true,					
					 'buttons': [],
					 body: "<div id='islet-logout-dialog-panel'>" +
						"<div id='islet-logout-dialog-content' style='width: 600px; height: 350px; overflow: auto; padding: 10px'></div>" +
						"<div style='width: 600px; text-align: right'>" + 
						"<a href='javascript:void(0);' onclick='Islet.Logout.doLogout();'>Logout</a>" +
						"</div>" +
						"</div>"
				});
	    							    		    	
	    	Islet.Logout.dialog.onShowing = function() {
				
				// Contents of challenge dialog must be initialized.
				
				var dlgBody = document.getElementById('islet-logout-dialog-content');				
				dlgBody.innerHTML = 'Loading...';
				
				FlowBasis.rpc.invoke(
					Islet.Paths.root + '/jsonservices/LogoutService.php',
					'getLogoutDialogHtml', [ Islet.Contexts ],
					function (response) {
						var dlgBody = document.getElementById('islet-logout-dialog-content');
						if (response.error == null) {
							dlgBody.innerHTML = response.result;
						}
						else {
							dlgBody.innerHTML = response.error.message;
						}
					});
			};
    	}
    	
    	Islet.Logout.dialog.show();								
    };


    
    Islet.GlossaryHoverPanel = new Islet.HoverPanel();
    Islet.GlossaryHoverPanel.entryID = -1;

    Islet.GlossaryHoverPanel.showForEntry = function(entryID, overElement) {
        this.entryID = entryID;
        this.show(overElement);
    };

    Islet.GlossaryHoverPanel.onShowing = function() {
        var self = this;
        var entryIDToLoad = this.entryID;

        FlowBasis.rpc.invoke(
            Islet.Paths.root + "/jsonservices/GlossaryContentService.php",
            "getContentByEntryID",
            [ entryIDToLoad ],
            function (response) {
                if (response.error == null) {
                    if (self.entryID == entryIDToLoad) {
                        // The comparison makes sure this is still the element we wanted to load.
                        self.hoverElement.innerHTML = response.result;
                        FlowBasis.Dom.rerunScripts(self.hoverElement);

                        // This will give us some extra time before hover panel disappears.
                        self.updateLastHoverTime();
                    }
                }
                else {
                    self.hoverElement.innerHTML = response.error.message;
                }
            });
    };


    Islet.HelpHoverPanel = new Islet.HoverPanel();
    Islet.HelpHoverPanel.options = null;
    
    Islet.HelpHoverPanel.showForOptions = function(helpOptions, overElement) {
        this.helpOptions = helpOptions;
        this.show(overElement);
    };

    Islet.HelpHoverPanel.onShowing = function() {
        var self = this;
        var optionsToLoad = this.helpOptions;

        FlowBasis.rpc.invoke(
            Islet.Paths.root + "/jsonservices/HelpContentService.php",
            "getHelpContent",
            [ optionsToLoad ],
            function (response) {
                if (response.error == null) {                   
                    if (self.helpOptions && self.helpOptions.id == optionsToLoad.id) {
                        // The comparison makes sure this is still the element we wanted to load.
                        self.hoverElement.innerHTML = response.result;
                        FlowBasis.Dom.rerunScripts(self.hoverElement);

                        // This will give us some extra time before hover panel disappears.
                        self.updateLastHoverTime();
                    }
                }
                else {
                    self.hoverElement.innerHTML = response.error.message;
                }
            });
    };


    Islet.VideoPopup = {};    

    Islet.VideoPopup.showVideo = function(videoUrl, width, height) {
        if (!Islet.VideoPopup.dialog) {
	    	Islet.VideoPopup.dialog = new Islet.UI.Dialog(
				'islet-video-dialog',
				{
					title: "Watch Video",
					width: null,
					close: true,
                    'buttons': [],
					body: "<div id='islet-video-dialog-panel'>" +						
						"</div>",
                    zIndex: 10000
				});

            Islet.VideoPopup.dialog.onHiding = function() {              
                var dlgBody = document.getElementById('islet-video-dialog-panel');
                dlgBody.innerHTML = '';				
            },

	    	Islet.VideoPopup.dialog.onShowing = function() {

				// Contents of video dialog must be initialized.

				var dlgBody = document.getElementById('islet-video-dialog-panel');
				dlgBody.innerHTML = 'Loading...';

                var playerDivID = 'islet-video-dialog-panel';

                // Setup video object.
                var so = new SWFObject(Islet.Paths.root + '/blocks/transcriber/flash/player-licensed.swf', playerDivID + '-embed', width, height,'10');
                so.addParam('allowscriptaccess','always');
                so.addParam('allowfullscreen','true');
                so.addParam('wmode', 'transparent');
                so.addVariable('file',this.videoUrl);
                so.addVariable('type', 'video');
                so.addVariable('id', playerDivID);
                so.addVariable('bufferlength', 10);
                so.addVariable('autostart', 'true');
                so.write(playerDivID);
			};
    	}

        Islet.VideoPopup.dialog.videoUrl = videoUrl;

    	Islet.VideoPopup.dialog.show();
    };


})();
				 
