/**
 * Copyright (C) 2007-2008 Achmea.
 */
var Achmea = {
    version: '1.0.0'
}; 

/// Provides the code for a collapse section
Achmea.Dom = {
    $: function() 
    {
        /// Create a stack of elements, based on the arguments
        var elements = new Array();
	
	    for (var i = 0, n = arguments.length; i < n; i++) 
	    {
		    var element = arguments[i];
		    
		    if (typeof element == 'string')
		    {
			    element = document.getElementById(element);
		    }
		    if (arguments.length == 1)
		    {
			    return element;
		    }
		    elements.push(element);
	    }
	    return elements;
    },
    hide: function(element)
    {
        /// Hide the collapse section (onclick)
        if (element)
        {
            if (typeof element == 'string')
            {
                var obj = Achmea.Dom.$(element);
                if (obj)
                    obj.style.display = 'none';
            }
            else
            {
                element.style.display = 'none';
            }
        }
    },
    show: function(element)
    {
        /// Show the collapse section (onclick)
        if (element)
        {
            if (typeof element == 'string')
            {
                var obj = Achmea.Dom.$(element);
                if (obj)
                    obj.style.display = 'block';
            }
            else
            {
                element.style.display = 'block';
            }
        }
    }
};

/// Adds a functino to the window load event
Achmea.Event = {
    addLoadEvent: function(f) 
    {
	    var oldonload = window.onload;
	
	    if (typeof window.onload != 'function') 
	    {
		    window.onload = f;
	    }
	    else 
	    {
		    window.onload = function() 
		    {
			    oldonload();
			    f();
		    }
	    }
    }
};

/// Provides trim functions for the rest of the source
Achmea.Util = {
    ltrim: function(str)
    {
        return str.replace(/^\s*/, '');
    },
    rtrim: function(str)
    {
        return str.replace(/\s*$/, '');
    }
};

/// Provides cookies for the enquete
Achmea.Cookie = {
    hasCookie: function(name)
    {
        /// Checks if the cookie exists on the client
        if (document.cookie)
        {
            var expression = '(?:; )?' + name + '=([^;]*);?';
            var regex      = new RegExp(expression);
            
            return regex.test(document.cookie);
        }
        return false;
    },
    bakeCookie: function(name, value, expires, path, domain, secure)
    {
        /// Sets the cookie on the client
        var cookie = name + '=' + encodeURIComponent(value);

        if (expires)
        {
            cookie += '; expires=' + expires.toGMTString();
        }
        if (path)
        {
            cookie += '; path=' + path;
        }
        if (domain)
        {
            cookie += '; domain=' + domain;
        }
        if (secure)
        {
            cookie += '; secure'; 
        }
        document.cookie = cookie;
    }
};

/// Provides URI functions for the enquete
Achmea.URI = {
    host: function(url)
    {
        /// Gets the host from a url
        var regex = /\:\/\/([A-Za-z0-9_\.\:]+)/i;
        var match = regex.exec(url);
        
        return match ? match[1] : '';
    },
    protocol: function(url)
    {
        /// Gets the protocol from a url
        // Examples: http:// | https:// | ftp:// | file://
        var regex = /^(.*)\:\/\/.*/i;
        var match = regex.exec(url);
        
        return match ? match[1] : '';
    },
    path: function(url)
    {
        /// Gets the path from a url
        var regex = /[A-Za-z](\/.*\/)[A-Za-z0-9]*/i;
        var match = regex.exec(url);
        
        return match ? match[1] : '';
    },
    extension: function(url)
    {       
        /// Gets the querystring from a url
        var x = 3 + Achmea.URI.protocol(url).length + Achmea.URI.host(url).length + Achmea.URI.path(url).length;
        var y = -1 == url.lastIndexOf('?') ? url.length : url.lastIndexOf('?');
        
        url = url.substring(x, y);
        
        var regex = /\.([A-Za-z0-9_]+)$/i;
        var match = regex.exec(url);
        
        return match ? match[1] : '';
        
    },
    isFileDownload: function(url)
    {
        /// Checks if this is a download based on the file extension
        var ext = Achmea.URI.extension(url);
        
        if (ext && 0 < ext.length)
        {
            return !/htm|asp|xml/i.test(ext);
        }
        return false;
    }
};

/// Provides client code for the survey control
Achmea.Enquete = {
    initEnqueteControl: function(url, width, height, end)
    {
        /// Checks if the survey was already triggered. If not opens the survey
        if (!Achmea.Cookie.hasCookie('AchmeaEnquete'))
        {
            var links = document.getElementsByTagName('a');
            
            for (var i = 0; i < links.length; i++)
            {
                links[i].onclick = function()
                {
                    if (Achmea.URI.protocol(this.href) != '' && location.host != Achmea.URI.host(this.href))
                    {
                        // Opens the survey
                        window.open(url, 'Achmea', 'width=' + width + ', height=' + height + ', toolbar=no, address=no, status=no');
                        
                        // Stores a cookie on the local HDD
                        Achmea.Cookie.bakeCookie('AchmeaEnquete', 'EnqueteTool', new Date( Date.parse(end) ), null, null, false);
                    }
                };
            }
        }
    }
};

/// Provides SharePoint specific functionality
Achmea.SharePoint = {
    disableRTEToolbarButton: function(id, mnemonic)
    {
        var button = RTE_TB_GetToolBarButton(id, mnemonic);
        if (button)
            button.disabled = true;
    },
    insertOrChangeHyperLink: function(strBaseElementID)
    {
        /// Provides the custom Url picker dialog and the functionality to parse existing and generate
        /// new url code
        var editor = RTE_GetEditorDocument(strBaseElementID);
	    if (editor)
	    {
			var bInserting=false;
			var innerLinkHTML=null;
			var elemToReplace=null;

	        var elemLink=RTE_GetNearestContainingElementOfType(strBaseElementID, "A");
	        if( !elemLink )
	        {
	            // This is a new link
		        bInserting=true;
		        elemLink=editor.createElement("A");
		        if (elemLink==null) {    return; }
		        var selectionType=RTE_GetCurrentSelectionType(strBaseElementID);
		        if (selectionType==null) {return;}
		        if (selectionType=="Control")
		        {
			        elemToReplace=RTE_GetCurrentElement(strBaseElementID);
			        if (elemToReplace==null) {return;}
		        }
	        }
	        else
	        {
	            // This is an existing link
		        innerLinkHTML=elemLink.innerHTML;
	        }
	        var html = elemLink.outerHTML;

    		var buffer    = new Array();
    		buffer.push('/_layouts/AlteredAssetEditHyperLink.aspx');
    		
    		if (AchmeaHyperLink.isUrl(html))
    		{	        
		        var hprlnk = AchmeaHyperLink.parse(html);
                var dialog = AchmeaHyperLink.isDialogUrl(html) ? '1' : '0';
                               
		        buffer.push('?url='      + hprlnk.getUrl());
		        buffer.push('&bookmark=' + hprlnk.getBookMark());
		        buffer.push('&tooltip='  + hprlnk.getTitle());
		        buffer.push('&dialog='   + dialog);
		        buffer.push('&features=' + hprlnk.getType());
	        }
        
            // Display the dialog
	        var response = window.showModalDialog(buffer.join(''), null, 'dialogHeight: 585px; dialogWidth: 575px; status: no;');
            if (response) 
            {
                // Remove [ ] characters
                response = response.substring(1, response.length - 1);
                                               
                // Seperate response in Array of strings using the ; sign
                var xs  = response.split(';');

                // [HREF, TITLE, TYPE, BOOKMARK]
                var achmeaLink = new AchmeaHyperLink(
                        xs[0], 
                        xs[1], 
                        xs[2], 
                        "", 
                        xs[0],
                        xs[3]);

                elemLink.setAttribute("type", achmeaLink.toTypeAttrVal(), 0);

				var title = achmeaLink.toTitleAttrVal();
				if (title && title != '')
				{
                    elemLink.setAttribute("title", title, 0);
				}

			    if (elemToReplace !=null)
			    {
				    elemToReplace.applyElement(elemLink);
				    return;
			    }
			    else if (bInserting)
			    {
				    var selection=editor.selection;
				    if (selection !=null)
				    {
					    var textRange=selection.createRange();
					    if (textRange !=null)
					    {
						    var text=textRange.text;
						    if (text && text !="" && !text.match(/^\s+$/))
						    {
							    textRange.execCommand("Unlink");
							    elemLink.innerHTML=textRange.htmlText;
						    }
						    textRange.pasteHTML(elemLink.outerHTML);
					    }
				    }
			    }
			}                       
	    }
	    RTE_RestoreSelection(strBaseElementID);
	    
	    return true;
    }
};

/// Constructor for a hyperlink
var AchmeaHyperLink = function(href, title, type, text, url, bookmark) 
{ 
    this.setHref(href);
    this.setTitle(title);
    this.setType(type);
    this.setText(text);
    this.setUrl(url);
    this.setBookMark(bookmark);
}

/// Checks a url to see if it is a dialog link
AchmeaHyperLink.isDialogUrl = function(input)
{
    if (input && input.length > 0)
    {
        return /type=\[[^\|]+\|[^\]]+\]/i.test(input);
    }
    return false;
}

/// Checks a string to see if it is a url
AchmeaHyperLink.isUrl = function(input)
{
    if (input && input.length > 0)
    {
        return /<a.*/i.test(
            Achmea.Util.ltrim(
                Achmea.Util.rtrim(input)));
    }
    return false;
}

/// Checks a string to see if it is a SiteStat url (legacy)
AchmeaHyperLink.isSiteStatUrl = function(input)
{
    if (input && input.length > 0)
    {
        return /nl\.sitestat\.com/i.test(
            Achmea.Util.ltrim(
                Achmea.Util.rtrim(input)));
    }
    return false;
}

/// Parses a link to be used in a dialog
/// 
/// Input:
///     <a title="" [type="[url[#bookmark]|options]"] [href=""]></a> 
///
AchmeaHyperLink.parse = function(input)
{
    if (!input || input.length <= 0)
    {
        return;
    }
    
    // Create two Arrays one for storing reg. expressions; and one for storing their result
    var xs = new Array();
    var ys = new Array();
    
    // Add Regular Expressions [ HREF, TITLE, TYPE, TEXT, BOOKMARK ]
    xs.push(/type=\[([^\|]+)\|[^\]]*\]/i);
    xs.push(/title=\"{0,1}(.*)\"{0,1}\s+type=/i); 
    xs.push(/type=\[[^\|]+\|([^\]]*)\]/i);
    xs.push(/\s*>(.*)<\/a>/i);
    // xs.push(/s\?(.*)&(?:amp;)*ns_type/i);
    xs.push(/#([^\|]+)\|/i);
    
    for (var i = 0, n = xs.length; i < n; i++)
    {
        var regex = xs[i];
        var match = regex.exec(input);
        
        ys.push( (match ? match[1] : '') );
    }
    return new AchmeaHyperLink(ys[0], ys[1], ys[2], ys[3], ys[0], ys[4]);
}

/// Provides the prototype for a hyperlink
AchmeaHyperLink.prototype = {
    getHref: function()
    {
        return this._href;
    },
    setHref: function(newHref)
    {
        this._href = Achmea.Util.ltrim(Achmea.Util.rtrim(newHref));
    },
    getTitle: function()
    {
        return this._title;
    },
    setTitle: function(newTitle)
    {
        var str = Achmea.Util.ltrim(Achmea.Util.rtrim(newTitle));
        var n   = str.length - 1;
        
        if ('"' == str.charAt(n))
        {
            this._title = str.substring(0, n);
        }
        else
        {
            this._title = str;
        }
    },
    getType: function()
    {
        return this._type;
    },
    setBookMark: function(newBookMark)
    {
        this._bookMark = newBookMark;
    },
    getBookMark: function()
    {
        return this._bookMark;
    },
    setType: function(newType)
    {
        this._type = newType;
    },
    getText: function()
    {
        return this._text;
    },
    setText: function(newText)
    {
        this._text = newText;
    },
    getUrl: function()
    {
        return this._url;
    },
    setUrl: function(newUrl)
    {
        var regex = /ns_url=\[(.*)\]/i;
        var match = regex.exec(newUrl);
        
        if (match)
        {
            // Remove SiteState
            this._url = match[1];
        }
        else
        {
            // Remove Bookmark
            regex = /([^#]+)#/i;
            match = regex.exec(newUrl);
            
            this._url = (match) ? match[1] : newUrl;
        }
    },
    toHtml: function()
    {
        /// Generates the html version of the url
        var buffer = new Array();
        buffer.push('<a');
        
        if (this._title && this._title.length > 0)
        {
            buffer.push(' title="');
            buffer.push(this._title);
            buffer.push('"');
        }

        buffer.push(' type=[');
        buffer.push(this._href);
        buffer.push( (this._bookMark && 0 < this._bookMark.length) ? '#' + this._bookMark : '' );
        buffer.push('|');
        buffer.push(this._type);
        buffer.push(']>');
        buffer.push(this._text);
        buffer.push('</a>');
        
        return buffer.join('');
    },
	toTitleAttrVal: function()
    {
        var buffer = new Array();
        
        if (this._title && this._title.length > 0)
        {
			return this._title;
        }
		else
		{
			return "";
		}
    },
	toTypeAttrVal: function()
    {
        /// Generates the persitant version of the link
        var buffer = new Array();
        
        buffer.push('[');
        buffer.push(this._href);
        buffer.push( (this._bookMark && 0 < this._bookMark.length) ? '#' + this._bookMark : '' );
        buffer.push('|');
        buffer.push(this._type);
        buffer.push(']');
        
        return buffer.join('');
    }

};