// JavaScript Document
Array.prototype.in_array = function (element) {
    for (var values in this){
        if (this[values] == element) 
            return true;
    }
    return false;
};

String.prototype.strip_tags = function(){ 
    return this.replace(/<[^>]+>/g, ' ');
}
/**
 * Some functions for manage the knipsels
 *  
 * @author: lwielink<lwielink@refdag.nl>
 * @date: 12/12/2008
 */
     
var Knipsels = {

    // cookie name
    cookieName          : 'knipsels',
    // cookie lifetime in days
    cookieLifeTime      : 365,
    // max knipsel items
    maxKnipselItems     : 10,
    // target list id
    targetListId        : 'knipsel_container',
    // active articleId
    activeArticleId     : null,
    // ajax call url
    ajaxCallUrl         : '/ajax_server.php?act=article&id=',
    // list id if no knipsels added
    noKnipselsListId    : 'no_knipsels',
    // add knipsel button/link ID
    addKnipselLinkId    : 'ad_knipsel',
    // warning by reaching the knipsel limit
    maxKnipselsWarning  : 'U kunt max. 10 knipsels toevoegen.',
    // warning by no Knipsels
    emptyKnipselsWarning: 'U heeft nog geen knipsels toegevoegd',
    // hightLight color by existing knipsel
    highLightColor      : 'red',
    // delete icon url
    delIconUrl          : '/img/icon_delete.gif',
    
        
    /**
     * add a knipsel
     * 
     * @param int articleId
     * @return boolean
     */                        
    addKnipsel      : function(articleId)
    {
        var toWriteKnipsels = articleId;
        if (currentKnipsels = this.getKnipsels()) {
            currentKnipselsSplit = currentKnipsels.split(/,/);
            if (currentKnipselsSplit.in_array(articleId))  /* article already existing. Highlight existing item */
                return $$('li#' + articleId)[0].firstChild.style.color = this.highLightColor;
            if (currentKnipselsSplit.length >= this.maxKnipselItems) { /* max items reached */
                try {
                    if ($(this.targetListId).firstChild.id != 'max_items_reacht') {
                        var newListItem = document.createElement('li');
                        newListItem.id = 'max_items_reacht';
                        newListItem.appendChild(document.createTextNode(this.maxKnipselsWarning));
                        newListItem.style.color = 'red'
                        newListItem.style.listStyle = 'none';
                        return $(this.targetListId).insertBefore(newListItem, $(this.targetListId).firstChild);
                    }
                } catch (error) {
                    alert($(this.targetListId).firstChild.nodeType);
                }
                return;
            } 
            currentKnipselsSplit.push(articleId);
            toWriteKnipsels = currentKnipselsSplit.join(',');
        }
        if (location.search == '?marc') {
            document.cookie = this.cookieName + "=" + toWriteKnipsels + this.getExpires() + "; path=/; domain=www.refdag.nl";
        } else {
            document.cookie = this.cookieName + "=" + toWriteKnipsels + this.getExpires() + "; path=/; domain=.refdag.nl";
        }
        // show article name in right frame
        return this.showNameOfArticle(articleId); 
    },
    
    /**
     * delete a knipsel on the base of the given article id
     * 
     * @param int articleId
     * @return boolean
     */
    delKnipsel      : function(articleId)
    {
        if (currentKnipsels = this.getKnipsels()) {
            currentKnipselsSplit = currentKnipsels.split(/,/);
            if (currentKnipselsSplit.in_array(articleId)) {
                newKnipsels = new Array();
                for (var i=0; i < currentKnipselsSplit.length; i++) {
                    if (currentKnipselsSplit[i] != articleId) {
                        newKnipsels.push(currentKnipselsSplit[i]);
                    }
                }
                var toWriteKnipsels = newKnipsels.join(',');
                if (location.search == '?marc') {
                    document.cookie = this.cookieName + "=" + toWriteKnipsels + this.getExpires() + "; path=/; domain=www.refdag.nl";
                } else {
                    document.cookie = this.cookieName + "=" + toWriteKnipsels + this.getExpires() + "; path=/; domain=.refdag.nl";
                }
                // remove accessory list item. $$ returns a array so we get the first one
                $$('li#' + articleId)[0].remove();
                if ($(this.targetListId).immediateDescendants() < 1) {
                    var newListItem = document.createElement('li');
                    newListItem.id = 'no_knipsels';
                    newListItem.appendChild(document.createTextNode(this.emptyKnipselsWarning));
                    return $(this.targetListId).appendChild(newListItem);
                }
            }
        }
    },
    
    
    /**
     * get all knipsels
     *      
     * @return String   
     */         
    getKnipsels     : function()
    {
        var nameEQ = this.cookieName + "=";
    	var ca = document.cookie.split(';');
    	for(var i=0; i < ca.length; i++) {
    		var c = ca[i];
    		while (c.charAt(0)==' ') 
                c = c.substring(1,c.length);
    		if (c.indexOf(nameEQ) == 0) { 
                return unescape(c.substring(nameEQ.length,c.length));
            }
    	}
    	return null;
    },
    
                             
    
    /**
     * Fix knipsels if there are cookies with different domains
     * 
     * @return boolean
     */
    fixKnipsels     : function()
    {
        // walk through all cookies
        var diffDomainCount = 0;
        var mergedIds = new Array();
        var nameEQ = this.cookieName + "=";
    	var ca = document.cookie.split(';');
    	for(var i=0; i < ca.length; i++) {
    		var c = ca[i];
    		while (c.charAt(0)==' ') 
                c = c.substring(1,c.length);
    		if (c.indexOf(nameEQ) == 0) { 
    		    diffDomainCount++;
                var cookieVal = unescape(c.substring(nameEQ.length,c.length));
                var cookieIds = cookieVal.split(',');
                for (var j = 0; j < cookieIds.length; j++)
                    if (!mergedIds.in_array(cookieIds[j]))
                        mergedIds.push(cookieIds[j]);
            }
    	}
    	// try to unset some cookies
    	document.cookie = this.cookieName + "=" + this.getExpires(true) + "; path=/; domain=www.refdag.nl";
    	document.cookie = this.cookieName + "=" + this.getExpires(true) + "; path=/; domain=.www.refdag.nl";
    	document.cookie = this.cookieName + "=" + this.getExpires(true) + "; path=/; domain=refdag.nl";
    	document.cookie = this.cookieName + "=" + this.getExpires(true) + "; path=/; domain=.refdag.nl";
    	// write new cookie
    	var toWriteKnipsels = mergedIds.join(',');
    	document.cookie = this.cookieName + "=" + toWriteKnipsels + this.getExpires() + "; path=/; domain=.refdag.nl";
    },

    /**
     * define expire date and set the expire string in document.cookie format
     *
     * @param bool dateInPast
     * @return String
     */                   
    getExpires      : function(dateInPast)
    {
        var date = new Date();
        if (dateInPast) {
		    date.setTime(date.getTime()-(this.cookieLifeTime*24*60*60*1000));
	    } else {
		    date.setTime(date.getTime()+(this.cookieLifeTime*24*60*60*1000));
	    }
		return "; expires="+date.toGMTString();
    },
    
    
    /**
     * Show the name of the specified article
     * 
     * @param int articleId
     * @return boolean
     */
     showNameOfArticle  : function(articleId)
     {
        if ((!articleId) || articleId == 0)
            return false;
        try {
            // test if contentElement exists. If the not exist we reveive a exception
            tempId = $(Knipsels.targetListId).id;
            // setting up a AJAX call
            new Ajax.Request(this.ajaxCallUrl + articleId, {
                method: 'get',
                onSuccess: function(transport, json) {
                    if (transport.responseText) {
                        // try to remove the first list information id
                        try {
                            $(Knipsels.noKnipselsListId).remove();
                        } catch (error){}
                        var article = eval('(' + transport.responseText + ')');
                        // list item
                        var newListItem = document.createElement('li');
                        newListItem.id = articleId;
                        
                        var cleanedHeader = escape(article.kop.replace(/<[^>]*>/g, '').replace(/(&(#\d+|\w+);|[^\w ])+/g, '_'));
                        var linkElement = document.createElement('a');
                        linkElement.href = '/artikel/' + articleId + '/' + cleanedHeader + '.html';
                        linkElement.innerHTML = article.kop;
                        newListItem.appendChild(linkElement);
                        // link
                        var link = document.createElement('a');
                        link.href = '#';
                        link.onclick = function() {
                            if (confirm('Weet u zeker dat u dit knipsel wilt verwijderen?'))
                                Knipsels.delKnipsel(this.parentNode.id);
                            return false;
                        }
                        // delete img
                        var delImg = document.createElement('img');
                        delImg.src = Knipsels.delIconUrl;
                        delImg.title = 'Knipsel verwijderen';
                        delImg.alt = 'Knipsel verwijderen';
                        link.appendChild(delImg);
                        newListItem.appendChild(link);
                        $(Knipsels.targetListId).appendChild(newListItem);
                    }
                },
                onFailure : function(
                ) {} 
            });
        } catch (error) {
            location.href = location.href;
        }
     }               
};
