var review_assessment_done = 0;
function journalSelectCheck(jourId)
{
  
  document.submit.journalId.value=jourId;
  document.submit.next_step.value=1;            
}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
//I modified the regex.
function validateEmail(field) {
    //var regex=/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
    var regex=/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return (regex.test(trim(field))) ? true : false;
}
function validateMultipleEmailsCommaSeparated(value) {
    var result = value.split(" ");
    //alert(result);
   // for(var i = 0;i < result.length;i++)
    if(!validateEmail(value)){
            //alert(value+"f");
            return false;
            
    }
    else{
    // alert(value+"t");                      
    return true;
    }
}
function isExists1(tbid,result){

   var rt=false;
   $('#'+tbid+ ' tr').each(function() {

    var value = this.cells[1].innerHTML;
    if(trim(value)==trim(result)){
        
           rt= true; 
    }

    
   });
   
   return rt;

    
}



 function add_confict(fname,email,aff,notes,id)
 {
        var table = document.getElementById('conflict_tb');
        var rowCount = table.rows.length;

        if(rowCount>0){
           $("#conflictHead").html('<p><b>Below you can find list of proposed conflicting users.</b></p>');
        }


        table.id='conflict_tb'; 
        
        var row = table.insertRow(rowCount);
        row.id='conflict'+rowCount;
        
        row.style.cursor="move";
        row.style.background="#fff"; 
        
        var detail='<span class="suggest">'+fname+'</span><span class="suggest">'+email+'</span><span class="suggest">'+aff+'</span>';
        var note= '<div class="motive">'+notes+'</div>';
        var cell0 = row.insertCell(0);
        cell0.innerHTML='<div style="text-align:left;background:#ddd;padding:5px">'+detail+'</div>'+note;


        var cell1 = row.insertCell(1);
        cell1.style.display="none";
        cell1.innerHTML=email;
        var del='<a href = "#" onClick="return (Delconflict('+rowCount+','+id+'));"><img src="templates/images/delete.gif" title="delete">'+
                                      '</a>';
        var cell4 = row.insertCell(2);
        cell4.innerHTML=del;
        cell4.style.background="#eee";  
        

        $('#cName').val('');
        $('#cEmail').val('');
        $('#cAffiliation').val('');
        $('#cAddititional').val('');

 }


 function add_reviewer(id)
 {
     var direct=$("#suggdirect").val();
     
     if(direct==1){
         var fname=$('#drName').val();
         var email=$('#drEmail').val();
         var aff=$('#drAff').val();
         var notes=$('#drNotes').val();

     }
     else{
         var fname=$('#rName').val();
         var email=$('#rEmail').val();
         var aff=$('#rAffiliation').val();
         var notes=$('#rAddititional').val();
    }
    var table = document.getElementById('propose_tb');
    var rowCount = table.rows.length;
  
    if(rowCount>0){
       $("#proposeHead").html('<p><b>Below you can find list of proposed reviewers.</b></p>');
    }
     
        var table = document.getElementById('propose_tb');
        var rowCount = table.rows.length;
        
        table.id='propose_tb'; 
        
        var row = table.insertRow(rowCount);
        row.id='propose'+rowCount;
        
       
        row.style.cursor="move";
        row.style.background="#fff";

        var detail='<span class="suggest">'+fname+'</span><span class="suggest">'+email+'</span><span class="suggest">'+aff+'</span>';
        var note= '<div class="motive">'+notes+'</div>';
        var cell0 = row.insertCell(0);
        cell0.innerHTML='<div style="text-align:left;background:#ddd;padding:5px">'+detail+'</div>'+note;
        
        
        var cell1 = row.insertCell(1);
        cell1.style.display="none";
        cell1.innerHTML=email;
        var del='<a href = "#" onClick="return (DelPropose('+rowCount+','+id+'));"><img src="templates/images/delete.gif" title="delete">'+
                                         '</a>';
       
        var cell4 = row.insertCell(2);
        cell4.innerHTML=del;
        cell4.style.background="#eee";
       
         $('#rName').val('');
         $('#rEmail').val('');
         $('#rAffiliation').val('');
         $('#rAddititional').val('');
    

 }




function addTobox(){
   // alert("adding");
    var strCU="";
    var strPR="";
    
    $('#conflict_tb tr').each(function() {
     var value = this.cells[0].innerHTML;    
    strCU=strCU+value+",";
   
    });
    
   $("#conflicting_domain").val(strCU);
   
    $('#propose_tb tr').each(function() {
     var value = this.cells[0].innerHTML;    
    strPR=strPR+value+",";
   
    });
    
   $("#proposed_reviewers").val(strPR);
    return true;
}

function reviewDetailAction(v,m,f){
    if(v==0){
        jQuery.prompt.close();
        return false;
    }
    else if (v==1 && (f.rid!='' || f.jid!='' || f.pid!='')){
        validateReview (f.rid,f.jid,f.pid);
        return false;
    }
    else if(v==2){

         var txt = $('#reviewHeader').html()+$('#reviewBody').html();
         var newdiv = document.createElement('div');
         newdiv.setAttribute('id', 'finalPrint');
         newdiv.setAttribute('class', 'divToPrint');
         newdiv.innerHTML ='';
         document.body.appendChild(newdiv);
         $('#finalPrint').hide();

         $('#finalPrint').html(txt);
         $("strong").css("background","#fff");

         $(".divToPrint").jqprint({printContainer: false,operaSupport: true});

    }


}
function reviewAssessment(v,m,f)
{
   loadForjForm('#forj_es_form',$("#jreviewId").val(),$("#jpaperId").val(),$("#juser_role").val());
   return false;
}
function goToReviewAssessmentForm(assessmentWarningMsg,goto_link){
   if(goto_link == 1 || (assessmentWarningMsg == 0)) {
        var review_detail_top = $('#wrap_table').position().top;
        var forj_form_top = $('#forj_es_form').position().top;
        $("#revbody").scrollTop(forj_form_top-review_detail_top);
   }
   return false;

}
function notNow()
{
        jQuery.prompt.close();
        return false;
}
/*This is the function to show the deatil of the review done by user*/
reqUrl='';
var ajaxLoader_html = '<span class="review_validate_loader" style="display:none"><img src="templates/images/ajax-loader.gif" width="15px" height="15px"></span>';
 function showReviewDetail(reviewId,reqURL)
 {
   reqUrl =  reqURL;
   $.getJSON(reqURL, {json:'{"action": "reviewDetail", "params": {"reviewId": "'+ reviewId +'"}}'}, function(resp) {

                     if (resp.status == 1){


                        var len = resp.data.criterionlist.criterion.length;
                        var crit = resp.data.criterionlist.criterion;
                        var total = resp.data.review.score;
                        var author = resp.data.paperAuthor;
                        var title = resp.data.paperTile;
                        var pid = resp.data.paperId;
                        var jid = resp.data.journalId;
                        var pStatus = resp.data.status;
                        var isValidated = resp.data.validate;
                        var isAuthor = resp.data.isAuthor;
                        var isReviewAssessmentAllowed = resp.data.review_assessment_allowed;
                        var isReviewer = resp.data.isReviewer;
                        var user_role = resp.data.user_role;
                       
                        var validationAllowed=0;
                        if(isValidated==0){
                            validationAllowed = resp.data.validateAllowed;

                        }
                        
                        if(pStatus == 'C' || pStatus == 'A' || pStatus == 'R' || pStatus == 'O'){
                            validationAllowed = 0;
                        }
                        var txt1 = '';
                        var txt_reviewassessment = '';
                        review_assessment_done = resp.data.isReviewAssessmnetDone;

                        var reviewRound = resp.data.reviewRound;

                        if(reviewRound>0)review_assessment_done =1;
                      
                        var goto_link = '';
                        if(isReviewAssessmentAllowed == 1)
                            goto_link="<p>You can help us improve the review process by <a href='#' onclick='return goToReviewAssessmentForm("+review_assessment_done+",1);'>rating this review</a></p>";
                        var txt0 ="<div id='reviewHeader'><h2> ..: Summary of the review :.. </h2>" +
                                 "<div style='float:right;color:red'>Total score <br>"+total+"/100</div><div><p> <b>Paper Title: </b>"+title+"<br><b> Authors: </b>"+author+"</p></div></div>"+
                      "<div>"+goto_link+"</div>"+
                      "<div id='revbody' style='height:300px;overflow:auto;border:1px solid'>"+
                      "<input type='hidden' name='jreviewId' id='jreviewId' value="+reviewId+" />"+
                      "<input type='hidden' name='jpaperId' id='jpaperId' value="+pid+" />"+
                      "<input type='hidden' name='juser_role' id='juser_role' value="+user_role+" />"+
                      "<div id='wrap_table'><table id='reviewBody' class='collect'>";

                        for (i=0; i<len;i++)
                        {
                           criTitle = crit[i].name;
                           var criWeight = new Number(crit[i].weight);
                           criWeight = criWeight.toFixed(3);
                           criId = crit[i].id_criterion;
                           selectedVal = new Number (resp.data.review.marks[i].value);
                           selectedVal = selectedVal.toFixed(3);
                           mId = resp.data.review.marks[i].id;
                          
                           part2='';
                           opt = '';
                           opt2 = '';
                           option2 ='';
                           finalOption ='';

                           comment='';
                           comment =  resp.data.review.marks[i].comment;
                           wtFromDb =0;
                           wtFromDb= selectedVal * resp.data.review.marks[i].weight; 
                           wtFromDb = new Number(wtFromDb);
                           wtFromDb = wtFromDb.toFixed(1);
                           
                            txt1  =txt1 +"<tr>"+
                                        "<td><strong>"+criId+". <span style='color:green'>"+criTitle+"</b></span> weight: "+criWeight+"  <span style='color:green;'> weighted mark is </span><span id=wt"+criId+">"+wtFromDb+"</span></strong></td>"+
                                        "</tr>"+
                                        "<tr>"+
                                            "<td><div style='background:#fff'><p style='padding-left:10px'>"+comment+"</p></div><input type='hidden' name='criId[]' id='criId[]' value="+criId+">"+
                                        "</tr>";


                        }
                       var reviewTxt ="<br/><table class='collect' width='100%'>";
                       var reviewCommentsAuthor="<tr><td>Additional comments to the authors:</td></tr>"+
                                "<tr><td><div style='background:#fff'><p style='padding-left:10px'>"+resp.data.commentsToAuthor+"</div></td></tr>";
                       reviewCommentsEditor='';
                       if(!isAuthor==1){

                            var reviewCommentsEditor="<tr><td>Additional comments to the editors:</td></tr>"+
                                "<tr><td><div style='background:#fff'><p style='padding-left:10px'>"+resp.data.commentsToEditor+"</div></td></tr>";
                       }
                       if(isReviewAssessmentAllowed == 1){
                        var txt_reviewassessment_warning = '<div id="reviewassment_warning" class="messageBoxWarning" style="display:none">You have not submitted the rating form for this review.  Rating reviews helps us to ensure a better review process.  You can submit your rating using the form at the bottom of the review page. <a href="#" onclick="return notNow()" style="color:#000;text-decoration: underline;" > Not now</a></div>';
                        var assessment_introduction_msg = '<div class="messageBoxInfo" style="display:block"><p>Help us improve the review process &mdash; please rate this review according to the criteria below.  When you are done click the "Submit" button at the bottom of the form to submit your feedback.</p></div>';
                        txt_reviewassessment = '<div id="forj_es_form"><h2>Review Assessment form</h2><p>'+assessment_introduction_msg+txt_reviewassessment_warning+'</p></div>';
                       }
                        txt2 =  "</table></div>"+reviewTxt+reviewCommentsAuthor+reviewCommentsEditor+"</table>"+txt_reviewassessment+
                                "</div>";
                        txt3 ='';
                        if(validationAllowed == 1){
                            txt3 = "<form><input type='hidden' id='rid' name='rid' value="+reviewId+"><input type='hidden' id='jid' name='jid' value="+jid+"><input type='hidden' id='pid' name='pid' value="+pid+"></form>"

                        }
                       txt = txt0+txt1+txt2+txt3;
                     
              if(validationAllowed == 1){
               showPromptWidth(750, txt,{

                            submit: reviewDetailAction,
                            top : '1%',
                            loaded: reviewAssessment ,
                            buttons:{'Validate':1,'Close':0}
                   });
              }
              else {
                  showPromptWidth(750, txt,{

                            submit: reviewDetailAction,
                            top : '1%',
                            loaded: reviewAssessment ,
                            buttons:{'Print':2,'Close':0}
                   });
              }
        }
        else {
            $.prompt(resp.message);
        }

       });
           return false;
    }
    


function validateReview(rid,jourId,pid)
{
    $("#jqi_state0_buttonValidate").before(ajaxLoader_html);
    $("#review_validate_loader").show();
    es_ajaxLoader("review_validate_loader");
    $("#jqi_state0_buttonValidate").text('Validating....');
    $.getJSON(URLreq, {json:'{"action": "validateReview", "params": {"reviewId": "'+ rid +'","paperId": "'+ pid +'","journalId": "'+ jourId +'"}}'}, function(resp) {
             if (resp.status == 1){
                $("#status"+rid).text('Validated');
                $("#rstatus"+rid).text('Validated');
                $("#review_status_img"+rid).html("<img src='templates/images/bullet_green.png' height='16px' width='16px' title='Submitted and Validated Review'>");
                $("#jqi_state0_buttonValidate").text('Validated');
                $("#jqi_state0_buttonValidate").attr("disabled", true);
                $("#jqi_state0_buttonValidate").css("background", "#ccc");
                if(review_assessment_done == 0)
                     $("#reviewassment_warning").show();
                goToReviewAssessmentForm(review_assessment_done,0);

             }
             else
                 $.prompt(resp.message);
           });

     return false;                       
}
function validateReview1(rid,jourId,pid,reqURL) 
{
    if(reqURL==0){
        reqURL=reqUrl;
    }
     $.getJSON(reqURL, {json:'{"action": "getNumberSubmittedReview", "params": {"reviewId": "'+ rid +'","paperId": "'+ pid +'","journalId": "'+ jourId +'"}}'}, function(resp) {
             if (resp.status == 1){
                 
               var txt ="It seems more than minimum number of reviews required is submitted.Paper will soon goes into decision phase as soon as you validates minimim number of reviews.In order to make sure your required review goes into consideration validate them first then others. Do you want to proceed with this validation? ";
                
                       $.prompt(txt,{ 
                            buttons:{'Validate':true, 'Cancel':false},
                            callback: function(v,m,f) {
                                if(v) {
                                        validateReviewConfirm(rid,jourId,pid,reqURL);
                                } else {return false;}
                            }
                        });  
             }
             else {
                 
                 validateReviewConfirm(rid,jourId,pid,reqURL);
             }
             
         });

     return false;                       
}


function showPromptWidth(width, p_content, p_options)
{
    $.prompt(p_content, p_options);
    var p = $("#jqi");
    var ow = p.width();
   
    // parseFloat makes it work with Chrome (any WebKit based browser)
    var ml = parseFloat(p.css('marginLeft'));
    var delta = ml - ((width-ow)/2);
   
    p.width(width);
    p.css('marginLeft',delta+'px');
    return false;
}
function ValidateURL(url) {
    var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(url)) {
        return false;
    }
    else {
        return true;
    }
} 

function submissionAction(v,m,f){
                             if(v.val == 1){

                                   if(v.action=='paper_ban'){
                                       $(location).attr('href',v.params.url);  
                                   }
                                   else if(v.action=='paper_submit'){
                                      $.getJSON( v.params.reqURL, {json:'{"action": "submitFinal", "params": {"paperId": '+ v.params.pid +'}}'}, function(resp) {
                                              if (resp.status ==1){
                                                $.cookie("accordion_paperList",1,{path:v.params.cookiespath});
                                                var url = v.params.uri+"paper/lists";
                                                $(location).attr('href',url);

                                            }

                                            else {
                                              $.prompt(resp.message);
                                              return false;
                                          }

                                      });

                                      return true;
                                                                          
                                   }
                                   else  if(v.action=='paper_withdraw'){
                                        $(location).attr('href',v.params.url);
                                       
                                   }
                                   else if(v.action=='paper_resubmit'){
                                        $("#frmpaperId").val(v.params.pid);
                                        $.cookie("accordion_paperList",3,{path:v.params.cookiespath});
                                        $("#frmresponse").submit();
                                        return true;

                                   }
                                   else if (v.action=='author_remove'){
                                        $.getJSON( v.params.reqURL, {json:'{"action": "delAuthor", "params": {"authorId": "'+ v.params.authorId +'","subAction": "delete","paperId": "'+v.params.paperId+'"}}'}, function(resp) {
                                            if (resp.status ==1){
                                               // alert("ok");
                                               $('#'+v.params.authorId).remove();
                                            }
                                            else if(resp.status == -1){
                                              
                                              $.prompt(resp.message);
                                              return false;
                                          }
                                         
                                      });
                                      var rowCount = $('#authors_table tr').length;
                                      var rows = document.getElementById('authors_table').getElementsByTagName('tbody')[0].getElementsByTagName('tr');
                                        for (i = 0; i < rows.length; i++) {
                                                 var el = document.getElementById('counter'+rows[i].id);
                                                 el.innerHTML = i+1;
                                        }
                                   }
                                   else if (v.action == 'system_data') {
                                           document.frmAuthorAdd.first_name.value=v.resp.data.fname;
                                           document.frmAuthorAdd.last_name.value=v.resp.data.lname;
                                           document.frmAuthorAdd.email.value=v.params.email.toLowerCase();
                                           document.frmAuthorAdd.affiliation.value=v.resp.data.affiliation;

                                           getNewAuthor(1);
                                       
                                       
                                   }
                                   else if (v.action == 'change_auhtor'){
                                            $.getJSON(v.params.reqURL, {json:'{"action": "setCorrespondingAuthor", "params": {"paperId": "'+ v.params.paperId +'","subAction": "changeCorresponding","oldauthorid": "'+v.params.oldauthorid+'","authorid": "'+v.params.authorid+'"}}'}, function(resp) { 
                                   
                                            if(resp.status == -1){
                                               $.prompt(resp.message);  
                                            }
                                            else {
                                              

                                                 $(location).attr('href',v.params.url);   
                                            }
                                         
                                            
                                        });
                                   }
                                   else if (v.action == 'edit_author_info'){
                                       
                                       if(!$("#popUpForm").valid()){
                                           return false;   
                                       }
                                          $.getJSON(v.params.reqURL, {json:'{"action": "updateAuthorInfo", "params": {"authorId": "'+ v.params.authorid +'","subAction": "edit","fname": "'+f.Fname+'","lname": "'+f.Lname+'","email": "'+f.Email+'","affiliation": "'+f.Aff+'","paperId":"'+v.params.paperId+'"}}'}, function(resp) {
                                          if(resp.status == 1) {
                                               var SPAN = document.getElementById('fname_spam'+v.params.authorid);
                                               SPAN.firstChild.nodeValue=f.Fname;
                                               
                                               var SPAN = document.getElementById('lname_spam'+v.params.authorid);
                                               SPAN.firstChild.nodeValue=f.Lname;
                                               var SPAN = document.getElementById('email_span'+v.params.authorid);
                                               SPAN.firstChild.nodeValue=f.Email;

                                               var SPAN = document.getElementById('aff_spam'+v.params.authorid);
                                               SPAN.firstChild.nodeValue=f.Aff; 
                                          }
                                          else if(resp.status == -1){
                                              
                                              $.prompt(resp.message);
                                          }
                                      });
                                      
                                   }
                                   else if (v.action=='review_submit'){
                                       changeCookieReview(3);
                                       $(location).attr('href',v.params.url);   

                                       
                                   }
                                   else if (v.action=='invitation'){
                                           url=''; 
                                           $.getJSON(v.params.reqURL, {json:'{"action": "invitationAction", "params": {"inviteId": "'+ v.params.id +'","action": "'+ v.params.action +'"}}'}, function(response) {
                                            if (response.status ==1)
                                            {   
                                                 if(v.params.roleId == ROLE_HE && v.params.action == 1){
                                                  $.cookie("cookies_paper_details","decide",{path:v.params.cookiesPath});
                                                   url = v.params.globalPath+"paper/detail/"+v.params.pid;
                                                 } 
                                                 else if (v.params.roleId == ROLE_AE ) {
                                                   url = v.params.globalPath+"home";   
                                                 }
                                                 else if (v.params.roleId == ROLE_REVIEWER && v.params.action == 1) {
                                                     
                                                     $.cookie("accordion_review", 1,{path:v.params.cookiesPath}); 
                                                      url = v.params.globalPath+"paper/review/view";
                                                 }
                                                 else if (v.params.roleId == ROLE_REVIEWER && v.params.action == 2) {
                                                     
                                                         url = v.params.globalPath+"paper/detail/"+v.params.pid;
                                                 }
                                                 else {
                                                     url = v.params.globalPath+"home";
                                                 }
                                                 
                                                
                                                $(location).attr('href',url); 
                                            }else
                                            {
                                               $.prompt (response.message);  
                                            }
                                               
                                          });
                                       
                                   }
                                   return true;
                                }
                                else if (v.val==2){
                                    
                                    if (v.action == 'provided_data'){
                                             document.frmAuthorAdd.first_name.value=v.params.fname;
                                             document.frmAuthorAdd.last_name.value=v.params.lname;
                                             document.frmAuthorAdd.email.value=v.params.email.toLowerCase();
                                             document.frmAuthorAdd.affiliation.value=v.params.affiliation; 
                                             v.params.dataMatched = 1;
                                             $.getJSON(v.params.reqURL, {json:'{"action": "addAuthor", "params": {"paperId": "'+ v.params.paperId +'","subAction": "add","fname": "'+v.params.fname+'","lname": "'+v.params.lname+'","email": "'+v.params.email+'","affiliation": "'+v.params.affiliation+'",,"dataIProvided": "'+v.params.dataMatched+'"}}'}, function(resp) {  

                                             if(resp.status==1) {  
                                              $(location).attr('href',v.params.url);
                                             return false; 
                                             }
                                            });
                                        
                                    }
                                }
                                else {
                                    if(v.action == 'cancel_author_data_not_matched') {
                                         resetNewAuthor();
                                    }
                                    jQuery.prompt.close();
                                    return false;
                                }
                             
    
}
/*
    common confirmation box for submit,withdraw and ban
*/


function Confirmation (h1,h2,detail,buttons,width)
{
    this.heading1 =h1;
    this.heading2=h2;
    this.detail= detail;
    this.buttons=buttons;
    this.width = width ? width : 450;

    this.renderConfirmationBox = function renderConfirmationBox (){
    
            h1="<div  align='center'><h2>..: "+this.heading1+" :..</h2></div>";

            h2="<div class='warning'  align='center'>"+this.heading2+"</div>";
            var len=0;
            
            
            if(this.detail!=null){
                
               if(this.detail['type']=='plainText'){
                   txt=this.detail['data'];
               }
               else if (this.detail['type']=='plainText2'){
                    txt=h1+h2+this.detail['data'];
                   
               }else { 
                    len =this.detail['data'].length; 
                    tableStart="<div><form id='popUpForm' ><table class='dump' width='100%'>";
                    rows='';
                    for(i=0;i<len;i++){
                        
                        row= "<tr><td>"+this.detail['data'][i].label+"</td><td style='font-weight:normal;'>"+this.detail['data'][i].value+"</td></tr>";
                        rows=rows+row;
                    }
                    tableClose="</table></form></div>";
                    txt=h1+h2+tableStart+rows+tableClose;
             }
                
            }
            else {
            txt=h1+h2;
            

            }
            //return txt;
             showPromptWidth(this.width, txt,{
                            submit :submissionAction,
                            buttons:this.buttons
                   });

    }
}      


function getIndexOfTab(){
  var url=($(location).attr('href'));
  var result = url.substring(url.lastIndexOf("?") + 1); 

    switch (result){
        case 'registered':
        case 'pendingBids':
        case 'journalInfo':
                return 0;
                break;
        case "submitted":
        case "newReview":
        case "info":
                return 1;
                break; 
        case "underReview":
        case "savedReview":
        case "authors":
                return 2;
                break;        
        case "waitingDecision":
        case "submittedReview":
        case "reviewer":
                return 3;
                break;
        case "requireRevision":
        case "expireReview":
        case "conflict":
                return 4;
                break; 
                  
        case "accepted":
        case "coverletter":
                return 5;
                break;  
        case "rejected":
        case "upload":
                return 6; 
                break;  
        case "summary":
                return 7;
                break;        
        case "decide":
                return "decide";
                break;  
        case "review":
                return "review";
                break;   
        case "reviewers":
                return "reviewers";
                break; 
        case "bids":
                return "bids";
                break;  
        case "editor":
                return "editor";
                break;    
        case "detail":
                return "detail";
                break;                                        
        default:
                return -1;               
    }
    
    
}
function abstractLenLimit(e,len,min,max){

       if(e.charCode==0){
               len=$("#abstractText").val().length;
        }
       if(len==0){
          $("#lessMin").html('');
        }

        if(len >= min && len <= max) {
            $("#lessMin").html("<span class='minmaxRange'><b>"+len+"</b> characters <br/>");
              $("#aberror1").hide();
                $("#aberror2").hide();
        }
        else if (len < min){
            $("#lessMin").html("<span class='minmaxRange'> <b>"+len+"</b> characters <br/>");


        }
        else if (len >  max){
             $("#lessMin").html("<span class='minmaxRange'><b>"+len+"</b> characters <br/>");
            // var abst =$("#abstractText").val();
            // var str = abst.substring(0, max);
            // $("#abstractText").val(str);
             return false;

        }


}


 function addSuggestion ()
 {
       if($("#frmSuggestR").valid()){

             var fname=$('#rName').val();
             var email=$('#rEmail').val();
             var aff=$('#rAffiliation').val();
             var notes=$('#rAddititional').val();

            var isEx1=isExists1('conflict_tb',email);
            var isEx2=isExists1('propose_tb',email);

            if(isEx1 || isEx2 ){
             $("#errorNotesR").show();
             return false;
            }

            $("#propose_tb").show();
             saveReviewer(fname,email,aff,notes);

            return false;
      }

     else {

         return false;
     }

 }
function addConflicts ()
{
  if($("#frmSuggestC").valid()){

        var email = $('#cEmail').val();
        var cName = $('#cName').val();
        var cAffiliation = $('#cAffiliation').val();
        var cAddititional = $('#cAddititional').val();
        var isEx1=isExists1('conflict_tb',email);
        var isEx2=isExists1('propose_tb',email);

        if(isEx1 || isEx2 ){
         $("#errorNotesC").show();
         return false;
        }

         $("#conflict_tb").show();
        saveConflict(cName,email,cAffiliation,cAddititional);
        return false;
  }

 else {

     return false;
 }

}
     function boxAction(v,m,f){
       var action = f.action;
       if(v==false){
        jQuery.prompt.close();
        return false;
       }
       $("#frmbox").validate({
            highlight: function(element, errorClass) {
                $(element).addClass('validateHighlightError');

              },
           unhighlight: function(element, errorClass) {
                 $(element).removeClass(errorClass);
                 $(element.form).find("label[for=" + element.id + "]")
                                .removeClass(errorClass);
                  $(element).removeClass('validateHighlightError');

              }

       });

        if(v){
            var isEx1=isExists1('conflict_tb',f.rEmail);
            var isEx2=isExists1('propose_tb',f.rEmail);

            if(isEx1 || isEx2 ){
             $("#errorNotes").show();
             return false;
            }

            var x=  $("#frmbox").valid();
            if(x==false){
                return false;
            }
            if(action == 'reviewer'){
                $("#propose_tb").show();
                add_reviewer();
            }
            else {
                  $("#conflict_tb").show();
                add_confict(f.rName,f.rEmail,f.rAffiliation,f.rAddititional);
            }
        }

    }
    function boxReviewerConflicting(action){

        var title = "";
        var heading ="";
        if(action == 'reviewer'){
           // title = "Propose reviewer";
          //  heading ="Please use the form below to enter the details of any recommendations you have for reviewers, providing a reason in each case.";

        }
        else{
          // title = "Propose conflicting user";
           // heading ="Please use the form below to enter the details of any individuals you would like not to review your paper, providing a reason in each case.";
        }
       $("#frmbox").validate();
        var txt="<form id='frmbox' name='frmbox'  method='post' action=''><input type='hidden' name='action' id='action' value="+action+" />"+
                   "<table class='collect' width='100%'>"+
                    "<tr>"+
                        "<td> <font class='critical'>*</font><b>Full Name:</b> </td> <td> <font class='critical'>*</font><b>Email:</b> </td>   <td> <font class='critical'>*</font><b>Affiliation:</b> </td>"+
                    "</tr>"+
                    "<tr>"+
                        "<td><input type='text' name='rName' id='rName' value=''  size='20' class='required' /></td>"+
                        "<td><input type='text' name='rEmail' id='rEmail' value='' size='20'  class='required email' />  </td>"+
                        "<td><input type='text' name='rAffiliation' id='rAffiliation' value='' size='20' class='required' /> </td>"+
                     "</tr>"+
                    "<tr>"+
                    "<td colspan='3'>"+
                        "<b>Reason:</b><br/>"+
                          "<textarea type='text' name='rAddititional' id='rAddititional' value='' cols='70' rows='6' ></textarea>"+
                          "<label id='errorNotes' class='error' style='display: none;'><i>Duplicate entry (entry in the conflicts list and the reviewer list should not be same)</i></label>"+
                     "</td>"+
                    "</tr>"+
                    "</table>"+
                    "<div><input type='submit' class='subbutton3' onclick='return addSuggestion()' value='Add'></div>"+
                    "</form>";

      //   showPromptWidth(650, txt,{

           //     submit :boxAction,
             //   buttons:{'Add':true,'Close':false}
      //   });

         return txt;
    }
     function confirm_msg(paperId,paperTitle,Authors,journal,action,cookiesPath,reqURL,uri)
     {

          var detail = new Array();
         if(action=='submit'){
            h1="Paper submission";
            h2="<div align='left'>Please confirm that you would like to submit your paper</div>";

         
            detail[0] ={label:'Paper',value:paperTitle};
            detail[1] ={label:'Author',value:Authors};
            detail[2] ={label:'Journal',value:journal};
            content['type']='mulitValued';
            content['data']=detail;
            var buttons = {"Submit paper": {val:1,action : 'paper_submit', params:{pid:paperId,cookiespath:cookiesPath,reqURL:reqURL,uri:uri}} , "Cancel": 0};

            confirmationObj = new Confirmation(h1,h2,content,buttons);
            confirmationObj.renderConfirmationBox();
         }
         else if(action == 'withdraw'){

            h1="Paper withdraw";
            h2="Are you sure to withdraw following paper";

          
            detail[0] ={label:'Paper',value:paperTitle};
            detail[1] ={label:'Author',value:Authors};
            detail[2] ={label:'Journal',value:journal};
            content['type']='mulitValued';
            content['data']=detail;
            var url = uri+"paper/withdraw/"+paperId;
            var buttons = {"Withdraw paper": {val:1,action : 'paper_withdraw', params:{url:url}} , "Cancel": 0};

            confirmationObj = new Confirmation(h1,h2,content,buttons);
            confirmationObj.renderConfirmationBox();

         }
         else if(action=='resubmit'){
            h1="Paper submission";
            h2="<div align='left'>Please confirm that you would like to submit this revised version of your paper</div>";

           
            detail[0] ={label:'Paper',value:paperTitle};
            detail[1] ={label:'Author',value:Authors};
            detail[2] ={label:'Journal',value:journal};
            content['type']='mulitValued';
            content['data']=detail;
            var buttons = {"Submit paper": {val:1,action : 'paper_resubmit', params:{pid:paperId,cookiespath:cookiesPath,reqURL:reqURL,uri:uri}} , "Cancel": 0};

            confirmationObj = new Confirmation(h1,h2,content,buttons);
            confirmationObj.renderConfirmationBox();
         }

         return false
    }

function showCoverLetter(paperId)
{
 
   var render = 1; 
   $.getJSON(URLreq, {json:'{"action": "getCoverLetter", "params": {"paperId": "'+ paperId +'","render": "'+ render +'"}}'}, function(resp) {
         if (resp.status == 1){

          var result = resp.data;
          result = '<h2>Cover Letter</h2>'+"<div id=popUpCoverLetter>"+result+"</div>";
           showPromptWidth(500, result);
          // alert(URLreq);
         }

         else {
           $.prompt("<p><img src='templates/images/error.png'/><strong> No cover letter has been provided for this submission.</strong></p>");

         }

     });
            return false;
    return false;
}

function showPromptWidthReview(width, p_content, p_options)
{
    $.prompt(p_content, p_options);
    var p = $("#jqi");
    var ow = p.width();
    var wh = $(window).height(); 
    var oh = p.height();
    if(wh <= oh){
        var h = wh-40;
        var rh = h-210;
        p.height(h);
        $("#startReviewId").css('height',rh+'px');
        $('html').css('height','700');
    }
    else{
        p.height(oh);
        $("#startReviewId").css('height:300px');
    }
    
  
    // parseFloat makes it work with Chrome (any WebKit based browser)
    var ml = parseFloat(p.css('marginLeft'));
    var delta = ml - ((width-ow)/2);
   
    p.width(width);
    p.css('marginLeft',delta+'px');
    return false;
}

function showPromptDecisionWindow(width, p_content, p_options)
{
    $.prompt(p_content, p_options);
    var p = $("#jqi");
    var ow = p.width();
    var wh = $(window).height(); 
    var oh = p.height();
    if(wh <= oh){
        var h = wh-30;
        var rh = h-120;
        p.height(h);
        $(".emailDraft").css('height',rh+'px');
        $('html').css('height','700');
    }
    else{
        p.height(oh);
    }
    
  
    // parseFloat makes it work with Chrome (any WebKit based browser)
    var ml = parseFloat(p.css('marginLeft'));
    var delta = ml - ((width-ow)/2);
   
    p.width(width);
    p.css('marginLeft',delta+'px');
    return false;
}
/* to edit the review*/
function updateWeightedMark (val,id,wt,len)
{
    wtTotal = val * wt;

    $('#wt'+id).html(wtTotal);

    $('#wtText'+id).val(wtTotal);
    var total =0;
    for (i=1;i<=len;i++)
    {
      weight = $('#wt'+i).html();
     // alert(weight);
       total = total + parseFloat(weight);

    }

    $('#totalScroe').html(total);

    $('#totalMarks').val(total);


}

function onSaveSubmit (){


     if($("#frmSaveReview").valid()){
         return true
     }
     else {

          return false;
     }

}
function keyUpCriterion(id)
{
    var str = $("#cri"+id).val();
    var len = str.lenght;
    if(len<50){

         $("#cri"+id).addClass('validateHighlightError');
         $("#errorCri"+id).show();

    }else{
        $("#cri"+id).removeClass('validateHighlightError');
        $("#errorCri"+id).hide();
    }


}

function keyUpAuthorEditor(){
    var min  = 50;
    var commentsToAuthor = $("#commetToAuthors").val();
    var commentsToAuthorLen = commentsToAuthor.length;
    var commentsToEditor = $("#commetToEditors").val();
    var commentsToEditorrLen = commentsToEditor.length;

    if(commentsToAuthorLen<min){
        $("#commetToAuthors").addClass('validateHighlightError');
    }else {
         $("#commetToAuthors").removeClass('validateHighlightError');
    }

    if(commentsToEditorrLen<min){
        $("#commetToEditors").addClass('validateHighlightError');
    }else {
         $("#commetToEditors").removeClass('validateHighlightError');
    }


}
function editReviewBox(reviewId,author,title,pid,action,isAdmin,path)
{
    $.getJSON(URLreq, {json:'{"action": "listCriterion" ,"params": {"reviewId": "'+ reviewId +'"}}'}, function(resp) {


        if (resp.status == 1){


            len = resp.data.criterionlist.criterion.length;
            crit = resp.data.criterionlist.criterion;
            countCri = len;
            if(action == 1) {// for edit


                reviewdetail =  resp.data.review.marks[0].value;
            }
            var total = new Number(resp.data.review.score);
            total = total.toFixed(3);

            var commetToEditors = resp.data.review.commetToEditors;
            var commetToAuthors = resp.data.review.commetToAuthors;
            var txt1 = '';
            txt0 ="<form id='frmSaveReview' name='frmSaveReview' action='review/edit/"+reviewId+"' method='post' ><h2> On this page you can fill a review  </h2>" +
              "<input id='jcookPath' name='jcookPath' type='hidden' value='"+path+"'><p>The review is not immediately submitted when you click Save. You can return to it as many times as needed, an when it is complete it can be submitted by selecting the corresponding action on My Reviews page.</p>"+
                     "<div style='float:right;color:red'>Total score is :<span id='totalScroe'>"+total+"/100</span> </div><div><p><b>Paper Title:</b><a href='paper/detail/"+pid+"'> "+title+"</a> <br> <b>Authors: </b>"+ author+
                     "</p></div> <input type='hidden' name='totalMarks' id='totalMarks' value='"+total+"'><input type='hidden' name='paperId' id='paperId' value="+pid+">"+
                     "<div id='startReviewId' style='height:300px;overflow:auto;border:1px solid'>"+
                      "<table class='collect'>";

            for (i=0; i<len;i++)
            {
               criTitle = crit[i].name;
               var criWeight = new Number(crit[i].weight);
               criWeight = criWeight.toFixed(3);
               criId = crit[i].id_criterion;
               selectedVal = resp.data.review.marks[i].value;
               mId = resp.data.review.marks[i].id;
               //alert(selectedVal);
               part2='';
               opt = '';
               opt2 = '';
               option2 ='';
               finalOption ='';
               option1 ="<input type='hidden' name='marksId"+criId+"' value="+mId+"><select id =marks"+criId+" name=marks"+criId+" onchange='updateWeightedMark(this.value,"+criId+","+criWeight+","+len+")'>" ;
               val =0;
               for (j=0; j<=10;j++) {
                    //finalOption = finalOption + "<option value="+val+" >"+val+"</option>" ;
                    part2 ='';
                    part1 = "<option value='"+val+"'";

                           if(selectedVal== val){

                               part2="selected";
                           }

                    part3= ">"+val+"</option>" ;

                   finalOption = finalOption +part1+part2+part3;


                 val =val+10;
              }
               option3 =   "</select>";

               optionSelect =  option1+finalOption+option3;
               comment='';
               comment =  resp.data.review.marks[i].comment;
               wtFromDb =0;
               wtFromDb= selectedVal * resp.data.review.marks[i].weight;;

                txt1  =txt1 +"<tr>"+
                            "<td> "+criId+". "+optionSelect+" <span style='color:green'>"+criTitle+"</span> weight: "+criWeight+"  <span style='color:green;'><input type='hidden' id=weightText"+criId+" name=weightText"+criId+"  value='"+criWeight+"'>weighted mark is </span><span id=wt"+criId+">"+wtFromDb+"</span><input type='hidden' id=wtText"+criId+" name=wtText"+criId+"  value=''></td>"+
                            "</tr>"+
                            "<tr>"+
                                "<td><textarea  id =cri"+criId+" name = cri"+criId+" cols='78' rows='5' validate='required:true, minlength:50' onKeyUp='keyUpCriterion("+criId+");'>"+comment+"</textarea><input type='hidden' name='criId[]' id='criId[]' value="+criId+">"+
                                "<br/><div id=errorCri"+criId+"  style='display:none;color:red'>Please enter mimimum 50 characters</div></td>"+
                            "</tr>";


            }
            var reviewComments="<br/><table class='collect'>"+
                                "<tr><td>Comments to the authors:</td></tr>"+
                                "<tr><td><textarea id='commetToAuthors' name='commetToAuthors' cols='78' rows='5' validate='required:true, minlength:50' onKeyUp='keyUpAuthorEditor();'>"+commetToAuthors+"</textarea><br/><div id=errorAuthorComment  style='display:none;color:red'>Please enter mimimum 50 characters</div></td></tr>"+
                                "<tr><td>Comments to the editors:</td></tr>"+
                                "<tr><td><textarea id='commetToEditors' name='commetToEditors' cols='78' rows='5' validate='required:true, minlength:50' onKeyUp='keyUpAuthorEditor();'>"+commetToEditors+"</textarea><br/><div id=errorEditorComment  style='display:none;color:red'>Please enter mimimum 50 characters</div></td></tr>"+                                     "</table>";

            txt2 =  "</table>"+reviewComments+
                    "</div><input type='hidden' name='totalComment' value="+len+"><div style='display:none'><input type='submit' id='save' name='save' value='save' > <input type='submit' id='submit' name='submit' value='submit'><input type='hidden' name='action' id='action'></div></form><div id='errorFillAll' style='display:none'><p class='warning'>Please fill all the fields. Scroll down/up to see which fields are missing.</p></div>";
            txt = txt0+txt1+txt2;
            if(isAdmin==0){
            showPromptWidthReview(750, txt,{

                            submit: reviewAction,
                            top : '1%',
                            buttons:{'Save':1,'Submit':2,'Close':0},
                            loaded: function(){resize_review_form();}
                   });
            }
            else {
              showPromptWidthReview(750, txt,{

                            submit: reviewAction,
                            top : '1%',
                            buttons:{'Save':1,'Close':0},
                            loaded: function(){resize_review_form();}
                   });
            }
        }
        else {
            $.prompt(resp.message);
        }

    });

    return false;
}
function changeCookieReview(Index,cookPath){

         var newIndex=Index;
         $.cookie("accordion_review",newIndex,{path:cookPath});
         $.cookie("accordion_review");

}

function reviewAction(v,m,f){
    var  min = 50;
    if(v==0){
        jQuery.prompt.close();
        return false;
    }
    for(i=1;i<=countCri;i++){
        var criStr = $("#cri"+i).val();

        var len = criStr.length;
        if(len<min){
             $("#cri"+i).addClass('validateHighlightError');
             $("#errorCri"+i).show();
             $("#errorFillAll").show();
             return false;
        }
        else{
            $("#cri"+i).removeClass('validateHighlightError');
           $("#errorCri"+i).hide();
        }
      }

    var commentsToAuthor = $("#commetToAuthors").val();
    var commentsToAuthorLen = commentsToAuthor.length;
    var commentsToEditor = $("#commetToEditors").val();
    var commentsToEditorrLen = commentsToEditor.length;

    if(commentsToAuthorLen<min){
        $("#errorAuthorComment").show();
        $("#commetToAuthors").addClass('validateHighlightError');
        $("#errorFillAll").show();
        return false;
    }else{
       $("#commetToAuthors").removeClass('validateHighlightError');
       $("#errorAuthorComment").hide();
    }

   if(commentsToEditorrLen<min){
        $("#errorEditorComment").show();
        $("#commetToEditors").addClass('validateHighlightError');
        $("#errorFillAll").show();
        return false;
    }else {
       $("#commetToEditors").removeClass('validateHighlightError');
       $("#errorEditorComment").hide();
    }

         $("#action").val(v);
         if(v==0)
            jQuery.prompt.close();
         else {

             if(v==1){
                changeCookieReview(2,f.jcookPath);
                $('#save').trigger('click');
             }
             else if(v==2){
                changeCookieReview(3,f.jcookPath);
                $('#submit').trigger('click');
             }
             return true;
         }

        return false;



}
function loadForjForm(elem,reviewId,paperId,roleId){
   var forj_form_id = 51;
   var forj_namspace = 'escripts.escripts-review-assessment';
   Forj.render_form({
                _form:forj_form_id,
                _namespace:forj_namspace,
                _parent:elem,
                _no_redirect:true,
                _validation_error : function(){
                    $("#forj_form_error").show();
                    setTimeout(function(){
                        $("#forj_form_error").fadeOut('fast');
                      }, 3000); 
                },
                 _submit_callback: function(o){ // you can use the data from here
                  $("#forj_assessment_submit").attr("disabled", true);
                  $("#forj_assessment_submit").css("background", "#ccc");
                  var forj_action = $("form.forj-form").attr('action');

                  var forj_data = {
                      action : 'forjSubmit',
                      params : {
                          post_forj_data   : o,
                          post_forj_action : forj_action,
                          reviewId         : reviewId,
                          paperId          : paperId,
                          roleId           : roleId,
                          forj_namspace    : forj_namspace,
                          forj_form_id     : forj_form_id
                      }
                  };
                     $.post(URLreq, { json : forj_data }, function(resp) {
                        if(resp.status == 1){
                             review_assessment_done = 1;
                             $("#forj_es_form").html('');
                             $("#forj_es_form").html('<br/><div class="messageBoxSuccess" style="display:block"><p>Thank you for rating this review &mdash; your feedback helps to ensure a better review process for everyone.</p></div>');
                         }
                         else{
                             $.prompt("Opps there is some problem during submitting the review assessment form!");
                         }

                    });

                 },
                _on_load: function(a)
                {
                    $('ol.radio-choice').each(function(){
                        $(this).after('<div class="clearer"></div>');
                    });
                    $('span.field-label').each(function(index) {
                      var question = $(this);
                      var nq = question.html();
                      nq = nq.replace(":","?");
                      question.html(nq);
                    });
                    $('div.form-input').each(function(index) {
                        var q = $(this);
                        q.find('label.radio-field input').each(function(i,e){
                            var str = $(e).parent().text();
                            var ss = $(e).parent().text();
                            ss = jQuery.trim(ss.toString());
                            var sl = ss.length;
                            var regEx = /^[0-9]+/;
                            var m = str.match(regEx);
                            var v = 0;
                            var t = str;
                            if(m!=null){
                                v = m[0];
                                $(e).attr('value', v);
                            }else {
                                 $(e).attr('value', str);
                            }
                            t = t.replace(regEx, '');
                            $(e).after('<br/>');
                            $(e).before(i+1+'<br/>');
                            var h = $(e).parent().html();
                            var hlen = h.length;
                            var x = '';
                            if(m!=null)
                               x = h.substr(0,hlen-sl) + t ;
                            else
                               x = h.replace(str,t);

                            $(e).parent().html(x);

                        });


                    });
                    var submit_button = $('div.form-input').last().next();
                    submit_button.val('Submit ratings');
                    submit_button.addClass('subbutton3');
                    submit_button.attr("id", "forj_assessment_submit");
                    submit_button.attr("onClick", "return es_ajaxLoader('review_validate_loader')");
                    submit_button.wrap('<div id="review_assessment" />');
                    var subbutton = $("#review_assessment").html();
                    var form_validation_error = '<span id="forj_form_error"  style="display:none; color:#9F092B">The form contains errors. Please review it and submit again.</span>';
                    $("#review_assessment").html(subbutton+ajaxLoader_html+form_validation_error);
                }
            });
}

function es_ajaxLoader(element){
        $('.'+element)
        .hide()  // hide it initially
        .ajaxStart(function() {
            $(this).show();
        })
        .ajaxStop(function() {
            $(this).hide();
     });
}
function ban_paper(id, title,author,journal){

    h1="Ban paper";
    h2="Are you sure to ban following paper";

    var detail = new Array();
    detail[0] ={label:'Paper',value:title};
    detail[1] ={label:'Author',value:author};
    detail[2] ={label:'Journal',value:journal};
    content['type']='mulitValued';
    content['data']=detail;
    var url = URI_STRING+"paper/ban/"+id;
    var buttons = { "Paper Ban": {val:1,action : 'paper_ban', params:{url:url}} , "Cancel": 0 };

    confirmationObj = new Confirmation(h1,h2,content,buttons);
    confirmationObj.renderConfirmationBox();
    return false;

 }

// to resize the review form
function resize_review_form(){
        var h = $('#jqi').height();
        $('#jqi')
             .resizable({
                    stop: function(e, ui) {
                       var diff =  ui.size.width - ui.originalSize.width;
                       var w_tarea =  $("textarea").width();
                       var tw= w_tarea+diff;
                       $("textarea").css("width",tw);
                    },
                 minHeight: h,
                 maxHeight:h,
                 minWidth:400
         });
}
