var is_chrome = (navigator.userAgent.toLowerCase().indexOf('chrome') > -1);
var is_firefox = (navigator.userAgent.toLowerCase().indexOf('firefox') > -1);

function setStyleSheet()
{
	var stylesheet = '';
    var sw = screen.width;
	var sh = screen.height;

	if (sw > 1280) stylesheet = 'std1600.css';
	else if (sw > 1024) stylesheet = 'std1280.css';
	else if (sw > 800) stylesheet = 'std1024.css';
	else stylesheet = 'standard.css';

	document.write('<link rel="stylesheet" href="./stylesheets/' + stylesheet + '">');
	//return '<link rel="stylesheet" href="./stylesheets/' + stylesheet + '">';
}

function urlExists(url)
{
	var localurl = "/faq/index.html";
	http.open("HEAD", url, true);
 http.onreadystatechange = function() {
  if (http.readyState==4) {
   if (http.status==200) alert("URL Exists!")
    else if (http.status==404) alert("URL doesn't exist!")
     else alert("Status is "+http.status)
  }
 }
 http.send(null)
}

function getHTTPObject() { 
	if (typeof XMLHttpRequest != 'undefined') { 
		return new XMLHttpRequest();
	} 
	
	try { 
		return new ActiveXObject("Msxml2.XMLHTTP"); 
	} 
	catch (e) { 
		try {
			return new ActiveXObject("Microsoft.XMLHTTP"); 
		} 
		catch (e) {} 
	} 
	
	return false; 
}

// Make requests using "create_http_object()"
// Also found on the net, but a bit changed
function makeHttpRequest(VUrl, VCallBack, VPostValues, UsePost)
{
    // Here we create xmlhttp the object
    var Http = getHTTPObject(); //create_http_object();

    // don't do make any request if the browser doesn't support AJAX
    if(!Http)
    {
        return false;
    }

		// If we received anything back call up the chosen function
    Http.onreadystatechange = function()
    {
        if(Http.readyState == 4)
        {
            // Call the function if the status is ok (200)
            if(Http.status == 200)
            {
								VCallBack(Http.responseText);
            }
            else
            {
                // Seems there was an error..
                alert('Error! ('+Http.status+')');
            }
        }
    }
		
		// Make sure the post values are filled out or on null..
    if(!VPostValues)
    {
        VPostValues = null;
    }
		if (UsePost) {
      // Open the appriopriate URL
      Http.open('POST', VUrl, true);
  		// Set the request header for a form sent by POST
      Http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      // send the post values
      Http.send(VPostValues);
		} 
		else {
			Http.open('GET', VUrl, true);
			Http.send(null);    
		}   
}


//var ctl = document.getElementById("savemailing");
//if (ctl != null) ctl.onChange = SaveMailing;

function SaveMailingAjax()
{
	//makeHttpRequest(url, CBSaveMailing, p, true);
	var params = 'a=emailing_save';
	var ctl = document.getElementById("from");
	if (ctl != null) params += '&' + ctl.name + '=' + ctl.value;
	ctl = document.getElementById("subject");
	if (ctl != null) params += '&' + ctl.name + '=' + ctl.value;
	ctl = document.getElementById("body");
	if (ctl != null) params += '&' + ctl.name + '=' + ctl.value;
	ctl = document.getElementById("attids");
	if (ctl != null) params += '&' + ctl.name + '=' + ctl.value;

	//var url = 'http://' + location.host + '/home/default.php';
	var url = '/v2/home/default.php';
	var http = getHTTPObject();
	http.open("POST", url, true);

	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	
	http.onreadystatechange = function() {
		if(http.readyState == 4 && http.status == 200) {
			CBSaveMailing(http.responseText);
		}
	}
	http.send(params);	
}

function CBSaveMailing(response)
{
	var ctl = document.getElementById("mailingsaved");
	if (ctl != null)
	{
		ctl.style.visibility = 'visible';
		ctl.innerHTML = "Mailing opgeslagen!";
		//ctl.innerHTML = response;
	}
}

function addAttachments() {
	//clearInterval();

	var obj = document.getElementById("attform");
	if (obj != null)
	{
		obj.style.display = "none";
		
		document.forms.form1.a.value = "emailing_freetext_att";
		document.forms.form1.submit();
	}
	//return true;
} // end function

function saveMailing() {
    var ctl;

    ctl = document.getElementById('from');
    if (ctl != null && ctl.value == '') {
        alert('Vul een afzender in a.u.b.');
        return false;
    }

    ctl = document.getElementById('subject');
    if (ctl != null && ctl.value == '') {
        alert('Vul een onderwerp in a.u.b.');
        return false;
    }

    document.forms.form1.a.value = "emailing_save";
	document.forms.form1.submit();
	//return true;
} // end function

function selectRegContact(newAction, ctl)
{
	if (ctl != null)
	{
		location.href = 'default.php?a=' + newAction + '&cid=' + ctl.value;
	}
}

function searchActivities() {
    var ctl = document.getElementById('search');
    if (ctl != null && ctl.value != '') {
      location.href = '/home/default.php?a=activities&search=' + ctl.value;
    }
}

function clearSearchActivities() {
    var ctl = document.getElementById('search');
    if (ctl != null) ctl.value = '';
    location.href = '/home/default.php?a=activities';
}

function searchReports() {
    var ctl = document.getElementById('search');
    if (ctl != null && ctl.value != '') {
      location.href = '/home/default.php?a=summary&search=' + ctl.value;
    }
}

function clearSearchReports() {
    var ctl = document.getElementById('search');
    if (ctl != null) ctl.value = '';
    location.href = '/home/default.php?a=summary';
}

function showDiv(sDivId) {
    var oCtl = document.getElementById(sDivId);
    if (oCtl != null) oCtl.style.visibility = 'visible';
}

function hideDiv(sDivId) {
    var oCtl = document.getElementById(sDivId);
    if (oCtl != null) oCtl.style.visibility = 'hidden';
}

function foldDiv(sDivId) {
    var oCtl = document.getElementById(sDivId);
    if (oCtl != null) oCtl.style.height = 5;
}

function unfoldDiv(sDivId) {
    var oCtl = document.getElementById(sDivId);
    if (oCtl != null) oCtl.style.height = 'auto';
}

function initTinyMCE() {
    tinyMCE.init({
        force_br_newlines : true,
        forced_root_block : '', // Needed for 3.x
        force_p_newlines: false,

        //content_css : "stylesheets/mail.css?" + new Date().getTime(),

		// General options
		mode : "textareas",
		theme : "advanced",
        skin : "o2k7",
        //skin_variant : "silver",
        //skin_variant : "black",
		//plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,tinybrowser",
        plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,insertdatetime,preview,media,print,contextmenu,paste,fullscreen,tinybrowser",

		// Theme options
		//theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
        theme_advanced_buttons1 : "save,preview,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
		//theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons2 : "cut,copy,paste,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,image,code,|,forecolor,backcolor",
		theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,|,sub,sup,|,charmap,emotions,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
		theme_advanced_buttons4 : "", //"insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,

		// Example content CSS (should be your site CSS)
		content_css : "css/content.css",

        remove_script_host : false,
        relative_urls : false,
        convert_urls : false,

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

        file_browser_callback : "tinyBrowser",

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
}

	function isValidEmailAddress(str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)

		if (str.indexOf(at)==-1){
		   //alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   //alert("Invalid E-mail ID")
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    //alert("Invalid E-mail ID")
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

		 if (str.indexOf(" ")!=-1){
		    //alert("Invalid E-mail ID")
		    return false
		 }

 		 return true
	}

function validateAndSubmitEmailForm(oEditor) {
    var el = document.getElementById('from');
    if (el != null) {
        if (el.value == '') {
            alert('Vul een afzender in a.u.b.');
            return false;
        }
    }

    el = document.getElementById('subject');
    if (el != null) {
        if (el.value == '') {
            alert('Vul een onderwerp in a.u.b.');
            return false;
        }
    }

    if (oEditor != null) {
      el = document.getElementById('body');
      if (el != null) {
          el.value = oEditor.getXHTMLBody();
          if (el.value == '') {
              alert('Vul een bericht in a.u.b.');
              return false;
          }
      }
    } else {
      alert('Vul een bericht in a.u.b.');
      return false;
    }

    var bChecked = false;
    for (i = 0; i < document.forms[0].elements.length; i++)
    {
      if (document.forms[0].elements[i].type == "checkbox")
      {
        if (document.forms[0].elements[i].checked) {
            bChecked = true;
            break;
        }
      }
    }

    if (!bChecked) {
        alert('Selecteer tenminste één groep a.u.b.');
        return false;
    }

    return true;
}
