﻿/*--------------------------------------------------------------------------*/
function $(element) {
    if (typeof(element) == "string")
        return document.getElementById(element);
    else
        return element;
}
function execute(f) {
	if (f != null) {
		f();
	}
}
/*--------------------------------------------------------------------------*/
if (typeof tal == "undefined" || !tal) {
    var tal = {};
}
/*--------------------------------------------------------------------------*/
tal.Context = {
    returnUrl: null
};
/*--------------------------------------------------------------------------*/
(function() {
	tal.Dom = {
	    getStyle: function(element, style)
        {
            var element = $(element);
	        if (element.currentStyle)
	        {
		        var value = element.currentStyle[style];
		    }
	        else if (window.getComputedStyle)
	        {
		        var value = document.defaultView.getComputedStyle(element, null).getPropertyValue(style);
		    }
		    return value;
        },
        
        setStyle: function(element, style, value)
        {
            element.style[style] = value;
        },
        
		visible: function(element)
		{
		    return tal.Dom.getStyle(element, "display") != "none";
			return $(element).style.display != 'none';
		},

		toggle: function(element)
		{
			element = $(element);
			tal.Dom[tal.Dom.visible(element) ? 'hide' : 'show'](element);
			return element;
		},

		hide: function(element)
		{
			$(element).style.display = 'none';
			return element;
		},

		show: function(element)
		{
			$(element).style.display = 'block';
			return element;
		},
		
		/*
		    hasClass: returns true if the element contains the given class.
		    Todo: refactor.
		 */
		hasClass: function(element, cls)
		{
		    return element.className.indexOf(cls) != -1;
		},
	    
		addClass: function(element, cls)
		{
			var elm = $(element);
			elm.className += " " + cls;
		},
	    
		removeClass: function(element, className)
		{
			var elm = $(element);
            elm.className = elm.className.replace(new RegExp(' ?' + className + ' ?'), '');			
		},
	    
		setWidth: function(element, width)
		{
			var elm = $(element);
			elm.style.width = width + "px";
		},
	    
		setHeight: function(element, height)
		{
			var elm = $(element);
			elm.style.height = height + "px";
		},
	    
		setTop: function(element, top)
		{
			var elm = $(element);
			elm.style.top = top + "px";
		},
	    
		setLeft: function(element, left)
		{
			var elm = $(element);
			elm.style.left = left + "px";
		},
	    
		setRight: function(element, right)
		{
			var elm = $(element);
			elm.style.right = right + "px";
		},
	    
		setValue: function(element, value)
		{
			var elm = $(element);
			elm.innerHTML = value;
		},
	    
		getWindowDimensions: function()
		{
			var winW = 1024, winH = 768;

			if (parseInt(navigator.appVersion)>3)
			{
				if (navigator.appName=="Netscape")
				{
					winW = window.innerWidth;
					winH = window.innerHeight;
				}
				if (navigator.appName.indexOf("Microsoft")!=-1)
				{
					winW = document.body.offsetWidth;
					winH = document.body.offsetHeight;
				}
			}

			return [winW, winH];
		},
	    
		getPageSize: function()
		{  /*
            var myWidth = 0, myHeight = 0;
            if( typeof( window.innerWidth ) == 'number' )
            {
                //Non-IE
                myWidth = window.innerWidth;
                myHeight = window.innerHeight;
            }
            else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ))
            {
                //IE 6+ in 'standards compliant mode'
                myWidth = document.documentElement.clientWidth;
                myHeight = document.documentElement.clientHeight;
            }
            else if (document.body && ( document.body.clientWidth || document.body.clientHeight ))
            {
                //IE 4 compatible
                myWidth = document.body.clientWidth;
                myHeight = document.body.clientHeight;
            }
            return [myWidth, myHeight];*/
		    
			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 = xScroll; //pageWidth = windowWidth;
			}
			else
			{
				pageWidth = xScroll;
			}

			arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
			return arrayPageSize;
		},
		
		getScrollPosition: function()
		{
            var scrOfX = 0, scrOfY = 0;
            if (typeof(window.pageYOffset) == 'number')
            {
                //Netscape compliant
                scrOfY = window.pageYOffset;
                scrOfX = window.pageXOffset;
            }
            else if (document.body && ( document.body.scrollLeft || document.body.scrollTop ))
            {
                //DOM compliant
                scrOfY = document.body.scrollTop;
                scrOfX = document.body.scrollLeft;
            }
            else if (document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ))
            {
                //IE6 standards compliant mode
                scrOfY = document.documentElement.scrollTop;
                scrOfX = document.documentElement.scrollLeft;
            }
            return [scrOfX, scrOfY];		
		},
		
		getByClass: function(oElm, strTagName, strClassName)
		{
			var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
			var arrReturnElements = new Array();
			strClassName = strClassName.replace(/\-/g, "\\-");
			var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
			var oElement;
			for (var i=0; i<arrElements.length; i++)
			{
				oElement = arrElements[i];
				if(oRegExp.test(oElement.className))
				{
					arrReturnElements.push(oElement);
				}
			}
			return (arrReturnElements);
		},
		
		getFirstChild: function(element)
		{
			var children = element.childNodes;
			var i = 0;
			while (children[i].nodeType == 3) i++;		
			return children[i];
		},
		
		include: function(src)
		{
			var head = document.getElementsByTagName('head')[0];
			
			script = document.createElement('script');
			script.src = src;
			script.type = 'text/javascript';
			
			head.appendChild(script);		
		},
		
		onReady: function(f)
		{
			//W3C
			if(document.addEventListener)
			{
				document.addEventListener("DOMContentLoaded", f, false);
			}
			//IE
			else
			{
				document.onreadystatechange = function()
				{
					//dom is ready for interaction
					if(document.readyState == "interactive")
					{
						f();
					}
				};
			}
		}, // onReady
		
		generateElement: function(className, container)
		{    		
    		// Create element.
		    var element = document.createElement("div");
		    tal.Dom.addClass(element, className);
		    //tal.Dom.hide(element);
		    
		    // Append to container.
		    container.appendChild(element);
		    
		    return element;
		}, // generateElement
		
		generateBppi: function(container)
		{
		    var bppi = tal.Dom.generateElement("bppi", container);
		    var blocker = tal.Dom.generateElement("blocker", bppi);
		    var loading = tal.Dom.generateElement("loading", bppi);
		    
		    container.style.position = "relative";
		    
		    tal.Dom.setHeight(bppi, container.offsetHeight);
		    tal.Dom.setWidth(bppi, container.offsetWidth);
		    
		    return bppi;
		}, // generateIndicator
		
		toggleProcessing: function(container)
		{
		    if (tal.Dom.hasClass(container, "processing"))
		    {
		        tal.Dom.removeClass(container, "processing");
		    }
		    else
		    {
		        tal.Dom.addClass(container, "processing");
		    }
		} // toggleProcessing
	}; // Dom
})();
/*--------------------------------------------------------------------------*/
tal.Event = {
    addListener: function(object, e, func) {
		if(window.addEventListener){ // Mozilla, Netscape, Firefox
			object.addEventListener(e, func, false);
		} else { // IE
			object.attachEvent("on" + e, func);
		}    
    },
    
    on: function(object, e, func) {
        return tal.Event.addListener(object, e, func);
    },
    
    onEnter: function(object, func) {
        return tal.Event.addListener(object, "keydown", function(e)
            {
                if (e.which == 13)
                {
                    func();
                }
            });
    },
    
	addLoadEvent: function(func) {
		var oldonload = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				if (oldonload) {
					oldonload();
				}
				func();
			}
		}
	}
};
/*--------------------------------------------------------------------------*/
var Conf = {
    
};
/*--------------------------------------------------------------------------*/
//var Container = {
//	
//};
/*--------------------------------------------------------------------------*/
tal.Modal = function()
{		
	var _me, _containerId, _container, _blocker, _wrap, _close, _cont,
	    _minTop = 44, _minLeft = 10, _width = 200, _height = 200;
	    
	var OFFSET = 30;
		
	return {
	    init: function(containerId)
	    {
	        _me = this;
	        
	        // Get container.
	        _containerId = containerId;
		    _container = $(_containerId);
    		
    		// Create blocker.
    		_blocker = tal.Dom.generateElement("screen-blocker", _container);
    		
    		// Create wrapper.
		    _wrap = document.createElement("div");
		    tal.Dom.addClass(_wrap, "wrap");
		    tal.Dom.hide(_wrap);
    		
    		// Create close button.
		    _close = document.createElement("a");
		    _close.innerHTML = "סגור";
		    _close.className = "button";
		    $addHandler(_close, "click", function() {
			    _me.hide();
			    return false;
		    });
		    _close.href = "javascript://";		
		    tal.Dom.addClass(_close, "btn-close");
		    tal.Dom.hide(_close);
    		
    		// Create content.
		    _cont = document.createElement("div");
		    tal.Dom.addClass(_cont, "content");
		    tal.Dom.hide(_cont);
    		
    		// Add elements to the modal container.
		    _wrap.appendChild(_close);
		    _wrap.appendChild(_cont);
		    _container.appendChild(_wrap);
	    },
	    
	    updatePosition: function()
	    {
		    var pageSize = tal.Dom.getPageSize();
		    var scrollPosition = tal.Dom.getScrollPosition();
    		
		    windowDimensions = tal.Dom.getWindowDimensions();
    		
		    var left = (windowDimensions[0] - _wrap.offsetWidth) / 2;
		    var top = (windowDimensions[1] - _wrap.offsetHeight) / 2;
    		
		    if (left < _minLeft)
		    {
			    left = _minLeft;
			}
			
		    if (top < _minTop)
		    {
			    top = _minTop;
    		}
    		
		    _wrap.style.left = (left) + "px";
		    _wrap.style.top = (top + scrollPosition[1]) + "px";
    		
		    _blocker.style.width = pageSize[0] + "px";
		    _blocker.style.height = pageSize[1] + "px";
	    },
    	
	    show: function(c, sc, width, height)
	    {
		    tal.Dom.show(_blocker);
		    tal.Dom.show(_wrap);
		    tal.Dom.show(_cont);
    		
    		// Show close button.
		    if (sc == true || sc == undefined)
		    {
			    tal.Dom.show(_close);
			}
    		
		    _cont.innerHTML = c;
    		
    		// Set dimensions.
    		//
		    tal.Dom.setWidth(_wrap, _width);
    		tal.Dom.setHeight(_wrap, _height);
    		tal.Dom.setWidth(_cont, _width - OFFSET * 2);
    		tal.Dom.setHeight(_cont, _height - OFFSET * 2);
    		
		    _me.executeJs();
		    _me.updatePosition();
		    
		    setTimeout(_me.updatePosition, 1000);
		    
		    tal.Event.addListener(window, "scroll", _me.updatePosition);
		    tal.Event.addListener(window, "resize", _me.updatePosition);
	    },
    	
	    executeJs: function()
	    {
		    var tags = _cont.getElementsByTagName("script");
		    for (var i = 0; i < tags["length"]; i++) {
			    eval(tags[i].innerHTML);
		    }
	    },
    	
	    getContent_CallBack: function(res)
	    {
		    tal.Dom.removeClass(_cont, "loading");
		    _me.show(res.d);
	    },
    	
	    showLoading: function()
	    {
		    this.show("", true, 200, 150);
		    tal.Dom.addClass(_cont, "loading");
	    },
    	
	    hide: function()
	    {
		    tal.Dom.hide(_blocker);
		    tal.Dom.hide(_wrap);
		    tal.Dom.hide(_close);
		    tal.Dom.hide(_cont);
		    _cont.innerHtml = "";
	    },
	    
	    setWidth: function(width)
	    {
	        _width = width + OFFSET * 2;
	    },
	    
	    setHeight: function(height)
	    {
	        if (height == 0)
	        {
	            var windowDimensions = tal.Dom.getWindowDimensions();
	            _height = windowDimensions[1];
	            _minTop = 0;
	        }
	        else
	        {
	            _height = height + OFFSET * 2;
	        }
	    }
    } // Return	
}(); // Modal
/*--------------------------------------------------------------------------*/
tal.UI = function() {
	var _me;
	
	var Dom = tal.Dom;
	var Event = tal.Event;
	
	return {
		init: function(siteUrl)
		{
		    _me = this;
			window.onerror = this.onError;
			_me.siteUrl = siteUrl;
			tal.Modal.init("modal_container");
			tal.Login.init();
		},
	    
		onError: function(errMsg, errScript, errLine) {
			//alert(errMsg);
		},
	    
		showSignup: function(url) {
			tal.Modal.showLoading();
			tal.Modal.setWidth(310);
			tal.Modal.setHeight(300);
			this.redirectUrl = url;
			talmidonet.web.services.ajax.getRegistrationPanel(
				tal.Modal.getContent_CallBack);	
		},
	    
		toggleMyCourses: function() {
			tal.Dom.toggle("myCourses");
		},
	    
		showUploadMaterial: function() {
			tal.Modal.showLoading();
			tal.Modal.setWidth(300);
			tal.Modal.setHeight(316);
			talmidonet.web.services.ajax.getUploadMaterialPanel(
				tal.Modal.getContent_CallBack);
		},
	    
		pages: function() {
			var Event = tal.Event;
			
			return {
				homepage: function() {
					return {
					}
				}(), // Homepage
				
				upload: function() {
					var _swfu;
					var _nextStepUrl;
					var _uploadSessionId;
					
					return {
						init: function(uploadSessionId) {
							var me = this;
							_nextStepUrl = tal.UI.siteUrl + "material/details.aspx";
							_uploadSessionId = uploadSessionId;
							_swfu = new SWFUpload({
								upload_url: tal.UI.siteUrl + "Services/Upload.ashx?uploadSessionId=" + _uploadSessionId,
								post_params: {},
								file_size_limit: "30 MB",
								file_types: "*.doc; *.docx; *.ppt; *.pptx; *.pps; *.xls; *.xlsx; *.pdf; *.ps; *.odt; *.odp; *.sxw; *.sxi; *.txt; *.rtf",
								file_types_description: "Microsoft Office, PDF, Open Ofice, Text",
								file_upload_limit: "10",
				                file_queue_limit : 0,

				                // Button settings
				                button_image_url: tal.UI.siteUrl + "js/swfupload/button.png",	// Relative to the Flash file
				                button_width: "130",
				                button_height: "35",
				                button_placeholder_id: "spanButtonPlaceHolder",
				                button_text: '',
				                button_text_style: "",
				                button_text_left_padding: 12,
				                button_text_top_padding: 3,
				                
				                // The event handler functions are defined in handlers.js
				                file_queued_handler : fileQueued,
				                file_queue_error_handler : fileQueueError,
				                file_dialog_complete_handler : fileDialogComplete,
				                upload_start_handler : uploadStart,
				                upload_progress_handler : uploadProgress,
				                upload_error_handler : uploadError,
				                upload_success_handler : uploadSuccess,
				                upload_complete_handler : function(fileObj) { me.uploadComplete(fileObj, this); },
				                queue_complete_handler : queueComplete,	// Queue plugin event

								//Flash Settings
								flash_url: tal.UI.siteUrl + "js/swfupload/swfupload.swf",
								swfupload_element_id: "flUpload",
								degraded_element_id: "degradedUpload",
								custom_settings: {
									progressTarget: "divFileProgressContainer",
									cancelButtonId: "flUploadCancel"
								},
								
								// Debug settings
								debug: false
							});
							
							//var params = { "uploadSessionId": _uploadSessionId };
							//_swfu.setPostParams(params);
							
//							Event.addListener($("flUploadSelect"), "click", function() {
//									_swfu.selectFiles();
//								});
							Event.addListener($("flUploadCancel"), "click", function() {
									cancelQueue(_swfu);
								});
							
							this.swfu = _swfu;							
							return _swfu;
						}, // Init
						
						uploadComplete: function(fileObj, scope)
						{
							try
							{
								/*  I want the next upload to continue automatically so I'll call startUpload here */
								if (scope.getStats().files_queued === 0)
								{
								    if (scope.getStats().successful_uploads > 0)
								    {
									    document.getElementById(scope.customSettings.cancelButtonId).disabled = true;
									    this.nextStep();
                                    }
								}
								else
								{	
									scope.startUpload();
								}
							}
							catch (ex)
							{
							    scope.debug(ex);
                            }
						},
						
						nextStep: function() {
							var url = String.format(_nextStepUrl, _uploadSessionId);
							window.location = url;
						}
					} // Upload Return
				}() // Upload
			}
		}() // Pages
	}; // UI Return
}(); // UI
/*--------------------------------------------------------------------------*/
tal.Login = function() {
    var _me, _login, _username, _password, _send, _register, _loading, _toolbar,
        _myCourses, _links, _logout, _bppi, _textChange;
    
    // Consts
    var TEXT_EMAIL = "הזיני כתובת דואר אלקטרוני";
    var TEXT_PASSWORD = "הזיני סיסמה";
    var CLASS_INPUT_TEXT = "default";
    
    return {
        init: function()
        {
            _me = this;
            _login = $("login");
            
            _form = $("frmLogin");
            
            if (_form != null)
            {
                _me.initLoginForm();
                
                if (_login != undefined)
                {
                    _me.initRegister();
                }
            }
            
            if (_login != undefined)
            {                
                _toolbar = tal.Dom.getByClass(_login, "ul", "toolbar")[0];
            
                if (_toolbar != null)
                {
                    _me.initWelcome();
                }
            }
        },
        
        initLoginForm: function()
        {
            _username = $("txtEmail");
            _password = $("txtPassword");
            _send = tal.Dom.getByClass(_form, "a", "send")[0];
            _loading = tal.Dom.getByClass(_form, "span", "loading")[0];
            _bppi = tal.Dom.generateBppi(_form);
            _textChange = _form.attributes["textchange"].nodeValue == "True" ? true : false;
            
            if (_textChange)
            {
                _me.onBlur(_username);
                _me.onBlur(_password);
                
                tal.Event.addListener(_username, "focus", function() { _me.onFocus(_username); });
                tal.Event.addListener(_password, "focus", function() { _me.onFocus(_password); });
                tal.Event.addListener(_username, "blur", function() { _me.onBlur(_username); });
                tal.Event.addListener(_password, "blur", function() { _me.onBlur(_password); });
            }
                
            // Add event listeners.
            tal.Event.addListener(_form, "keydown", function(e) { if (e.which == 13) _me.submit(); });
            tal.Event.addListener(_send, "click", function() { _me.submit(); });
        },
        
        initRegister: function()
        {
            _register = tal.Dom.getByClass(_login, "a", "btn-register")[0];
            tal.Event.addListener(_register, "click", tal.UI.showSignup);
        },
	    
		initWelcome: function() 
		{
			_myCourses = tal.Dom.getByClass(_toolbar, "*", "my-courses")[0];
			_links = tal.Dom.getByClass(_login, "*", "links")[0];
			_logout = tal.Dom.getByClass(_login, "a", "btn-logout")[0];
			
			var placeholder = tal.Dom.getFirstChild(_myCourses, "div");
			
			tal.Event.addListener(_myCourses, "mouseover", function() { tal.Dom.addClass(placeholder, "selected"); });
			tal.Event.addListener(_myCourses, "mouseout", function() { tal.Dom.removeClass(placeholder, "selected"); });
			tal.Event.addListener(_logout, "click", function() { tal.Auth.logout( function() { location.reload() }); });
		},
        
        submit: function()
        {
            var username = _username.value;
            var password = _password.value;
            
            if (username == TEXT_EMAIL)
            {
                username = "";
            }
            
            if (password == TEXT_PASSWORD)
            {
                password = "";
            }
            
            if (_me.validate(username, password))
            {
                tal.Dom.toggleProcessing(_form);
                tal.Auth.login(username, password, true, _me.submit_Callback);
            } 
        },
        
        validate: function(username, password)
        {
            if (username == "" || password == "")
            {
                return false;
            }
            else
            {
                return true;
            }
        },
        
        submit_Callback: function(res)
        {
            tal.Dom.toggleProcessing(_form);
            
            if (res.d)
            {
                if (tal.Context.returnUrl != null)
                {
                    location = tal.Context.returnUrl;
                }
                else
                {
                    location.reload();
                }
            }
            else
            {
                alert("שם משתמש ו/או סיסמה אינם תואמים");
            }
        },
        
        onFocus: function(which)
        {
            if (which == _username)
            {
                if (which.value == TEXT_EMAIL)
                {
                    which.value = "";
                }
                tal.Dom.removeClass(_username, CLASS_INPUT_TEXT);
            }
            else
            {
                if (which.value == TEXT_PASSWORD)
                {
                    which.type = "password";
                    which.value = "";
                }
                tal.Dom.removeClass(_password, CLASS_INPUT_TEXT);
            }
        },
        
        onBlur: function(which)
        {
            if (which.value == "")
            {
                tal.Dom.addClass(which, CLASS_INPUT_TEXT);
                
                if (which == _username)
                {
                    which.value = TEXT_EMAIL;
                }
                else
                {
                    try
                    {
                        which.type = "text";
                    }
                    catch(e) {}
                    which.value = TEXT_PASSWORD;
                }
            }
        }
    } // Return
}(); // Login
/*--------------------------------------------------------------------------*/
Messages = function() {
	var MSGTIMER = 20;
	var MSGSPEED = 5;
	var MSGOFFSET = 110;
	var MSGHIDE = 3;
	var me = this;
	var msg = null,
		msgContent = null;
		
	var Dom = tal.Dom;
	
	this.init = function() {
		msg = document.createElement("div");
		msgContent = document.createElement("div");
		tal.Dom.addClass(msg, "msg");
		tal.Dom.addClass(msgContent, "msg-content");
		tal.Dom.hide(msg);
		document.body.appendChild(msg);
		msg.appendChild(msgContent);
		msg.style.filter = 'alpha(opacity=0)';
		msg.style.opacity = 0;
		msg.alpha = 0;
	}
	this.init();

	// build out the divs, set attributes and call the fade function //
	this.show = function(target, string, autohide) {
		tal.Dom.setValue(msgContent, string);
		tal.Dom.show(msg);
		var msgheight = msg.offsetHeight;
		target = $(target);
		target.select();
		var targetheight = target.offsetHeight;
		var targetwidth = target.offsetWidth;
		var topposition = this.topPosition(target) - ((msgheight - targetheight) / 2);
		var rightposition = this.rightPosition(target);
		
		tal.Dom.setTop(msg, topposition);
		tal.Dom.setRight(msg, rightposition);
		
		clearInterval(msg.timer);
		msg.timer = setInterval(function() { me.fadeMsg(1); }, MSGTIMER);
		if(!autohide) {
			autohide = MSGHIDE;  
		}
		window.setTimeout(function() { me.hideMsg(); }, (autohide * 1000));
	}

	// hide the form alert //
	this.hideMsg = function() {
		if(!msg.timer) {
			msg.timer = setInterval(function() { me.fadeMsg(0); }, MSGTIMER);
		}
	}

	// face the message box //
	this.fadeMsg = function(flag) {
		if(flag == null) {
			flag = 1;
		}
		var value;
		if(flag == 1) {
			value = msg.alpha + MSGSPEED;
		} else {
			value = msg.alpha - MSGSPEED;
		}
		msg.alpha = value;
		msg.style.opacity = (value / 100);
		msg.style.filter = 'alpha(opacity=' + value + ')';
		if(value >= 99) {
			clearInterval(msg.timer);
			msg.timer = null;
		} else if(value <= 1) {
			tal.Dom.hide(msg);
			clearInterval(msg.timer);
		}
	}

	// calculate the position of the element in relation to the left of the browser //
	this.rightPosition = function(target) {
	    return tal.Dom.getPageSize()[0] - this.leftPosition(target);
	}
	
	this.leftPosition = function(target) {
		var left = 0;
		if(target.offsetParent) {
			while(1) {
				left += target.offsetLeft;
				if(!target.offsetParent) {
					break;
				}
				target = target.offsetParent;
			}
		} else if(target.x) {
			left += target.x;
		}
		return left;
	}	

	// calculate the position of the element in relation to the top of the browser window //
	this.topPosition = function(target) {
		var top = 0;
		if(target.offsetParent) {
			while(1) {
				top += target.offsetTop;
				if(!target.offsetParent) {
					break;
				}
				target = target.offsetParent;
			}
		} else if(target.y) {
			top += target.y;
		}
		return top;
	}

	// preload the arrow //
	if(document.images) {
	  arrow = new Image(7,80); 
	  arrow.src = "images/msg_arrow.gif"; 
	}
}
/*--------------------------------------------------------------------------*/
tal.Auth = function()
{
    return {
        login: function(username, password, persist, callback)
        {
            talmidonet.web.services.ajax.Login(
                    username,
                    password,
                    persist,
                    callback
                );
        },
        
        logout: function(callback)
        {
            talmidonet.web.services.ajax.Logout(callback);
        }
    } // Return
}(); // Auth

/*var Auth = {
    usernameEntry: null,
    passwordEntry: null,
    username: null,
    password: null,
    textLoggedIn: null,
    textNotLoggedIn: null,
    buttonLogin: null,
    buttonLogout: null,
    loginForm : null,
    self: this,

    init: function()
    {
        this.usernameEntry = $get("NameId");
        this.passwordEntry = $get("PwdId");
        this.username = $get("txtEmail");
        this.password = $get("txtPassword");
        this.textLoggedIn = $get("loggedin");
        this.textNotLoggedIn = $get("notloggedin");
        this.buttonLogin = $get("ButtonLogin");  
        this.buttonLogout = $get("ButtonLogout"); 
        this.loginForm = $get("frmLogin");
    },          

    // This function sets and gets the default
    // login completed callback function.
    SetDefaultLoginCompletedCallBack: function()
    {
        // Set the default callback function.
        Sys.Services.AuthenticationService.set_defaultLoginCompletedCallback(this.OnLoginCompleted);
    },

    // This function sets and gets the default
    // logout completed callback function.
    SetDefaultLogoutCompletedCallBack: function()
    {
        // Set the default callback function.
        Sys.Services.AuthenticationService.set_defaultLogoutCompletedCallback(this.OnLogoutCompleted);
    },

    // This function sets and gets the default
    // failed callback function.
    SetDefaultFailedCallBack: function()
    {
        // Set the default callback function.
        Sys.Services.AuthenticationService.set_defaultFailedCallback(this.OnFailed);
    },

    // This function calls the login method of the
    // authentication service to verify 
    // the credentials entered by the user.
    // If the credentials are authenticated, the
    // authentication service issues a forms 
    // authentication cookie. 
    OnClickLogin: function()
    {   
        // Set the default callback functions.
        this.SetDefaultLoginCompletedCallBack();
        this.SetDefaultLogoutCompletedCallBack();
        this.SetDefaultFailedCallBack();

        // Call the authetication service to authenticate
        // the credentials entered by the user.
        Sys.Services.AuthenticationService.login(this.username.value, 
            this.password.value, false,null,null,null,null,"User Context");
    },

    // This function calls the logout method of the
    // authentication service to clear the forms 
    // authentication cookie.
    OnClickLogout: function() 
    {  
       // Clear the forms authentication cookie. 
       Sys.Services.AuthenticationService.logout(null, 
            null, null, null);
    } ,

    // This is the callback function called 
    // if the authentication fails.      
    OnFailed: function(error, userContext, methodName)
    {      
        var self = Auth;
              
        // Display feedback message.
        self.DisplayInformation("error:message = " + 
            error.get_message());
        self.DisplayInformation("error:timedOut = " + 
            error.get_timedOut());
        self.DisplayInformation("error:statusCode = " + 
            error.get_statusCode());            
    },


    // The callback function called 
    // if the authentication completed successfully.
    OnLoginCompleted: function(validCredentials, userContext, methodName)
    {
        // Reload the page.
        location.reload();
    },

    // This is the callback function called 
    // if the user logged out successfully.
    OnLogoutCompleted: function(result) 
    {
        // Display login fields.
        usernameEntry.style.visibility = "visible";
        passwordEntry.style.visibility = "visible";
        textNotLoggedIn.style.visibility = "visible";  
        buttonLogin.style.visibility = "visible";

        // Hide logout fields.
        buttonLogout.style.visibility = "hidden";
        textLoggedIn.style.visibility = "hidden";
    },               

    // This function displays feedback
    // information for the user.    
    DisplayInformation: function(text)
    {
        alert(text);
//        document.getElementById("FeedBackID").innerHTML = 
//            "<br/>" + text;

        // Display authentication service information.


        var userLoggedIn =
            Sys.Services.AuthenticationService.get_isLoggedIn();
        
        var authServiceTimeout =       
            Sys.Services.AuthenticationService.get_timeout();

        var userLoggedInfo = 
            "<br/> User logged in:                 " + userLoggedIn;

        var timeOutInfo = 
            "<br/> Authentication service timeout: " + authServiceTimeout;

//        document.getElementById("FeedBackID").innerHTML = 
//            userLoggedInfo + timeOutInfo; 
        alert(userLoggedInfo + timeOutInfo);
    }
};*/
/*--------------------------------------------------------------------------*/
/*
if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
*/
String.format = function() {
    if( arguments.length == 0 )
        return null;
        
    var str = arguments[0]; 
    
    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i-1) + '\\}','gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}