// +------------------------------------------------------------------+
// | JavaScript version 1.0                                           |
// +------------------------------------------------------------------+
// | general.js – Some standard functions used in the CMS cleint      |
// |              side. Script is loaded in template by parser.       |
// +------------------------------------------------------------------+
// | Copyright (c) 2008 MultiMove                                     |
// +------------------------------------------------------------------+
// | Authors: S.F.Beck <sander@multimove.nl>     					  |
// +------------------------------------------------------------------+

/**
 * The load function
 * 
 * @return void
 */
function doLoad(){}

$(document).ready(
	function(){
		/*Enable rel="external" as a replacement for target="_blank" attributes*/
		$("a[rel*='external']").attr('target','_blank'); 
	}		
);

/**
 * Make pop-up windows
 * 
 * @return void
 */
function popup( url, width, height )
{
	var iLeft = (screen.width - width) / 2 ;
	var iTop  = (screen.height - height) / 2 ;

	var sOptions = "resizable=yes,dependent=yes,scrollbars=yes," ;
	sOptions += ",width=" + width ;
	sOptions += ",height=" + height ;
	sOptions += ",left=" + iLeft ;
	sOptions += ",top=" + iTop ;

	window.open( url, "FCKBrowseWindow", sOptions ) ;
}


/**
 * Clear textfields preset text and turn to black
 * 
 * @return void
 */
function clearText(thefield, onfocus)
{
	if(onfocus && thefield.value == thefield.defaultValue)
	{
		thefield.value = '';
		thefield.style.color = '#000000';
	}
	if(!onfocus && thefield.value == '')
	{
		thefield.value = thefield.defaultValue;
		thefield.style.color = '#cccccc';
	}
}


/**
 * Detect the browser
 */
var browserDetect = {
	init: function() {
		this.browser = this.searchString(this.dataBrowser) || 'default';
	},
	searchString: function(data) {
		for(var i = 0; i < data.length; i++) {
			var dataString = navigator.userAgent;
			if (dataString) {
				if(dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
		}
	},
	dataBrowser: [
		{
			subString: 'Chrome',
			identity: 'Chrome'
		},
		{
			subString: 'MSIE',
			identity: 'Explorer'
		},
		{
			subString: 'Firefox',
			identity: 'Firefox'
		},
		{
			subString: 'Safari',
			identity: 'Safari'
		}
	]
}


/**
 *
 */
function popImage(imageURL, imageTitle)
{
	browserDetect.init();
	
	var AutoClose			= true;
	var PositionX			= 0;
	var PositionY			= 0;
	var defaultWidth		= 250;
	var defaultHeight		= 75;
	
	var optFF = 'scrollbars=no,status=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	var optIE = 'scrollbars=no,status=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	var optChrome = 'scrollbars=no,status=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	var optSafari = 'scrollbars=no,status=yes,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	
	switch(browserDetect.browser)
	{
		case 'Explorer': default: var isIE = true; break;
		case 'Firefox': var isFF = true; break;
		case 'Chrome': var isChrome = true; break;
		case 'Safari': var isSafari = true; break;
	}
	
	if(isFF) { imgWin = window.open('about:blank', '', optFF); }
	if(isIE) { imgWin = window.open('about:blank', '', optIE); }
	if(isChrome) { imgWin = window.open('about:blank', '', optChrome); }
	if(isSafari) { imgWin = window.open('about:blank', '', optSafari); }
	
	with(imgWin.document)
	{
		var image = new Image();
			image.onload = function() {
				
				switch(browserDetect.browser)
				{
					case 'Explorer': var width = this.width + 10; var height = this.height + 55; break;
					case 'Firefox': var width = this.width + 16; var height = this.height + 87; break;
					case 'Chrome': var width = this.width + 16; var height = this.height + 64; break;
					case 'Safari': var width = this.width; var height = this.height + 39; break;
				}
				
				if(width < 200) { width = 200; }
				if(height < 200) { height = 200; }
				
				getElementById('loading').style.display = 'none';
				
				getElementById('image').src = this.src;
				getElementById('image').style.width = this.width;
				getElementById('image').style.height = this.height;
				
				imgWin.resizeTo(width, height);
				imgWin.moveTo((screen.availWidth / 2) - (width / 2), (screen.availHeight / 2) - (height / 2));
				imgWin.document.title = imageTitle;
			};
			image.src = imageURL;
		
		writeln('<html><head><title>Loading..</title><style>body{margin: 0px; padding: 0px; font-family: Arial; font-size: 12px; color: #ffffff;}</style>');
		
		writeln('</head>');
		
		if(!AutoClose) writeln('<body bgcolor=000000 scroll="no" onload="resizeImage(); self.focus()">')
		else writeln('<body bgcolor=000000 scroll="no" onload="self.focus()" onblur="self.close()">');
		
		writeln('<div id="loading">Loading..</div>');
		writeln('<img id="image" onclick="window.close();" style="display: block; width: 0px; height: 0px; cursor: pointer;">');
		
		writeln('</body></html>');
		
		close();
	}
}


/**
 *
 */
function popupGalleryImage(galleryTitle, imageBrowserUrl, imageDesc)
{
	var PositionX = 0;
	var PositionY = 0;
	var defaultWidth  = 250;
	var defaultHeight = 250;
	
	if (parseInt(navigator.appVersion.charAt(0))>=4)
	{
		var isNN=(navigator.appName=="Netscape")?1:0;
		var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;
	}
	
	var optNN='scrollbars=no, status=yes, width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	var optIE='scrollbars=no, status=yes, width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY;
	
	if (isNN){imgWin=window.open(imageBrowserUrl,'gallery',optNN);}
	if (isIE){imgWin=window.open(imageBrowserUrl,'gallery',optIE);}
}


/**
 *
 */
function mailinglistXmlhttpPost(url, query)
{
    var xmlHttpReq = false;
    var self = this;
    
    // Mozilla/Safari
    if (window.XMLHttpRequest)
    {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject)
    {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    self.xmlHttpReq.open('POST', url, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function()
    {
      if(self.xmlHttpReq.readyState == 4)
      {
        var type = self.xmlHttpReq.responseText.split('|');
        
        switch(type[0])
        {
          default:
            alert(type[1]);
            break;
          
          case 'succes=2':
            alert(type[1]);
            document.getElementById('mailinglist_unsubscribe').style.display = 'none';
            document.getElementById('mailinglist_content').style.display = 'block';
            break;
          
          case 'succes=1':
            document.getElementById('mailinglist_content').style.display = 'none';
            document.getElementById('mailinglist_succes').style.display = 'block';
            break;
          
          case 'error=3':
          case 'error=2':
            alert(type[1]);
            break;
          
          case 'error=1':
            document.getElementById('mailinglist_content').style.display = 'none';
            document.getElementById('mailinglist_error').style.display = 'block';
            document.getElementById('error_text').innerHTML = type[1];
            break;
        }
      }
    }
    
    self.xmlHttpReq.send(query);
}

/**
 *
 */
function strpos(haystack, needle, offset)
{
    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}

/**
 *
 */
function loadVideo(url, width, height, backcolor, frontcolor, lightcolor)
{
	//Initiate video player
	var so = new SWFObject(BASE_URL+"flash/videoplayer.swf", "videoplayer", width, height, "9");
	so.addParam('allowfullscreen', 'true');
	so.addParam('allowscriptaccess', 'always');
	so.addParam('wmode', 'transparent');
	so.addVariable('flashvars', '&amp;file='+url+'&amp;autostart=true&amp;repeat=true&amp;backcolor='+backcolor+'&amp;frontcolor='+frontcolor+'&amp;lightcolor='+lightcolor);
	so.write("video_player");
}

/**
 *
 */
function initShadowbox(backcolor, frontcolor, lightcolor, text_cancel, text_previous, text_next, text_close, text_of)
{
	try { Shadowbox.init(backcolor+';'+frontcolor+';'+lightcolor+';'+text_cancel+';'+text_previous+';'+text_next+';'+text_close+';'+text_of); }
	catch(e) { alert(e.toString()); }
}

function vote(comment_url, post_id) {
	var name = $('#react_name_' + post_id).val();
	var post = $('#react_post_' + post_id).val();
	var email = $('#react_email_' + post_id).val();
	comment_url += '/user_naam,' + name + '/react_post,' + post;

	if (email == '' && name != '' && post != '') {
		$.ajax({
			url: comment_url,
			success: function(data) {
				if (data == 'false')
					alert('error');
				else if (data == 'timeout')
					alert('You already posted a comment on this item.');
				else {
					var xx = $('#news_content_'+post_id+'_container').outerHeight();
					var y = $('#news_content_'+post_id+'_container').parents('.scrollable').outerHeight();
					
					$('#blog_comments_' + post_id).after(data);
					var count = parseInt($('#blog_count_' + post_id).text()) + 1;
					$('#blog_count_' + post_id).html(count)
					$('#react_name_' + post_id).parents('.reaction_form').hide();
					
					var x = $('#news_content_'+post_id+'_container').outerHeight();
					
					$('#news_content_'+post_id).stop(true).animate({ height: x + 10 }, 250);
					$('#news_content_'+post_id+'_container').parents('.scrollable').stop(true).animate({ height: (y + (x - xx) + 10) }, 250);

//					setTimeout(function(){ $(".notice").fadeOut() }, 5000);

				}
			}
		});
	}
	else if (name == '')
		alert('Please enter a name');
	else if (post == '')
		alert('Please enter a message');
}

function subscribe(mail_url) {
	var f_email = $('#input_email').val();
	var f_name = $('#input_name').val();
	
	mail_url += '/f_email,' + f_email;
	if (checkEmail(f_email) == false)
		alert('Please enter a valid e-mail address');
	else {
		if (f_name == '' && f_email != '' && f_email != 'Join my e-mailing !') {
			$.ajax({
				url: mail_url,
				success: function(data) {
					if (data == 'Yay!')
						alert('Thanx a bunch! We keep you updated from now on.');
					else if (data == 'timeout')
						alert('You are already signed up.');
					else {
						alert('Something went wrong, please try again later.');
					}
					$('#input_email').val('');
				}
			});
		}
		else if (f_email == '' || f_email == 'Join my e-mailing !')
			alert('Please enter an e-mail address');
	}

}


function submit_message(mail_url) {
	var f_email   = $('#contact_email').val();
	var f_name    = $('#contact_name').val();
	var f_fake    = $('#contact_required').val();
	var f_message = $('#contact_message').val();
	
	mail_url += '/sub,3/f_email,' + f_email + '/f_name,' + f_name + '/f_message,' + f_message;
	if (checkEmail(f_email) == false)
		alert('Please enter a valid e-mail address');
	else if (f_name == '')
		alert('Please enter your name');
	else if (f_message == '' || f_message == 'Whats on your mind ...')
		alert('Please enter a message');
	else if (f_fake != '') {
		//Do nothing, this is a bot
	}
	else {
		$.ajax({
			url: mail_url,
			success: function(data) {
				
			}
		});
		alert('Thanx for the heads up!');
		$('#contact_name').val('');
		$('#contact_email').val('');
		$('#contact_message').val('');
	}

}

function checkEmail(email) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	if (!filter.test(email)) 
		return false;
	else
		return true;
}


var scrolling = false;
var active_slider = 1;

function scroll_header(direction) {
	var numItems = $('.slider').length
	var max_width = (numItems -1) * $('.slider').width();

	if (scrolling == false) {
		scrolling = true;
		var current_pos = $('#header_slider_container').position();
		var current_left = current_pos.left
		
		if (direction == 'left') {
			if (current_left >= 0) {
				var new_left = 0 - max_width; 
				active_slider = numItems;
			}
			else {
				var new_left = current_left + 495;
				active_slider = active_slider - 1;
			}
		}
		else {
			// || is nodige vanwege IE die bij laatste item left pos - 1 heeft !!
			if (current_left == (0 - max_width) || (current_left - 1) == (0 - max_width) ) {
				var new_left = 0;
				active_slider = 1;
			}
			else {
				var new_left = current_left - 495;
				active_slider = active_slider + 1;
			}
		}
		

		$('#header_slider_container').animate({
			left: new_left
		}, 300, function() {
			scrolling = false;
		}
		);
		
		$('#header_slider_container > :not(#slider_'+active_slider+')').find('iframe').each(function() {
			$(this).attr('src', $(this).attr('src'));
		});  

		

		
	}
}





var default_news_height = 128;

function toggle_news_div(div_id) {
	var news_height = $('#news_content_'+div_id).outerHeight();
	var y = $('#news_content_'+div_id+'_container').parents('.scrollable').outerHeight();
	if (news_height == default_news_height) {
		var x = $('#news_content_'+div_id+'_container').outerHeight();
			
		$('#news_content_'+div_id).stop(true).animate({ height: x + 10 }, 250);
		$('#news_content_'+div_id+'_container').parents('.scrollable').stop(true).animate({ height: (y + (x - default_news_height) + 10) }, 250);

		$('#news_content_'+div_id+'_container').children('.news_more').hide();
		$('#news_content_'+div_id+'_container').children('.news_less').show();
	}
	else {
		$('#news_content_'+div_id).stop(true).animate({ height: default_news_height }, 250);
		$('#news_content_'+div_id+'_container').parents('.scrollable').stop(true).animate({ height: (y - (news_height - default_news_height) + 10) }, 250);
		
		$('#news_content_'+div_id+'_container').children('.news_more').show();
		$('#news_content_'+div_id+'_container').children('.news_less').hide();
	}

}

function show_archive() {
	$('#archive').show()
	$('#archive').css('overflow', 'visible');
	$('#archive').css('height', 'auto');
	
	$('#show_archive').hide();
	$('#hide_archive').show();
	
	$('#archive').parents('.scrollable').stop(true).animate({ height: ($('#news').outerHeight() + 10) }, 250);

}


function hide_archive() {
	$('#archive').css('overflow', 'hidden');
	$('#archive').css('height', '0');
	$('#archive').hide()
	
	$('#show_archive').show();
	$('#hide_archive').hide();
	
	$('#archive').parents('.scrollable').stop(true).animate({ height: ($('#news').outerHeight() + 10) }, 250);

}

