Array.prototype.in_array = function (element) {
    for (var values in this) {
        if (this[values] == element)
            return true;
    }
    return false;
};

function countAndTruncate(obj, maxChars, counterObj)
{
	if (obj.value.length >= maxChars) {
		jQuery(counterObj).text(0);
		obj.value = obj.value.substring(0, maxChars);
		return false;
	}
	jQuery(counterObj).text(maxChars-obj.value.length);
}

jQuery.fn.mouseOverOutAction = function(options) {
	if (!options.overClassName) {
        if (window.console && window.console.log)
        	window.console.log('jQuery mouseOverOutAction: invalid over classname');
        return;
	}
	// iterate and set the action for each matched element
    return this.each(function() {
    	jQuery(this).mouseover(function() {
			jQuery(this).addClass(options.overClassName);
		});
		jQuery(this).mouseout(function() {
			jQuery(this).removeClass(options.overClassName);
		});
    });
}

function initFlowPlayer(videoTargetId, videoFile)
{
	flowplayer(videoTargetId, "/tools/common/flowplayer3.1.5/flowplayer.commercial-3.1.5.swf", 
	{
		key: '#@489a0cc767ac582d915', 
		clip: {
			autoBuffering: true,
			autoPlay: true,
            url: videoFile,
			provider: 'lighttpd' 
			
        },
		plugins: { 
            controls: { 
                url: '/tools/common/flowplayer3.1.5/flowplayer.controls-3.1.5.swf', 
          
                bottom:0, 
                height:24,  
                
         		progressColor:'#174591',
				bufferColor:'#000000',
				sliderColor:'#EEEEEE',
                fontColor: '#ffffff', 
               	sliderGradient:'high', 
                autoHide: 'never', 
          
                play:true, 
                volume:false, 
                mute:true, 
                time:true, 
                stop:true, 
                playlist:false, 
                fullscreen:true, 
          
                scrubber: true,
				pause: 'Afspelen'
            },
			lighttpd: { 
                url: '/tools/common/flowplayer3.1.5/flowplayer.pseudostreaming-3.1.3.swf' 
            } 
        },
		play: {
			replayLabel : 'Afspelen',
			url: '/img/refdag/video_rectangle_large.gif',
			width: 44,
			height: 45
			
		},
		logo: { 
            url: '/img/refdag/refdag_logo_small.png', 
            fullscreenOnly: true, 
            linkUrl : 'http://www.refdag.nl',
            opacity: 0.4,
            displayTime: 2000
        } 
	});
}

var Multimedia = {


    play    : function(title, videoContentIdString, videoFile, videoPlayerWrapper)
    {
        if (title != "")
            jQuery('div.multimedia_element_wrapper p.title').text(title); 
        jQuery('div.multimedia_element_wrapper div.description').hide(); 
        jQuery('div.multimedia_element_wrapper div#article_video_' + videoContentIdString + '') .show(); 
        initFlowPlayer(videoPlayerWrapper, videoFile); 
        return false;
    }
}


var Knipsels = {

    // cookie name
    cookieName          : 'knipsels',
    // cookie lifetime in days
    cookieLifeTime      : 365,
    // max knipsel items
    maxKnipselItems     : 30,
    // target list id
    targetListId        : 'knipsel_container',
    // active articleId
    activeArticleId     : null,
    // 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. 30 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',
    // top level domain
    domain				: '.refdag.nl',
    
        
    /**
     * add a knipsel
     * 
     * @param int articleId
     * @return boolean
     */                        
    addKnipsel      : function(articleId, articleName, articleLink)
    {
        var toWriteKnipsels = articleId;
        if (currentKnipsels = this.getKnipsels()) {
            currentKnipselsSplit = currentKnipsels.split(/~/);
            if (currentKnipselsSplit.in_array(articleId))  /* article already existing. Highlight existing item */
                return false;
            if (currentKnipselsSplit.length >= this.maxKnipselItems) { /* max items reached */
                try {
                    if (jQuery('#' + this.targetListId + ' > li:first').hasClass('max_items_reached').size() <= 0)
                       jQuery('#' + this.targetListId).prepend('<li class="max_items_reached" style="color:red; list-style:none;">' + this.maxKnipselsWarning + '</li>');
                } catch (error) {
                }
                return;
            } 
            currentKnipselsSplit.push(articleId);
            toWriteKnipsels = currentKnipselsSplit.join('~');
        } else {
        	try{
        		jQuery('#no_knipsels').remove();
        	} catch (error) {
        	}
        }
        document.cookie = this.cookieName + "=" + toWriteKnipsels + this.getExpires() + "; path=/;domain=" + this.domain;
        // show article name in right frame
        return this.showNameOfArticle(articleId, articleName, articleLink); 
    },
    
    /**
     * 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(new String(currentKnipselsSplit[i]));
                    }
                }
                var toWriteKnipsels = newKnipsels.join('~');
                if (toWriteKnipsels != '') {
                	document.cookie = this.cookieName + "=" + toWriteKnipsels + this.getExpires() + "; path=/;domain=" + this.domain;
                } else {
                	// no knipsels existing. So remove the cookie
                	this.clearCookie();
                }
                jQuery('#' + this.targetListId + ' li[id="' + articleId + '"]').remove();
                if (jQuery('#' + this.targetListId + ' > li').size() <= 0)
                    jQuery('#' + this.targetListId).prepend('<li class="no_knipsels"">' + this.emptyKnipselsWarning + '</li>');
            }
        }
    },
    
    
    /**
     * 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;
    },
    
    /**
     * clear cookie
     *      
     * @return String   
     */         
    clearCookie     : function()
    {
        document.cookie = this.cookieName+"=;expires="+new Date().toGMTString()+";path=/;domain=" + this.domain;
    },
    
                             
    /**
     * 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, articleName, articleLink)
     {
        jQuery('.knipsel_element_wrapper').show();
        if ((!articleId) || articleId == 0)
            return false;
        try {
            var html = '';
            html += '<li id="' + articleId + '">';
            html += '<a href="' + articleLink + '">' + articleName + '</a> ';
            html += '<a href="#" onclick="if (confirm(\'Weet u zeker dat u dit knipsel wilt verwijderen?\')){ Knipsels.delKnipsel(' + articleId + '); } return false;"><img src="' + Knipsels.delIconUrl + '" title="Knipsel verwijderen" alt="Knipsel verwijderen" /></a>';
            html += '</li>';
            jQuery('#' + Knipsels.targetListId).append(html);
        } catch (error) {
        }
     }
};


(function($) {
	jQuery.fn.articleSlideshow = function(options) {
    	var settings = {
			'slideShowTimeout'	: 5000,
        	'currentArray' 		: 0
		};
		// overwrite the default options
		if ( options ) { 
            jQuery.extend( settings, options );
       	}
		
		var currentIndex = 0;
		var lastTimeOut = null;
		var navImgs = {
			'first' 	: 'Eerste foto',
			'previous' 	: 'Volgende foto',
			'play' 		: 'Start slideshow',
			'pause' 	: 'Stop slideshow',
			'next' 		: 'Volgende foto',
			'last' 		: 'Laatste foto'
		};	
        $(this).fancybox({
        	'titleShow'		: true,
    		'showNavArrows' : false,
    		'titlePosition' : 'inside',
        	'transitionIn'	: 'elastic',
        	'transitionOut'	: 'elastic',
    		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
    			if(currentArray.length == 1) {
    				return title;
    			} else {
					var titleText = '<div style="width: 77%; padding-right: 1%; float: left;">'+title+'</div>';
    				var navWrapper = '<div style="float: right;"><table cellpadding="0" cellspacing="0" class="nav_wrapper"><tr>';
        		    for (element in navImgs) {
        				var hideButton = false;
        				if (element == 'pause' || (currentIndex == 0 && (element == 'first' || element == 'previous')))
        					hideButton = true;
        				if (currentIndex+1 == currentArray.length && (element == 'next' || element == 'last'))
        					hideButton = true;
						if (lastTimeOut && (element == 'pause'))
							hideButton = false;
						
        				var img = '<a href="#" id="nav_'+element+'"><img title="'+navImgs[element]+'" src="/img/common/slideshow_buttons/photoslide_nav_' + element + ((hideButton == true) ? "_inactive" : "") + '.gif" /></a>';
        		        var item = '<td>'+img+'</td>';                
        		        navWrapper += item;
                    };
        			navWrapper += '</tr></table></div><div style="clear:both;"></div>';
        			return titleText + navWrapper;
    			};
    		},
    		onComplete	: function() {
    			$('a#nav_first').click(function() {
					currentIndex = 0;
    				return jQuery.fancybox.pos(0);
    			});
    			$('a#nav_previous').click(function() {
					if (currentIndex > 0)
						currentIndex--;
					return jQuery.fancybox.prev();
    			});
    			$('a#nav_play').click(function() {
					$('a#nav_play > img').attr('src','/img/common/slideshow_buttons/photoslide_nav_play_inactive.gif');
            		$('a#nav_pause > img').attr('src','/img/common/slideshow_buttons/photoslide_nav_pause.gif');
					if (currentIndex < settings.currentArray) {
    					lastTimeOut = setTimeout('jQuery(\'a#nav_next\').click();', settings.slideShowTimeout);
					} else {
						lastTimeOut = setTimeout('jQuery(\'a#nav_first\').click();', settings.slideShowTimeout);
					};
					return false;
    			});
    			$('a#nav_pause').click(function() {
    				if (lastTimeOut) {
                		clearTimeout(lastTimeOut);
						lastTimeOut = null;
					};
    				$('a#nav_play > img').attr('src','/img/common/slideshow_buttons/photoslide_nav_play.gif');
            		$('a#nav_pause > img').attr('src','/img/common/slideshow_buttons/photoslide_nav_pause_inactive.gif');
					return false;
    			});
    			$('a#nav_next').click(function() {
					if (currentIndex < settings.currentArray)
						currentIndex++;
    				return jQuery.fancybox.next();
    			});
    			$('a#nav_last').click(function() {
					currentIndex = settings.currentArray;
					return jQuery.fancybox.pos(currentIndex);	
    			}); 
				if (lastTimeOut) {
					if (currentIndex < settings.currentArray) {
						$('a#nav_play').click();
					} else {
						lastTimeOut = setTimeout('jQuery(\'a#nav_first\').click();', settings.slideShowTimeout);
					}
				}
    		},
			onClosed	: function() {
				if (lastTimeOut) {
            		clearTimeout(lastTimeOut);
					lastTimeOut = null;
				};	
				jQuery.fancybox.close();
			}
        });
	}
})(jQuery);

jQuery(document).ready(function() {
	jQuery('a.fancybox').each(function() {
		var myObj = this;
		if (jQuery(this).attr('rel').replace(/^([^\|]+)\|([^\|]+)\|([^\|]+)$/g, function(wholeMatch, boxType, boxHeight, boxWidth) {
			jQuery(myObj).fancybox({
				'autoDimensions'	: false,
				'width'				: parseInt(boxWidth),
        		'height'			: parseInt(boxHeight),
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: boxType,
				'href' 				: jQuery(myObj).attr('href')
			});
		}));
	});
});

