/**
 * Functies voor filebrowser en koppeling met TinyMCE
 */


/**
 * Media types
 */
var mediaTypes=new Array();
mediaTypes[1]="image";
mediaTypes[2]="document";
mediaTypes[3]="video";
mediaTypes[4]="audio";
mediaTypes[5]="flash";

/**
 * File types
 */
function C_fileType(ext,ico,media)
{
	this.ext=ext;
	this.ico=ico;
	this.media=media;

	return this;
}

//data for all known extensions
var fileTypes=new Array(
	//ext,icon,mediaType
  new C_fileType("mp3","images/ico_mp3.gif","audio"),
  new C_fileType("flv","images/ico_flv.gif","video"),
  new C_fileType("swf","images/ico_swf.gif","flash"),
  new C_fileType("gif","images/ico_gif.gif","image"),
  new C_fileType("jpg","images/ico_jpg.gif","image"),
  new C_fileType("jpeg","images/ico_jpg.gif","image"),
  new C_fileType("doc","images/ico_doc.gif","document"),
  new C_fileType("pdf","images/ico_pdf.gif","document"),
  new C_fileType("rtf","images/ico_rtf.gif","document"),
  new C_fileType("xls","images/ico_xls.gif","document")
);

//reverse lookup for extensions
var fileTypesIndex=new Array();
for (var i=0;i<fileTypes.length;i++) {
	afileType=fileTypes[i];
	fileTypesIndex[afileType.ext]=i;
}

function getMediaType(afile) {
	var ext=getFileExtension(afile);
	if (fileTypesIndex[ext]!=null) {
		return fileTypes[fileTypesIndex[ext]].media;
	} else {
		return "unknown";
	}
}

/**
 * MW20080526: functie die puntkomma gescheiden lijst teruggeeft van toegestane extensies (voor bulk uploader)
 */
function getExtensionsByMediaType(mediaType) {
	fileExtensions="";
	for (var i=0;i<fileTypes.length;i++) {
		afileType=fileTypes[i];
		if (afileType.media==mediaType) {
			fileExtensions+="*."+afileType.ext+"; ";
		}
	}
	return fileExtensions;
}

function getFileExtension(afile) {
	var pos=afile.lastIndexOf(".");
	if (pos>-1) {
		return afile.substr(pos+1).toLowerCase();
	} else {
		return "";
	}
}

function getFileName(fullFilename) {
	var pos=fullFilename.lastIndexOf("/");
	if (pos>-1) {
		return fullFilename.substr(pos+1);
	} else {
		return "";
	}
}

function getFilePath(fullFilename) {
	var ext=getFileExtension(fullFilename);
	if (ext!="") {
		var pos=fullFilename.lastIndexOf("/");
		if (pos>-1) {
			return fullFilename.substr(0,pos);
		} else {
			return "";
		}

	} else {
		//als we geen extensie vinden, is het vast alleen een path
		return fullFilename;
	}
}

function extractMediumFromText(s) {
	s=s.toLowerCase();
	for (ext in fileTypesIndex) {
		if (s.indexOf("."+ext)>-1) {
			return fileTypes[fileTypesIndex[ext]].media;
		}
	}
}

function extractInfoFromText(s)	{
	//alert(s);
	var medium,r,re;
	var info={"url":"","t":"","s":"","ta":"","al":"","ml":"","mr":"","mt":"","mb":""}; //url,title,video size,target
	if (medium=extractMediumFromText(s)) {

		//URL
		if (medium=="video" || medium=="audio") {
			re=/\Wf=(.*?)[&"']/i;
		} else if (medium=="image") {
			re=/src[\s]*=[\s]*["'](.*?)['"]/i;
		} else if (medium=="document") {
			re=/href[\s]*=[\s]*["'](.*?)['"]/i;
		}
		if(r=s.match(re)) {
			info["url"]=r[1];
		}

		//Title
		if (medium=="video" || medium=="audio") {
			re=/t=(.*?)[&\"']/i;
			if(r=s.match(re)) {
				info["t"]=r[1];
			}
		} else if (medium=="image") {
			re=/title[\s]*=[\s]*["'](.*?)['"]/i;
			if(r=s.match(re)) {
				info["t"]=r[1];
			}
		}

		//Video size
		if (medium=="video") {
			re=/\Ws=(.*?)[&']/i;
			if(r=s.match(re)) {
				info["s"]=r[1];
			}
		}

		//Target
		if (medium=="document") {
			re=/target[\s]*=[\s]*["'](.*?)['"]/i;
			if(r=s.match(re)) {
				info["ta"]=r[1];
			}
		}

		//Image (align en margins
		if (medium=="image") {
			re=/margin\-left\:(\d+)px/i;
			if(r=s.match(re)) {
				info["ml"]=r[1];
			}

			re=/margin\-right\:(\d+)px/i;
			if(r=s.match(re)) {
				info["mr"]=r[1];
			}

			re=/margin\-top\:(\d+)px/i;
			if(r=s.match(re)) {
				info["mt"]=r[1];
			}

			re=/margin\-bottom\:(\d+)px/i;
			if(r=s.match(re)) {
				info["mb"]=r[1];
			}

			re=/align[\s]*=[\s]*["'](.*?)['"]/i;
			if(r=s.match(re)) {
				info["al"]=r[1];
			}

		}

	}
	return info;
}

function cleanupHTMLTinyMCE(type, value) {
	switch (type) {
		case "get_from_editor":
			//alert("Value HTML string: " + value);
			break;
		case "insert_to_editor":
			//alert("Value HTML string: " + value);
			break;
		case "get_from_editor_dom":
			//alert("Value DOM Element " + value);
			break;
		case "insert_to_editor_dom":
			//alert("Value DOM Element: " + value);
			break;
	}

	return value;
}



function initSIFR() {
	if(typeof sIFR == "function"){
		sIFR.replaceElement(named({sSelector:"h1", sFlashSrc:"/xsite/VAG_light.swf", sColor:"#3AA8E2", sLinkColor:"#000000", sBgColor:"#FFFFFF", sWmode: "transparent", sHoverColor:"#CCCCCC", nPaddingTop:5, nPaddingBottom:0, sFlashVars:"textalign=left&offsetTop=0"}));
		sIFR.replaceElement(named({sSelector:"h2", sFlashSrc:"/xsite/VAG_light.swf", sColor:"#3AA8E2", sLinkColor:"#000000", sBgColor:"#F2F2F2", sWmode: "transparent", sHoverColor:"#CCCCCC", nPaddingTop:0, nPaddingBottom:0, sFlashVars:"textalign=left&offsetTop=0"}));
	};
}

function initToolTip() {
	document.onmousemove=positiontip;
	addTooltip();
}




function jumpToSiteStructure(pageID) {
  document.location.href="/xsite/site_structure.php?id="+pageID;
}

function jumpToPageInfo(pageID,subpageID) {
  document.location.href="/xsite/admin_pageinfo.php?pid="+pageID+"&spid="+subpageID;
}

function deleteCurrentPage(pageID,subpageID) {
	var f=document.forms.dataprocessor_form;
	f.action="/xsite/confirm_delete.php";
	f.target="_self";
	f.cmd.value="confirm_delete";
	f.pid.value=pageID;
	f.spid.value=subpageID;
	f.submit();
}

function adoptBlock(block_id) {
  document.forms.dataprocessor_form.cmd.value="adopt_block";
  document.forms.dataprocessor_form.datasource.value="";
  document.forms.dataprocessor_form.block_id.value=block_id;
  document.forms.dataprocessor_form.submit();
}

function formatUrlPart(u) {
	u.value=convertToUrlPart(u.value);
}

function convertToUrlPart(v) {
	re=/\s+/g;

	v=v.toLowerCase();
	v=v.replace(/^\s+|\s+$/,'');
	v=v.replace(re,"_");
	v=v.replace(/\W+/g,'');
	
	return v;
}

/**
 * Ajax calls
 */
function sajax_init_object() {
	var A;
	try {
		A=new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			A=new ActiveXObject("Microsoft.XMLHTTP");
		} catch (oc) {
			A=null;
		}
	}
	if(!A && typeof XMLHttpRequest != "undefined")
		A=new XMLHttpRequest();
	if (!A)
		alert("Could not create connection object.");
	return A;
}

function doAjaxCall(cmd,params) {
  var postdata='cmd='+cmd+'&params='+params;

  var a=sajax_init_object();
  if (a) {
    a.open("POST","ajax_handler.php", false);
    a.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    a.send(postdata);
 	  document.body.style.cursor="default";

    if(a.readyState == 4) {
      return a.responseText;
    } else {
      alert("Xsite was unable to execute the ajax call.");
    }
  }
}
/**
 * center popups
 */
function Lvl_openWin(u,n,w,h,l,t,c,f,x) { //v2.0 4LevelWebs
  n+=getSiteIdentifier();
  var ww=((screen.width-w)/2);if(c==1){l=ww;t=(screen.height-h)/2;}if(c==2){l=ww}
	f+=',top='+t+',left='+l;LvlWin = window.open(u,n,f);LvlWin.focus();
	document.MM_returnValue=false;
}

/**
 * Helper functie die voor iedere site een apart nummer geeft, zodat popups niet conflicteren
 */
function getSiteIdentifier() {
	var s=document.domain;
	var n=0;
	for (var i=0;i<s.length;i++) {
		n+=s.charCodeAt(i);
	}
	return n.toString();
}

/**
 * OnClick handlers for gumbuttons
 */
function editBlock(block_id) {
  var aurl="/xsite/edit_contenttype.php?id="+block_id;
  var w=Lvl_openWin(aurl,'xsdatasource','700','540','0','0','1','width=700,height=640,scrollbars=yes,status=yes,menubar=no,location=no,resizable=yes,titlebar=no');return document.MM_returnValue;
	/* var w=window.open(aurl,'xsdatasource','left=0,top=0,width=700,height=500,scrollbars=yes,status=yes,menubar=no,location=no,resizable=yes,titlebar=no'); */
	w.focus();
}

/**
 * Page properties
 */
function editPageProperties(page_id,mode) {
  var aurl="/xsite/edit_pageproperties.php?id="+page_id+"&mode="+mode;
  if (editPageProperties.arguments.length>2) {
  	aurl+="&version="+editPageProperties.arguments[2];
  }
	var w=Lvl_openWin(aurl,'xspageproperties','700','540','0','0','1','width=700,height=640,scrollbars=yes,status=yes,menubar=no,location=no,resizable=yes,titlebar=no');return document.MM_returnValue;
	w.focus();
}

function showXSPopup(aurl) {
	var w=Lvl_openWin(aurl,'xspopup','700','540','0','0','1','width=700,height=640,scrollbars=yes,status=yes,menubar=no,location=no,resizable=yes,titlebar=no');return document.MM_returnValue;
	w.focus();
}

/**
 * New page
 */
function newPage(page_id) {
	document.location.href="/xsite/newpage1.php?id="+page_id;
}

/**
 * Dingen met blokken
 */
function removeBlock(block_id) {
  if (window.confirm('Are you sure you want to remove this block?')) {
    document.forms.dataprocessor_form.cmd.value="remove_block";
    document.forms.dataprocessor_form.datasource.value="";
    document.forms.dataprocessor_form.block_id.value=block_id;
    document.forms.dataprocessor_form.submit();
  }
}

function moveBlock(block_id,direction) {
  document.forms.dataprocessor_form.cmd.value="move_block_"+direction;
  document.forms.dataprocessor_form.block_id.value=block_id;
  document.forms.dataprocessor_form.submit();
}

function insertNewBlock(page_id,subpage_id,blockname,parent_block_id) {
  var aurl='/xsite/newblock_newexisting.php?pid='+page_id+'&spid='+subpage_id+'&b='+blockname+'&pbid='+parent_block_id;
  showXSPopup(aurl);
}

function editWidget(block_id) {
  var aurl="/xsite/edit_widget.php?id="+block_id;
  showXSPopup(aurl);
}


/**
 * Functions for file browser
 */

//insert the file url into dedicated field
function processFile(selectedFile) {
	if (selected_field!="") {
		document.forms["mainform"][selected_field].value=selectedFile;
	} else {
	  alert("Error: unknown destination field. Unable to insert link to the selected file.");
	}
}

function processFileWYSIWYG(fileInfo) {
	if (selected_field!="") {
    //Haal instance van editor op
    var inst = tinyMCE.getInstanceById(selected_field);

		//Image
		switch (fileInfo["mediaType"]) {
			case "image":
				insertImageIntoWYSIWYG(inst,fileInfo);
				break;
			case "audio":
				insertAudioIntoWYSIWYG(inst,fileInfo);
				break;
			case "video":
				insertVideoIntoWYSIWYG(inst,fileInfo);
				break;
			case "document":
				insertdocumentLinkIntoWYSIWYG(inst,fileInfo);
				break;
			/** Eventueel uitbouwen met flash **/
		}

	} else {
	  alert("Error: unknown destination field. Unable to insert link to the selected file.");
	}
}

function hasSelection(inst) {
  var sel = inst.selection.getSel();
	return (sel!="");
}

function insertContent(inst,content) {
  if (hasSelection(inst)) {
    inst.execCommand('mceReplaceContent',false,content);
  } else {
    inst.execCommand('mceInsertContent',false,content);
  }
}

function insertImageIntoWYSIWYG(inst,imageInfo) {

  var imgTag='<img src="'+imageInfo["url"]+'"';
  if (imageInfo["image_title"]) {
  	imgTag+=' title=\''+imageInfo["image_title"]+'\'';
  	imgTag+=' alt=\''+imageInfo["image_title"]+'\'';
  }
  if (imageInfo["f_align"]) {	imgTag+=' align="'+imageInfo["f_align"]+'"'; }
  imgTag+=' style="';
  imgTag+='margin-left:'+imageInfo["ml"]+'px;';
  imgTag+='margin-right:'+imageInfo["mr"]+'px;';
  imgTag+='margin-top:'+imageInfo["mt"]+'px;';
  imgTag+='margin-bottom:'+imageInfo["mb"]+'px;';
  imgTag+='"';
  imgTag+='>';

  insertContent(inst,imgTag);
}

function insertAudioIntoWYSIWYG(inst,audioInfo) {

	//oud:
  //var audioTag='<a href="javascript:;" onclick="audioPlayer(\''+audioInfo["url"].replace("'","\\'")+'\',\''+audioInfo["audio_title"].replace("'","\\'")+'\');" title="'+audioInfo["audio_title"]+'">';
	//var audioTag='<a href="javascript:;" onclick="window.open(\'/plugins/widgets/audioplayer/audioplayer.php?f='+audioInfo["url"].replace("'","\\'")+'&t='+audioInfo["audio_title"].replace("'","\\'")+'\',\'audioplayer\',\'width=250,height=79,scrollbars=no,status=no,menubar=no,location=no,resizable=no,titlebar=no\');">';
	var audioTag='<img class="xsInlineAudioPlaceHolder" src="/xsite/images/spacer.gif" title="f='+audioInfo["url"].replace("'","\\'")+'&t='+audioInfo["audio_title"].replace("'","\\'")+'">';

/*
  if (hasSelection(inst)) {
	  audioTag+="{$selection}</a>";
  } else {
	  if (audioInfo["audio_title"]!="") {
	  	audioTag+=audioInfo["audio_title"];
	  } else {
	  	audioTag+=audioInfo["url"];
	  }
	  audioTag+='</a>';
  }
 */
 
  insertContent(inst,audioTag);
}

function insertVideoIntoWYSIWYG(inst,videoInfo) {

	//videosize komt binnen als 640x480
	var size=videoInfo["video_size"].split("x");
	var w=parseInt(size[0]);
	var h=parseInt(size[1]);

	//var videoTag='<div class="xsInlineVideoPlaceHolder" style="width:'+w+'px;height:'+h+'px;" title="'+videoInfo["url"].replace("'","\\'")+'|'+videoInfo["video_size"]+'|'+videoInfo["video_title"].replace("'","\\'")+'"><strong>Videoplayer</strong><br>'+videoInfo["url"]+'<br>'+w+' px x '+h+' px</div>';
	var videoTag='<img class="xsInlineVideoPlaceHolder" src="/xsite/images/spacer.gif" title="f='+videoInfo["url"].replace("'","\\'")+'&s='+videoInfo["video_size"]+'&t='+videoInfo["video_title"].replace("'","\\'")+'" align="" height="'+h+'" width="'+w+'">';
  insertContent(inst,videoTag);
}

function insertdocumentLinkIntoWYSIWYG(inst,docInfo) {
	var docTarget=(docInfo["document_target"]!="")?' target="'+docInfo["document_target"]+'"':"";

 	//var docTag='<a href="'+docInfo["url"]+'"'+docTarget+' onclick="new Image().src=\'/plugins/modules/xstats/downloadcounter.php?doc=\'+this.href">';
  var docTag='<a href="'+docInfo["url"]+'"'+docTarget+'>';

  if (hasSelection(inst)) {
	  docTag+="{$selection}</a>";
  } else {
	  docTag+=docInfo["url"];
	  docTag+='</a>';
  }

  insertContent(inst,docTag);
}


//Waarschijnlijk niet in gebruik, moet wel...
function getLinkUrl(fieldname) {
	selected_field=fieldname;

	var linkbrowser_url="link_browser.php";
	if (document.forms["mainform"][fieldname].value!="")
	{
	  linkbrowser_url+="?link_url="+document.forms["mainform"][fieldname].value;
	}

	var w=window.open(linkbrowser_url,"second_popup","center=yes,width=760,height=565,resizable=yes,scrollbars=yes,status=yes,menubar=no,titlebar=no");
	w.focus();
}


function processLink(alink,mode) {
	if (selected_field=="")	{
	  alert("Error: unknown destination field. Unable to add link.");
	  exit;
	}

	if (mode=="wysiwyg") {
    var inst = tinyMCE.getInstanceById(selected_field);
    //var sel=inst.selection.getSel();
    var sel=inst.selection.getContent();

		//check of er een target is geselecteerd
		if (alink["f_target"]) {
			//check of het een gewone target is, of een popup
			var linktarget=alink["f_target"];

			if (linktarget.charAt(0)=="_") {
		  	var linkTag='<a href="'+alink["link_url"]+'" target="'+linktarget+'">';
		  } else {
		  	var dim=linktarget.split("x");
		  	popup_properties='width='+dim[0]+',height='+dim[1]+',toolbar=no,location=no,status=no,menubar=0,scrollbars=yes,resizable=yes';
		  	var linkTag="<a href=\"javascript:;\" onclick=\"window.open('"+alink["link_url"]+"','linked_popup','"+popup_properties+"');\">";
		  }
		} else {
		  var linkTag='<a href="'+alink["link_url"]+'">';
		}

    if (sel!="") {
  	  //linkTag+="{$selection}</a>";
  	  linkTag+=sel+"</a>";
    } else {
  	  linkTag+=alink["link_url"]+"</a>";
    }

//    alert(linkTag);

    insertContent(inst,linkTag);
	}
	else {
		//Dedicated link field
		if (selected_field!='') {
			document.forms["mainform"][selected_field].value=alink;
		}
	}
}

function getImageUrl(fieldname)
{
	selected_field=fieldname;

	fieldVal=document.forms["mainform"][selected_field].value;
	if (fieldVal!="")
	{
		aurl="?media=1&url="+fieldVal;
	}
	else
	{
	  aurl="?media=1";
	}
	var w=window.open("file_browser.php"+aurl,"second_popup","center=yes,width=840,height=660,scrollbars=yes,resizable=yes,status=yes,menubar=no,titlebar=no");

	w.focus();
}

function getDocumentUrl(fieldname)
{
	selected_field = fieldname;
	fieldVal=document.forms["mainform"][selected_field].value;
	if (fieldVal!="")
	{
		aurl="?media=2&url="+fieldVal;
	}
	else
	{
	  aurl="?media=2";
	}
	var w=window.open("file_browser.php"+aurl,"second_popup","center=yes,width=790,height=660,resizable=yes,status=yes,menubar=no,titlebar=no");
	w.focus();
}

function getFileUrl(fieldname,media)
{
	selected_field=fieldname;
	fieldVal=document.forms["mainform"][selected_field].value;
	if (fieldVal!="") {
		aurl="?media="+media+"&url="+fieldVal;
	}
	else {
	  aurl="?media="+media;
	}
	var w=window.open("file_browser.php"+aurl,"second_popup","center=yes,width=790,height=660,resizable=yes,status=yes,menubar=no,titlebar=no");
	w.focus();
}


/**
 * OnClick handlers for top menu (edit/preview, page properties etc.)
 */
function editBlock(block_id) {
  var aurl="/xsite/edit_contenttype.php?id="+block_id;
  showXSPopup(aurl);
}

/**
 * Show / Hide MENU -gumbutton
 */
function showDiv(divid) {
 if (document.layers) document.layers[divid].display='block';
 else document.getElementById(divid).style.display='block';
}

function hideDiv(divid) {
 if (document.layers) document.layers[divid].display='none';
 else document.getElementById(divid).style.display='none';
}

function highlightRow(r) {
	r.style.backgroundColor='#DFE3F6';
}

function dimRow(r) {
	r.style.backgroundColor='#FFFFFF';
}

/**
 * Datum conversie routines
 */


/**
 * Converteer een lokaal geformatteerde datum naar een MySQL-datum. LET OP: Functie gebruikt globale variabele fmt.
 */
function jsDateToMySQLDate(datum) {

	var sep=datum.replace(/[0-9a-z]/ig,"").charAt(0);
	var a=datum.split(sep);
	var m=new Array();

	//MW:20080128: 09 wordt door parseInt als 0 teruggegeven, hiervoor heb ik er nog een parseFloat omheen gezet
	for (var i=0,j=0;i<fmt.length;i+=2,j++)	{
		if (fmt.charAt(i)=="d"||fmt.charAt(i)=="j") m[2]=parseInt(parseFloat(a[j]));
		if (fmt.charAt(i)=="m"||fmt.charAt(i)=="n") m[1]=parseInt(parseFloat(a[j]));
		if (fmt.charAt(i)=="Y"||fmt.charAt(i)=="y") m[0]=parseInt(parseFloat(a[j]));
	}

	return m[0]+sep+(m[1]<10?"0"+m[1]:m[1])+sep+(m[2]<10?"0"+m[2]:m[2]);
}

/**
 * Converteer een MySQL-datum naar een lokaal geformatteerde datum. Functie gebruikt globale variabele fmt.
 */
function mySQLDateToJSDate(mdatum) {

	var sep=fmt.replace(/[0-9a-z]/ig,"").charAt(0);
	var a=mdatum.split("-");

	if (a.length==3) {
		var m=new Array();
		var d=new Date(a[0],a[1]-1,a[2]);
		var day=d.getDate();
		var month=d.getMonth()+1;
		var year=d.getFullYear();

		if (year>1900) {
			for (var i=0,j=0;i<fmt.length;i+=2,j++)	{
				if (fmt.charAt(i)=="d") m[j]=(day<10) ? "0"+day : day;
				if (fmt.charAt(i)=="j") m[j]=day;
				if (fmt.charAt(i)=="m") m[j]=(month<10) ? "0"+month : month;
				if (fmt.charAt(i)=="n") m[j]=month;
				if (fmt.charAt(i)=="Y") m[j]=year;
				if (fmt.charAt(i)=="y") m[j]=year; //moet eigenlijk 2-cijferig jaar zijn, willen we niet meer
			}

			return m[0]+sep+m[1]+sep+m[2];
		}	else {
			return "";
		}

	} else {
		return "";
	}
}

/**
 * Update Yahoo calendar nadat gebruiker handmatig in een edit-box heeft getypt. yuiCalendar is ref naar cal. mdatum in MySQL yyyy-mm-dd formaat.
 */
function updateCalendar(yuiCalendar,mdatum) {
	var a=mdatum.split("-");
	year=a[0];
	month=a[1];
	day=a[2];

	if (! isNaN(month) && ! isNaN(day) && ! isNaN(year)) {
		var date=year+"/"+month+"/"+day; //volgorde afhankelijk van init yui calendar
		yuiCalendar.select(date);
		yuiCalendar.cfg.setProperty("pagedate", month + "/" + year);
		yuiCalendar.render();
	}
}