var captchaVal = "";
var authorcount = 1;
var page = 0;
var authors = new Array();
var conferencethemes = new Array();
var pages = new Array();
pages[0] = new Array();
var authorSaved = false;
var confMail = false;
var corrAuthor = false;
var type ="";
//page,before functie, title, description, after function
pages[0][0] = "authorPage";
pages[0][1] = "checkType();";
pages[0][2] = "Author";
pages[0][3] = "Please, enter the details of the authors of the paper.";
pages[0][4] = "checkAuthor();";
pages[1] = new Array();
pages[1][0] = "abstractPage";
pages[1][1] = "checkType();";
pages[1][2] = "Abstract info";
pages[1][3] = "";
pages[1][4] = "checkAbstract();";
pages[2] = new Array();
pages[2][0] = "conferencethemesPage";
pages[2][1] = "getConferenceThemes();";
pages[2][2] = "Conference themes";
pages[2][3] = "Please, choose the conference themes of the paper.";
pages[2][4] = "setloading(true);checkConferenceThemes();";
function saveAuthor(){
    var msg="";
    if(authorcount > 1 && typeof(authors[$("authorNumber").value]) == "undefined"){
       for(var i=1;i<(authorcount);i++){     
          var arr = authors["Author"+i];
          if(typeof(arr) != "undefined"){
              if($("fname").value.toLowerCase() ==arr["fname"].toLowerCase() && $("lname").value.toLowerCase() == arr["lname"].toLowerCase()){
                      msg += "-The name of this author is equal to a previous author. Please change the name of this author.";
              }
          }
      }
    }
    if(!confirmEmail($("confemail"))) return false;
    if($("fname").value =="" && $("lname").value == "" ){
        msg+="-The first and last name of the Author are empty. \n";    
    }else{
        if($("fname").value ==""){
            msg+="-The first name of the Author is empty. \n";    
        }
        if($("lname").value ==""){
            msg+="-The last name of the Author is empty. \n";    
        }
        if($("authorTitle").value =="-" ||$("authorTitle").value == ""){
            msg+="-The title of Author "+$("fname").value+" "+$("lname").value +" is empty. \n";    
        }
        if($("university").value ==""){
            msg+="-The university of Author "+$("fname").value+" "+$("lname").value +" is empty. \n";    
        }
        if($("address").value ==""){
            msg+="-The address of Author "+$("fname").value+" "+$("lname").value +" is empty. \n";    
        }
        if($("postalcode").value ==""){
            msg+="-The zip/postal code of Author "+ $("fname").value+" "+$("lname").value +" is empty. \n";    
        }
        if($("city").value ==""){
            msg+="-The city of Author "+$("fname").value+" "+$("lname").value +" is empty. \n";    
        }
        if($("country").value ==""){
            msg+="-The country of Author "+$("fname").value+" "+$("lname").value +" is empty. \n";    
        }
        if($("email").value ==""){
            msg+="-The email adress of Author "+$("fname").value+" "+$("lname").value +" is empty. \n";    
        }
        if($("phone").value ==""){
            msg+="-The phone number of Author "+$("fname").value+" "+$("lname").value +" is empty. \n";    
        }
    }
    if(msg !=""){
        alert("the following error(s) occurred:\n" + msg);
        authorSaved = false;
        return false;
    }  
    
    if(typeof(authors[$("authorNumber").value]) == "undefined"){
        authors["Author" + authorcount] = new Array();
        var arr = authors["Author" + authorcount];
        var test = $("authortab").innerHTML;     
       $("authortab").innerHTML = test+ " <span><a id='spanAuthor"+authorcount+"' name='authorspan"+authorcount+"' style='font-size:15px;margin:3px;' href='javascript:getAuthor(\"Author"+authorcount+"\");'>| "+ $("fname").value + " "+$("lname").value +" |</a></span>";    
    }else{
        var count = $("authorNumber").value;
        var arr = authors[count];
        $("span"+count).innerHTML ="| "+ $("fname").value + " "+$("lname").value + " |";   
    }
    arr["fname"] = $("fname").value;
    arr["lname"] = $("lname").value; 
    arr["authortitle"] = $("authorTitle").value;
    arr["university"] = $("university").value;
    arr["address"] = $("address").value;
    arr["postalcode"] = $("postalcode").value;
    arr["city"] = $("city").value;
    arr["country"] = $("country").value;
    arr["email"] = $("email").value;
    arr["phone"] = $("phone").value;
    if(corrAuthor){
        if($("authorName").value == ""){
            arr["corresponding"] = "true";
            $("authorName").value = $("fname").value + " " +  $("lname").value;
        }else{
            if( $("authorName").value == $("fname").value + " " +  $("lname").value){
                arr["corresponding"] = "true";    
            }else{
                arr["corresponding"] = "false";      
            }
        }            
    }else{
        arr["corresponding"] = "false";
    }
    authorSaved = true;
    return true;
}
function newAuthor(){
    if(!authorSaved){
        alert("the following error(s) occurred:\n-The current author is not saved. Please save the current author first.");    
    }else{
        clear(pages[page][0]);
        authorcount++;
        $("titleAuthor").innerHTML =  "Author "+ authorcount;
        $("authorNumber").value = "Author"+ authorcount;  
        $("authorTitle").value = "-";
        authorSaved = false;
        if(corrAuthor){
            $("currCorrAuthor").innerHTML = $("authorName").value + " is the current corresponding author";
            $("currCorrAuthor").style.display = "block";
            $("authorRB").style.display = "none";
        }else{
            $("currCorrAuthor").style.display = "none";
            $("authorRB").style.display = "block";    
        }
    }
}
function getAuthor(author){
    if(!authorSaved){
        alert("the following error(s) occurred:\n-Please save the current author first.");
    } 
    else{
        var arr = authors[author]; 
        $("authorTitle").value = arr["authortitle"];
        $("authorNumber").value = author; 
        $("fname").value = arr["fname"]; 
        $("lname").value= arr["lname"];  
        $("university").value = arr["university"]; 
        $("address").value= arr["address"]; 
        $("postalcode").value= arr["postalcode"];
        $("city").value=arr["city"];
        $("country").value= arr["country"]; 
        $("email").value= arr["email"]; 
        $("confemail").value = arr["email"];
        $("phone").value= arr["phone"];
         if(!corrAuthor){
            $("currCorrAuthor").style.display = "none";
            $("authorRB").style.display = "block";           
         }else{
            if(arr["corresponding"] == "true"){
                $("currCorrAuthor").style.display = "none";
                $("authorRB").style.display = "block";    
                
            }
            if(arr["corresponding"] == "false"){
                $("currCorrAuthor").innerHTML = $("authorName").value + " is the current corresponding author";
                $("currCorrAuthor").style.display = "block";
                $("authorRB").style.display = "none";
            }
         } 
    }
}
function delAuthor(){
    if(confirm("Are you sure you want to delete this author?")){
        if(typeof(authors[$("authorNumber").value]) == "undefined"){
                clear(pages[page][0]);
                $("authorTitle").value = "-"; 
        } else{
            var delAuthor = $("authorNumber").value;
            delete authors[delAuthor];
            $("span"+delAuthor).parentNode.removeChild($("span"+delAuthor));    
            $("authorNumber").value = ""; 
            clear(pages[page][0]); 
            var count = 0;
            for(var i=1;i<(authorcount+1);i++){        
                var arr = authors["Author"+i];
                if(typeof(arr) != "undefined"){
                    count++;    
                } 
            }
            if(count == 0){
                authorSaved = false;
                authorcount = 1; 
            }
        }
    }
}
function getConferenceThemes(){
    
    new Ajax.Request('./submitting/processabstract.php',{
        method:'get',
         parameters: {'function': 'getConferenceThemes'},
        onSuccess: function(transport){
            eval('var themes = new Array("'+transport.responseText+'")');
            processConferenceThemes(themes);
        },
        //@TODO e-mail when something goes wrong!!
        onFailure: function(){}
    });  
}
function processConferenceThemes(array){
        $("conferencetheme1").options[$("conferencetheme1").options.length] = new Option("-", "-");
        $("conferencetheme2").options[$("conferencetheme2").options.length] = new Option("-", "-");
        $("conferencetheme3").options[$("conferencetheme3").options.length] = new Option("-", "-");
    for(var i=0;i<array.length;i++){
        $("conferencetheme1").options[$("conferencetheme1").options.length] = new Option(array[i], array[i]);
        $("conferencetheme2").options[$("conferencetheme2").options.length] = new Option(array[i], array[i]);
        $("conferencetheme3").options[$("conferencetheme3").options.length] = new Option(array[i], array[i]);
    }
}

function clear(id){
    var boxes = $(id).getElementsByTagName("input");
    for(var i =0; i < boxes.length; i++){
        if(boxes[i].type != "hidden"){
            boxes[i].value ="";
        }
    }
}
function nextStep(){
    if(typeof(pages[(page +1)]) !="undefinde"){
        //after function
        if(pages[page][4] !="" && pages[page][4] !=undefined){
            if(!eval(pages[page][4])){
                return false;
            }
        }
        $(pages[page][0]).style.display = "none";
        page++;   
        if(typeof(pages[page +1]) == "undefined"){
            $("next").innerHTML = "finish";
        } 
        
        if(page == pages.length){
            page = (pages.length -1);
        }
        $(pages[page][0]).style.display = "block"; 
        //before function
        if(pages[page][1] !="" && pages[page][1] !=undefined){
            eval(pages[page][1]);
        }
        //title
        $("title").innerHTML = pages[page][2];
        //description
        $("contentPage").innerHTML = pages[page][3];
    }
}
function previousStep(){
    if(page <=0){
        page = 0;
        
    }else{
        $("next").innerHTML = "next";
        $(pages[page][0]).style.display = "none";
        page--;
        if(page <0){
            page = 0;
        }
        $(pages[page][0]).style.display = "block";  
        
        // before function
        if(pages[page][1] !="" && pages[page][1] !=undefined){
            eval(pages[page][1]);
        }
        //title
        $("title").innerHTML = pages[page][2];
        //description
        $("contentPage").innerHTML = pages[page][3];
    }
}
function CountWords (this_field, show_word_count, show_char_count) {
    if (show_word_count == null) {
        show_word_count = false;
    }
    if (show_char_count == null) {
        show_char_count = false;
    }
    var char_count = this_field.value.length;
    var fullStr = this_field.value + " ";
    var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
    var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
    var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
    var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
    var splitString = cleanedStr.split(" ");
    var word_count = splitString.length -1;
    if (fullStr.length <2) {
        word_count = 0;
    }
    if (word_count == 1) {
        wordOrWords = " word";
    }
    else {
        wordOrWords = " words";
    }
    if (char_count == 1) {
        charOrChars = " character";
    } else {
        charOrChars = " characters";
    }
    if (show_word_count & show_char_count) {
        //alert ("Word Count:\n" + "    " + word_count + wordOrWords + "\n" + "    " + char_count + charOrChars);
    }
    else {
        if (show_word_count) {
            return word_count;
            //alert ("Word Count:  " + word_count + wordOrWords);
        }
        else {
            if (show_char_count) {
                return char_count;
                //alert ("Character Count:  " + char_count + charOrChars);
            }
        }
    }
    return word_count;
}
function clearError(el){
    $('errorLabel').innerHTML = "";
    el.style.borderColor="";
}
function onlyLetters(el){
    authorSaved = false;
    if(el.value.match(/[^a-zA-Z ]/g)){
        el.value = el.value.replace(/[^a-zA-Z ]/g,"");
        $('errorLabel').innerHTML = "Only letters (a-z and A-Z) are allowed!";
        el.style.borderColor="red";
        return false;
    }   
    return true;
}
function validLastName(el){
     authorSaved = false;
    if(el.value.match(/[^a-zA-Z -]/g)){
        el.value = el.value.replace(/[^a-zA-Z -]/g,"");
        $('errorLabel').innerHTML = "Only letters and - are allowed!";
        el.style.borderColor="red";
        return false;
    }   
    return true;
}
function onlyLettersAndNumbers(el){
    authorSaved = false;
    if(el.value.match(/[^a-zA-Z0-9 .,\-\+]/g)){
        el.value = el.value.replace(/[^a-zA-Z0-9 .,\- \+]/g,"") ;  
        $('errorLabel').innerHTML = "Only letters, numbers and + - . , are alowed!";
        el.style.borderColor="red";
        return false;
    }
    return true;
}
function validEmail(el){
    authorSaved = false;
    el.value = el.value.replace(/[^a-zA-Z0-9@.\-\_]/g,"");
    var re = new RegExp("^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$");
    if(el.value ==$("confemail").value){
        clearError($("confemail"));
        confMail = true;
    }
    if(el.value.match(re)){
        clearError(el);
        return true;
    }
    $('errorLabel').innerHTML = "The email adress is not valid. Please enter a valid email adress.";
    el.style.borderColor="red";
    return false;
}
function onlyEmailChar(el){
    authorSaved = false;
    if(el.value.match(/[\\'\\" ]/g)){
        el.value = el.value.replace(/[\\' \\" ]/g,"") ;  
        $('errorLabel').innerHTML = "Characters like ' and \" are not allowed";
        el.style.borderColor="red";
        return false;
    }
    return true;
}
function validPhone(el){
    authorSaved = false;
if(el.value.match(/[^0-9 + - ]/g)){
        el.value = el.value.replace(/[^0-9 \+ \- ]/g,"") ;  
        $('errorLabel').innerHTML = "Only letters, numbers and + - are allowed!";
        el.style.borderColor="red";
        return false;
    }
    return true;
}
function confirmEmail(el){
    el.value = el.value.replace(/[^a-zA-Z0-9@.\-\_]/g,"");
    if(el.value !=$("email").value){
        alert("The email adresses are different!");
        confMail = false;
        el.style.borderColor="red";
        return false;
    }
    clearError(el);
    confMail = true;
    return true;   
}
function keywordsCheck(el){
    authorSaved = false;
    if(el.value.match(/[^a-zA-Z, ]/g)){
        el.value = el.value.replace(/[^a-zA-Z, ]/g,"") ;  
        $('errorLabel').innerHTML = "Only letters and a comma are allowed!";
        el.style.borderColor="red";
        return false;
    }
    return true;
}
//@TODO!!
function checkAuthor(){
    if(!authorSaved){
        if(confirm("Are you sure you want to save this author?")){
            if(!saveAuthor())return false;
        }
    }
    if(typeof(window.variables) != "undefined"){
        type = (window.variables['type'] != undefined && window.variables['type'] !="")? window.variables['type'] : ""; 
    }
    var msg="";
    for(var i=1;i<(authorcount+1);i++){
        
        var arr = authors["Author"+i];
        if(typeof(arr) != "undefined"){
        
            if(arr["fname"] =="" && arr["lname"] == "" ){
                msg+="-The first and last name of the Author are empty. \n";    
            }else{
                if(arr["fname"] ==""){
                    msg+="-The first name of the Author is empty. \n";    
                }
                if(arr["lname"] ==""){
                    msg+="-The last name of the Author is empty. \n";    
                }
                if(arr["authortitle"] =="-" ||arr["authortitle"] == ""){
                    msg+="-The title of Author "+arr["fname"]+" "+arr["lname"] +" is empty. \n";    
                }
                if(arr["university"] ==""){
                    msg+="-The university of Author "+arr["fname"]+" "+arr["lname"] +" is empty. \n";    
                }
                if(arr["address"] ==""){
                    msg+="-The address of Author "+arr["fname"]+" "+arr["lname"] +" is empty. \n";    
                }
                if(arr["postalcode"] ==""){
                    msg+="-The zip/postal code of Author "+arr["fname"]+" "+arr["lname"] +" is empty. \n";    
                }
                if(arr["city"] ==""){
                    msg+="-The city of Author "+arr["fname"]+" "+arr["lname"] +" is empty. \n";    
                }
                if(arr["country"] ==""){
                    msg+="-The country of Author "+arr["fname"]+" "+arr["lname"] +" is empty. \n";    
                }
                if(arr["email"] ==""){
                    msg+="-The email adress of Author "+arr["fname"]+" "+arr["lname"] +" is empty. \n";    
                }
                if(arr["phone"] ==""){
                    msg+="-The phone number of Author "+arr["fname"]+" "+arr["lname"] +" is empty. \n";    
                }
            } 
        }   
    }
    if(!corrAuthor){
        msg+="-There must be one author who is the corresponding author.\n";    
    }
    if(msg !=""){
        alert("the following errors occurred:\n" + msg);  
        return false;
    }
    authorSaved = true;
    $('errorLabel').innerHTML = "";
    return true;
}
function checkConferenceThemes(){
    setloading(true);
    if($("conferencetheme1").value != "-"  && $("conferencetheme2").value != "-" && $("conferencetheme3").value != "-"){
        if($("conferencetheme1").value == $("conferencetheme2").value || $("conferencetheme1").value == $("conferencetheme3").value
        || $("conferencetheme2").value == $("conferencetheme3").value ){
            alert("Please select three different conference themes");
            document.getElementById('captcha').src = './includes/securimage/securimage_show.php?' + Math.random();
            setloading(false);
            return false;
        }
        conferencethemes[0] = $("conferencetheme1").options[$("conferencetheme1").selectedIndex].value;
        conferencethemes[1] = $("conferencetheme2").options[$("conferencetheme2").selectedIndex].value;
        conferencethemes[2] = $("conferencetheme3").options[$("conferencetheme3").selectedIndex].value;
    }else{
         alert("the following error(s) occurred:\n-Please select three different conference themes.");   
         document.getElementById('captcha').src = './includes/securimage/securimage_show.php?' + Math.random();
         setloading(false);
         return false;   
    }
    setloading(false);
    $('errorLabel').innerHTML = ""; 
    //return finishAbstract();
    checkCaptcha();
    
}
function checkWords(el){
    var words = CountWords(el,true,false);
    var chars =  CountWords(el,false,true); 
    if(words > 500){
        alert("the following error(s) occurred:\n-The abstract contains too much words. A maximum of 500 words is allowed. Current word count is " +words + " .");
        el.style.borderColor="red";   
        return false;
    } 
    if(chars > 3600){
        alert("the following error(s) occurred:\n-The abstract contains too much characters. A maximum of 3600 characters is allowed. Current character count is " +chars + " .");
        el.style.borderColor="red"; 
        return false;      
    }
    clearError(el);
    return true;
}
function finishAbstract(){
    setloading(true);
    var abstractType = "paper";
    if(type == "doctoral"){
        if( $("radioPaper").checked){
            abstractType = $("radioPaper").value;
        }
        if( $("radioPoster").checked){
            abstractType = $("radioPoster").value;
        }
    }
    var abstractValue =$('abstract').value;
    var titlepaperValue =$('titlePaper').value;
    var keywordValue = $('keywordValues').value;
    var authorString = "";
    for(var i=1;i<(authorcount+1);i++){
        var arr = authors["Author"+i];
        if(typeof(arr) != "undefined"){
            if(authorString == ""){  
                authorString += arr["authortitle"] + "$$";
                authorString +=  arr["fname"]+ "$$"; 
                authorString +=  arr["lname"]+ "$$";  
                authorString +=  arr["university"]+ "$$"; 
                authorString +=  arr["address"]+ "$$"; 
                authorString +=  arr["postalcode"]+ "$$";
                authorString += arr["city"]+ "$$";
                authorString +=  arr["country"]+ "$$"; 
                authorString +=  arr["email"]+ "$$"; 
                authorString +=  arr["phone"] + "$$";
                authorString +=  arr["corresponding"];
            }else{
                authorString += "|";   
                authorString += arr["authortitle"] + "$$";
                authorString +=  arr["fname"]+ "$$"; 
                authorString +=  arr["lname"]+ "$$";  
                authorString +=  arr["university"]+ "$$"; 
                authorString +=  arr["address"]+ "$$"; 
                authorString +=  arr["postalcode"]+ "$$";
                authorString += arr["city"]+ "$$";
                authorString +=  arr["country"]+ "$$"; 
                authorString +=  arr["email"]+ "$$"; 
                authorString +=  arr["phone"] + "$$"; 
                 authorString +=  arr["corresponding"];   
            }
        }
    }
     var conferenceString = conferencethemes[0] +","+conferencethemes[1] +","+conferencethemes[2];
    
     new Ajax.Request('./submitting/processabstract.php',{
        method:'post',
         parameters: {'function':'saveAbstract','authors': authorString,'conferencethemes' : conferenceString,'titlePaper':titlepaperValue,'keywords':keywordValue,'textAbstract' : abstractValue,'abstractType' : abstractType,"type":type},
        onSuccess: function(transport){
            if(transport.responseText == "completed"){
                alert("Your abstract has been submitted succesfully. A confirmation has been sent to your e-mail account.\n Please contact us at info@eres2011.com if you did not get the confirmation email within a day.");
                setloading(false);
            } else{
                alert("Your abstract has not been submitted succesfully. Please contact us at info@eres2011.com and include the following error message: " + transport.responseText);
                setloading(false);    
            }
            loadMenuItem($("home"),"home","Conference 2011","Welcome to Eindhoven, The Netherlands, 15<sup>th</sup>-18<sup>th</sub> June 2011");
        },
        //@TODO e-mail when something goes wrong!!
        onFailure: function(){
            alert("Your abstract has not been submitted succesfully. Please contact us at info@eres2011.com and include the following error message: " + transport.responseText);
            loadMenuItem($("home"),"home","Conference 2011","Welcome to Eindhoven, The Netherlands, 15<sup>th</sup>-18<sup>th</sub> June 2011");
            
        }
    }); 
    return true;
}
function checkAbstract(){
    var words = CountWords($('abstract'),true,false);
    var chars =  CountWords($('abstract'),false,true); 
    
    if(words > 500){
        alert("the following error(s) occurred:\n-The abstract contains too much words. A maximum of 500 words is allowed. Current word count is " +words + " .");
         setloading(false);
         return false;
    }
    if(chars > 3600){
        alert("the following error(s) occurred:\n-The abstract contains too much characters!. A maximum of 3600 characters is allowed. Current character count is " +characters + " .");
         setloading(false);
         return false;
    } 
    if(chars == 0 ){
        alert("the following error(s) occurred:\n-The abstract is empty.");
        setloading(false); 
         return false;    
    }  
    if($('keywordValues').value == ""){
        alert("the following error(s) occurred:\n-There is/are no keyword(s) specified.");
        setloading(false);
        return false;
    }
    if($('titlePaper').value == ""){
        alert("the following error(s) occurred:\n-There is no title specified");
        setloading(false);
        return false;
    }
    $('errorLabel').innerHTML = "";
    return true;
}
function onlyLettersAndNumbersTextArea(el){
    authorSaved = false;
     if(el.value.match(/[\\'\\"]/g)){
        el.value = el.value.replace(/[\\'\\"]/g,"") ;   
        $('errorLabel').innerHTML = "Quotes and double quotes are not allowed!";
        return false;
    }
    return true;
}
function checkType(){
  if(type !=""){
    if(type == "doctoral"){
        $('trType').style.display =  "block";
    }
  }  
}
function checkCaptcha(){
    var code = "";
    if(typeof($('captcha_code').value) !="undefined"){
         code = $('captcha_code').value;
    }
    new Ajax.Request('./submitting/processabstract.php',{
      method:'get',
       parameters: {'function': 'checkCaptcha','code':code},
      onSuccess: function(transport){
        if(transport.responseText == "true"){
            setloading(true);
            finishAbstract();
        
        }else{
            setloading(true);
            alert("the following error(s) occurred:\n -The security code from the security image is not filled in correctly.");
            document.getElementById('captcha').src = './includes/securimage/securimage_show.php?' + Math.random();
            setloading(false);
        }
      },
      //@TODO e-mail when something goes wrong!!
      onFailure: function(){}
    }); 
}
function checkAuthorRB(){
    authorSaved = false;
    if($("radioYes").checked){
        corrAuthor = true;
    }else{
        corrAuthor = false;
        $("authorName").value ="";
    }
}





