
/**
 * @name StaticJs.js
 * @author Jiri v. Bergen
 * @copyright 2006 - Safihre
 * @version 1.0
 * 
 * Alle standaard javascript functies..
 * Sommige gejat, maar dat dan wel netjes gemeld ;-)
 */

/**
* Hele mooie AjaxFunctie, wel gejat.. Maar beter zou ik het toch niet doen :P
***
* params:    Parameters for the requested url in the format p1=1&p2=0&p3=2
* meth:      The request method. Can be "get" or "post". Default is "post".
* async:     Toggles asynchronous mode. Default is true.
* startfunc: A function or list of functions to be called before the AJAX
*            request is made. A list of functions must be separated by the
*            semi-colon like this: "showLoad(); animateText(); hideDiv('bob')".
*            You can pass parameters into the functions.
* endfunc:   A function or list of functions to be called after a successful
*            AJAX request. Uses the same format as "startfunc".
* errorfunc: A function or list of functions to be called when the AJAX request
*            is unsuccessful. Uses the same format as "startfunc".
*
* Returns true on success and false on failure.
*
* Example Usage:
*
  ajaxUpdate( "rightdiv", "getData.php", {
    meth:"post",
    async:true,
    startfunc:"elemOn('loading')",
    endfunc:"elemOff('loading'); elemOn('rightdiv')",
    errorfunc:"ajaxError()",
  	ChacheBust: true }
  );
*/

function ajaxUpdate( elemid, url, options ) {
	var meth = options.meth || "GET";
	var async = options.mode || true;
	var startfunc = options.startfunc || "";
	var endfunc = options.endfunc || "";
	var errorfunc = options.errorfunc || "";
	var CacheBust = options.CacheBust || true;
	var focusl = options.focusl || "";
	var req = false;
	if( window.XMLHttpRequest )
		req = new XMLHttpRequest();
	else if( window.ActiveXObject )	
		req = new ActiveXObject( "Microsoft.XMLHTTP" );
	else {
    	alert( "Your browser cannot perform the requested action. "+
   			"Either your security settings are too high or your "+
  			"browser is outdated. Try the newest version of "+
   			"Internet Explorer or Mozilla Firefox." );
   		return false;
	}
	if( startfunc != "" )
		eval( startfunc );
	/** 
	 * EDIT Safihre: Met laad icoontje & anti-cache spul
	 */
	//document.getElementById(elemid).innerHTML = "<img src=\"images/feed-loading.gif\" id=\"LoadImg\" alt=\"laden\">";
	// Extra anti cache ding als nodig is
	AntiCache = '';
	if(CacheBust) {
		AntiCache = (url.indexOf("?")!=-1) ? "&" + new Date().getTime() : "?" + new Date().getTime();
	}
	req.open( meth, url + AntiCache, async );
	//req.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded" );
	req.onreadystatechange = function() {
		if ( req.readyState == 4 ) {
			if ( req.status == 200 || ( window.location.href.indexOf("http")==-1) ) {
				document.getElementById(elemid).innerHTML = req.responseText;
				if( endfunc != "" )
            		eval( endfunc );
            	if( focusl != "") 
            		document.location = options.focusl;
            	return true;
			} else {
				if( endfunc != "" )
					eval( endfunc );
				if( errorfunc != "" )
					eval( errorfunc );
				return false;
			}	
		}
	};
	req.send(null);
}

/**
 Gestolen email check functie..
 Hij is wel uber-uitgebreid :P
**/
function ExtendedEmailCheck (emailStr) {
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			return false;
	   }
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			return false;
	   }
	}
	if (user.match(userPat)==null) {
		return false;
	}
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				return false;
	   		}
		}
		return true;
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			return false;
	   }
	}
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		return false;
	}
	if (len<2) {
		return false;
	}
	return true;
}

// Verkrijgen alle elementen met classnaam.
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

// Removes leading whitespaces
function LTrim( value ) {
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
}

// Removes ending whitespaces
function RTrim( value ) {	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");	
}

// Removes leading and ending whitespaces
function trim( value ) {
	return LTrim(RTrim(value));
}

/**
  Eigen functies
**/

// Verkrijgen element via id
function El(id) {
	return document.getElementById(id);
}

// Zichtbaar/onzichtbaar maken van element
function ShowOrHide (ID) { 
	if(El(ID).style.display == 'none') { 
		El(ID).style.display = ''; 
	} else { 
		El(ID).style.display = 'none'; 
	}
}

// Verbergen
function Hide(ID) {
	El(ID).style.display = 'none'; 
}

// Voor het laten verkleuren van de rijen in tabel
function ColorRow(FuncId) {
	if ( FuncId.style.backgroundColor == '') {
		FuncId.style.backgroundColor = '#EBEBEB';
	} else {
		FuncId.style.backgroundColor = '';
	}
}

// Upload venster
function UploadWindow() {
	page = '/upload.php?upload=1';
	SW = window.open(page,'UploadWin','toolbar=no,menubar=no,location=no,resizable=no,status=no,width=700,height=300,scrollbars=yes')            
	SW.moveTo(30,30);  
	SW.resizeTo(400,200);
}

// Edit menu pagina's/users
function ShowEditMenu(ID) {
	var cells = document.getElementsByName('Edits');
	for(j = 0; j < cells.length; j++) cells[j].style.display = 'none';
	ShowOrHide(ID);
}

// Nettere doorstuur functie
function SendMe(url) {
	document.location = url;
}

// Openen fotoboek show
function OpenFotoShow(AlbumId, FotoNr) {
	FotoShowUrl = '/fotoboek_content.php?AlbumId='+AlbumId+'&FotoNr='+FotoNr;
	FotoShow = window.open(FotoShowUrl,'FotoAlbum'+AlbumId,'toolbar=no,menubar=no,location=no,resizable=no,status=no,scrollbars=yes')            
	FotoShow.moveTo(40, 40);  
	FotoShow.resizeTo(630, 800);
	FotoShow.focus();
}

// Past daadwerkelijk de foto aan
function ShowImg(FotNr) {
	// Vervangen foto & onderschrift
	El("FotoImg").src = '/images/fotoboekimg/'+FotoLinks[FotNr];
	El("FotoText").innerHTML = FotoText[FotNr];
	
	// Ophalen reacties & aanpassen reactie id/link
	ajaxUpdate("ReactiesFotoboek", "/ajax_reacties.php?LinkId="+FotoLinks[FotNr], {CacheBust:false, endfunc:"CheckSmilies()"});
	El("FotoNr").value = FotoLinks[FotNr];
	El("ReactieForm").action = "/fotoboek_content.php?AlbumId="+CurAlbum+"&FotoNr="+(FotNr+1);

	// Als ingelogd als admin dan ook bijwerken forminfo
	if(IsAdmin == 1) {
		El("fotoinfo").value = FotoText[FotNr];
		El("fotoid").value = FotoIds[FotNr];
		El("EditFotoForm").action = "/fotoboek_content.php?AlbumId="+CurAlbum+"&FotoNr="+(FotNr+1);
		El("DelLink").href = "/index.php?page=del&FotoId="+FotoIds[FotNr]+"&RedirUrl=%2Ffotoboek_content.php%3FAlbumId%3D"+CurAlbum+"%26FotoNr%3D1"
	}
}

// Voor fotoboek, volgende plaatje
function NextImg() {
	// Verhogen teller
	CurFoto = CurFoto + 1;
	
	// Kijken of we niet over max zitte
	if(CurFoto > (FotoLinks.length-1)) CurFoto = 0;
	
	// Uitvoeren wissel
	ShowImg(CurFoto);
}

// Fotoboek: vorige knop
function PrevImg() {
	// Verhogen teller
	CurFoto = CurFoto - 1;
	
	// Kijken of we niet over max zitte
	if(CurFoto < 0) CurFoto = (FotoLinks.length-1);
	
	// Uitvoeren wissel
	ShowImg(CurFoto);
}

// Fotoboek: edit knop
function EditFoto() {
	// Bijwerken foto ID en tekst in edit form
	El("fotoinfo").value = FotoText[CurFoto];
	El("fotoid").value = FotoIds[CurFoto];
	// Laten zien form
	ShowOrHide("EditFotoForm");
}

// Checken reactie form
function CheckReactie(hetform) {
	with(hetform) {
		if(trim(naam.value).length < 2) {
			alert("Naam moet minimaal 2 letters zijn!");
			naam.focus();
			return false;
		}
		/*
		if(!ExtendedEmailCheck(email.value)) {
			alert("Email adres ongeldig!");
			email.focus();
			return false;
		}*/
		if(trim(comment.value).length < 1) {
			alert("Geen reactie ingevoerd!");
			comment.focus();
			return false;
		}
	}
	return true;
}

// Vervangt smilie code door plaatjes
function UBBSmilieReplace(text) {
	text = text.replace(/:cry:/gi, "<img alt='' src='/images/smilies/cry.gif'>");
	text = text.replace(/:devil:/gi, "<img alt='' src='/images/smilies/devil.gif'>");
	text = text.replace(/:@/gi, "<img alt='' src='/images/smilies/frown.gif'>");
	text = text.replace(/\|:\(/gi, "<img alt='' src='/images/smilies/frusty.gif'>");
	text = text.replace(/:P/gi, "<img alt='' src='/images/smilies/puh2.gif'>");
	text = text.replace(/:kots:/gi, "<img alt='' src='/images/smilies/pukey.gif'>");
	text = text.replace(/:O/gi, "<img alt='' src='/images/smilies/redface.gif'>");
	text = text.replace(/\*D/gi, "<img alt='' src='/images/smilies/shiny.gif'>");
	text = text.replace(/:Z/gi, "<img alt='' src='/images/smilies/sleephappy.gif'>");
	text = text.replace(/:\)/gi, "<img alt='' src='/images/smilies/smile.gif'>");
	text = text.replace(/;\)/gi, "<img alt='' src='/images/smilies/wink.gif'>");
	text = text.replace(/;-\)/gi, "<img alt='' src='/images/smilies/wink.gif'>");
	text = text.replace(/:$/gi, "<img alt='' src='/images/smilies/biggrin.gif'>");
	text = text.replace(/:\+/gi, "<img alt='' src='/images/smilies/clown.gif'>");
	text = text.replace(/:\?/gi, "<img alt='' src='/images/smilies/confused.gif'>");
	text = text.replace(/8-\)/gi, "<img alt='' src='/images/smilies/coool.gif'>");
	text = text.replace(/\(A\)/gi, "<img alt='' src='/images/smilies/smilie_innocent.gif'>");
	text = text.replace(/\(L\)/gi, "<img alt='' src='/images/smilies/smilie_heart_bounce.gif'>");
	text = text.replace(/:D/gi, "<img alt='' src='/images/smilies/shiny.gif'>");
	return text;
}

// Toevoegen smilie
function emoticon(smilie) {
	var TextField = El("commentveld");
	TextField.value += " " + smilie + " ";
	TextField.focus();
}

// Bijwerken smilies in reacties
function CheckSmilies() {
	var Reacties = getElementsByClass('ReactieText', null, 'span');
	for(r = 0; r < Reacties.length; r++) {
		Reacties[r].innerHTML = UBBSmilieReplace(Reacties[r].innerHTML);
	}
}
