// +------------------------------------------------------------------+
// | 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>     					  |
// +------------------------------------------------------------------+
var slideshowSpeed = 6000;

$(document).ready(function(){	
	$(document).pngFix(); 
	$('.input').defaultInputValue();
	$('.zoek_input').defaultInputValue();
	//theRotator();	
	initmenu();
	
	if(photos.length > 0){
		var interval;
		$("#control").toggle(function(){
			stopAnimation();
		}, function() {
			// Change the background image to "pause"
			$(this).css({ "background-image" : "url(images/btn_pause.png)" });
			
			// Show the next image
			navigate("next");
			
			// Start playing the animation
			interval = setInterval(function() {
				navigate("next");
			}, slideshowSpeed);
		});
		
		
		var activeContainer = 1;	
		var currentImg = 0;
		var animating = false;
		var navigate = function(direction) {
			// Check if no animation is running. If it is, prevent the action
			if(animating) {
				return;
			}
			
			// Check which current image we need to show
			if(direction == "next") {
				currentImg++;
				if(currentImg == photos.length + 1) {
					currentImg = 1;
				}
			} else {
				currentImg--;
				if(currentImg == 0) {
					currentImg = photos.length;
				}
			}
			
			// Check which container we need to use
			var currentContainer = activeContainer;
			if(activeContainer == 1) {
				activeContainer = 2;
			} else {
				activeContainer = 1;
			}
			
			showImage(photos[currentImg - 1], currentContainer, activeContainer);
			
		};
		
		var currentZindex = -1;
		var showImage = function(photoObject, currentContainer, activeContainer) {
			animating = true;
			
			// Make sure the new container is always on the background
			currentZindex--;
			
			// Set the background image of the new active container
			$("#headerimg" + activeContainer).css({
				"background-image" : "url(" + photoObject.image + ")",
				"display" : "block",
				"z-index" : currentZindex
			});
			
			// Hide the header text
			$("#headertxt").css({"display" : "none"});
			
			
			// Fade out the current container
			// and display the header text when animation is complete
			$("#headerimg" + currentContainer).fadeOut(function() {
				setTimeout(function() {
					$("#headertxt").css({"display" : "block"});
					animating = false;
				}, 500);
			});
		};
		
		var stopAnimation = function() {
			// Change the background image to "play"
			$("#control").css({ "background-image" : "url(images/btn_play.png)" });
			
			// Clear the interval
			clearInterval(interval);
		};
		
		// We should statically set the first image
		navigate("next");
		
		// Start playing the animation
		interval = setInterval(function() {
			navigate("next");
		}, slideshowSpeed);
	}
/*	$("a[rel=fancy_group]").fancybox({
		'titlePosition' 	: 'over',
		'titleFormat'       : function(title, currentArray, currentIndex, currentOpts) {
		    return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + ' ' + title + '</span>';
		}
	});
	$("a.iframe").fancybox({
		'titlePosition'		: 'inside',
		'scrolling'			: 'no',
		'width' 			: 600,
		'height'			: 400
	});*/
	
	
})

/**
 * The load function
 * 
 * @return void
 */
function doLoad( ){}

/**
 * Image rotator
 * 
 * @return void
 */
function chgImg(direction) {
	if (document.images) {
	ImgNum = ImgNum + direction;
	if (ImgNum > ImgLength) {
	ImgNum = 0;
	}
	if (ImgNum < 0) {
	ImgNum = ImgLength;
	}
	document.slideshow.src = NewImg[ImgNum];
	document.getElementById('slideshowurl').href = NewImgURL[ImgNum];
   }
}
function auto() {
	if (lock == true) {
		lock = false;
		window.clearInterval(run);
		}
		else if (lock == false) {
		lock = true;
		run = setInterval("chgImg(1)", delay);
   }
}

function searchBlur(field,defaultvalue){
	if (field.value == ''){
		field.value = defaultvalue;
	}else{ }		
}
function searchFocus(field,defaultvalue){
	if (field.value == defaultvalue){
		field.value = '';
	}
}

/**
 * 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) {
	if (thefield.defaultValue == thefield.value) {
		thefield.value = "";
		thefield.style.color = "#b2b2b2";
	}
	else thefield.value = thefield.defaultValue;
}


/**
 * 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 disableSubmit(id,form){
	try{
		document.getElementById(id).style.display = 'none';
		document.getElementById(id).disabled = 'disabled';
		
		document.inputForm.submit();		
		document.getElementById('displayLoading').style.display = 'block';	
		}
	catch(e){}
}


function load_image(id){ 
	var imgpath = document.getElementById(id).value; 
	if(imgpath != "") {
		// code to get File Extension..
		
		var arr1 = new Array;	
		arr1 = imgpath.split("\\");	
		var len = arr1.length;	
		var img1 = arr1[len-1];	
		var filext = img1.substring(img1.lastIndexOf(".")+1);	
		
		// Checking Extension	
		if(filext == "jpg" || filext == "jpeg" || filext == "JPG" || filext == "JPEG")	
		{
			return true;
		}
		else	
		{
			alert("Het geselecteerde bestand is niet toegestaan.\nSelecteer een geldige extensie (*.jpg/*.jpeg)");
			document.getElementById(id + '_span').innerHTML = "";
   			document.getElementById(id + '_span').innerHTML = "<input type=\"file\" name=\"afbeeldingFile[]\" id=\""+id+"\" onchange=\"load_image(this.id)\" style=\"width:200px;\" />";		
			return false;
		}
	}
}


/**
 * Get the parentnode of the tab
 * @return node
 */
function findTabs(tab)
{
	return tab.parentNode;
}


/**
 * Get the tab
 * @return node
 */
function getTabId(tab)
{
	return tab.getElementsByTagName("a")[0].id;
}


/**
 * Show tab
 * @return bool
 */
function showTab(o)
{
	var current_tab = o.parentNode;
	var current_tabs = current_tab.parentNode.getElementsByTagName("li");
	for (var i = 0; i < current_tabs.length; i++) {
		current_tabs[i].id="";
		document.getElementById(getTabId(current_tabs[i]) + "-content").style.display="none";
	}
	current_tab.id = "current";
	document.getElementById(getTabId(current_tab) + "-content").style.display="block";
	document.cookie = findTabs(current_tab).id + "=" + getTabId(current_tab);
	return false;
}


/**
 * Focus field
 * @return void
 */
function eFocus(field,value){
	if (field.value == value){
		field.value ='';
	}
	field.className="bfilter"
}


/**
 * Blur field
 * @return void
 */
function eBlur(field,value){
	if (field.value == ''){
		field.value = value;
		field.className="rfilter";
	}else{
		field.className="bfilter";
	}
}


/**
 * Add load event
 * @return void
 */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}


/**
 * AJAX clientside include
 * @return bool
 */
function clientSideInclude(id, url){
  var req = false;
  // For Safari, Firefox, and other non-MS browsers
  if (window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch (e) {
      req = false;
    }
  } else if (window.ActiveXObject) {
    // For Internet Explorer on Windows
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        req = false;
      }
    }
  }
 var element = document.getElementById(id);
 if (!element) {
  alert("Bad id " + id +
   "passed to clientSideInclude." +
   "You need a div or span element " +
   "with this id in your page.");
  return;
 }
  if (req) {
    // Synchronous request, wait till we have it all
    req.open('GET', url, false);
    req.send(null);
    element.innerHTML = req.responseText;
  } else {
    element.innerHTML =
   "Sorry, your browser does not support " +
      "XMLHTTPRequest objects. This page requires " +
      "Internet Explorer 5 or better for Windows, " +
      "or Firefox for any system, or Safari. Other " +
      "compatible browsers may also exist.";
  }
}

function menuRollOver(id){			
	//try{
		mainnav = document.getElementById("menu_level1")
		subnav = document.getElementById("menu_level2")
		for(var i=0; i < mainnav.getElementsByTagName("a").length; i++){	
			e = mainnav.getElementsByTagName("a")[i].id;		
			if( id == e ){			
				document.getElementById(e).className = 'menu_level1_on';
			}
			else{		
				document.getElementById(e).className = 'menu_level1';	
			}
		}	
		for(var i=0; i < subnav.getElementsByTagName("div").length; i++){
			e = subnav.getElementsByTagName("div")[i];	
			if(e.id == "menu_level2_" + id){
				e.style.display = "block"			
			}
			else{
				e.style.display = "none"
			}
		}
	//} catch(e){ }
}

function getElementsByClassName( strClassName, obj ) {    
	var ar = arguments[2] || new Array();    
	var re = new RegExp("\\b" + strClassName + "\\b", "g");    
	if ( re.test(obj.className) ) {        
		ar.push( obj );    
	}    
	for ( var i = 0; i < obj.childNodes.length; i++ )        
		getElementsByClassName( strClassName, obj.childNodes[i], ar );        
	return ar;
}

function menuOnload() {    
	var aryClassElements = getElementsByClassName( 'menu_level1_on', document.getElementById('menu_level1') );    
	for ( var i = 0; i < aryClassElements.length; i++ ) {       
		menuRollOver(aryClassElements[0].id);
	}
}

/**
 *
 */
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 getRadioValue()
{
 theRadioValue = 0;    
 for (var i=0; i < document.signup_frm.gender.length; i++)
  {
	 if (document.signup_frm.gender[i].checked) 
	 { 
		  theRadioValue = document.signup_frm.gender[i].value;
		  break;
	 }
  }  
  return theRadioValue;
}

function show_unsubscribe()
{
  document.getElementById('mailinglist_content').style.display = 'none';
  document.getElementById('mailinglist_unsubscribe').style.display = 'block';
}

function error_back()
{
  document.getElementById('mailinglist_error').style.display = 'none';
  document.getElementById('mailinglist_content').style.display = 'block';
}

function submitInput(){
  var f_firstname = document.getElementById('f_firstname').value;
  var f_lastname = document.getElementById('f_lastname').value;
  var f_company = document.getElementById('f_company').value;
  var f_gender = getRadioValue();
  var f_email = document.getElementById('f_email').value;  
  var query = 'f_firstname='+f_firstname+'&f_lastname='+f_lastname+'&f_gender='+f_gender+'&f_email='+f_email+'&f_company='+f_company;	  
  mailinglistXmlhttpPost(MAILINGLIST_URL, query);
}

function submitUnsubscribe(){
  var f_email = document.getElementById('f_email_unsubscribe').value;	  
  var query = 'f_email='+f_email;	  
  mailinglistXmlhttpPost(MAILINGLIST_URL+'/sub,2', query);
}	
