﻿var MyNetResearch = {};

MyNetResearch.closeWindow = function(){
    window.close();   
}
MyNetResearch.back = function(){
    window.history.back();
}
MyNetResearch.messages = {};

MyNetResearch.messages.openAddressBook = function(hdnID, btnID) {
    window.open("/MessageCenter/AddressBookPopup.aspx?hdnid="+hdnID+"&btnid="+btnID,"AddressBook","toolbar=0,menubar=0,status=0,scrollbars=1,resizable=0,width=620,height=800");
};
MyNetResearch.messages.openNotes = function(addressBookID) {
    window.open("/MessageCenter/NotesPopup.aspx?AddressBookID="+addressBookID,"Notes","toolbar=0,menubar=0,status=0,scrollbars=0,resizable=0,width=400,height=400");
};
MyNetResearch.messages.openHelp = function() {
    window.open("/Help.aspx","Help","toolbar=0,menubar=0,status=0,scrollbars=1,resizable=1,width=700,height=600");
};
MyNetResearch.messages.openBillingPolicy = function() {
    window.open("/BillingPolicy.aspx","BillingPolicy","toolbar=0,menubar=0,status=0,scrollbars=1,resizable=0,width=400,height=600");
};
MyNetResearch.messages.openUserAgreementPolicy = function() {
    window.open("/UserAgreement.aspx","UserAgreement","toolbar=0,menubar=0,status=0,scrollbars=1,resizable=0,width=400,height=600");
};
MyNetResearch.messages.openAdminUserPromote = function(ResearcherId) {
    var w = window.open("/Admin/AdminUserPromote.aspx?ResearcherID=" + ResearcherId,"AdminPromote","toolbar=0,menubar=0,status=0,scrollbars=0,resizable=1,width=420,height=700");
    w.focus();
};



MyNetResearch.messages.confirmPayment = function(amount, backBtn) {
    var conf = confirm("A charge of " + amount + " will be made to your credit card.\nAre you sure you want to proceed?");
    
    if ( conf === true )
    {
        var btn = document.getElementById(backBtn);
        btn.disabled = true;
    }
    
    return conf;
};

MyNetResearch.messages.clearRecipients = function(){
    var conf = confirm("Are you sure you want to remove all recipients?");
    return conf;
}

MyNetResearch.messages.deactivateResearcher = function(){
    var conf = confirm("Are you sure you want to deactivate the user?");
    return conf;
}

MyNetResearch.messages.activateResearcher = function(){
    var conf = confirm("Are you sure you want to activate the user?");
    return conf;
}

MyNetResearch.messages.demoteResearcher = function() {
    var conf = confirm("Are you sure you want to demote the user?");
    return conf;
};

MyNetResearch.messages.deletionInstitution = function() {
    var conf = confirm("Are you sure you want to deactivate the Institution?\nIf you do so then all the researchers belonging to that" +
                    " institution will be demoted to Regular Accounts.\nThe action of demoting an account will reflect until tomorrow. It is done" + 
                    " by a background job so if the Institution has too many researchers, the changes may not be reflected immediately.");
    return conf;
};

MyNetResearch.messages.activationInstitution = function() {
    var conf = confirm("Are you sure you want to activate the selected Institution?");
    return conf;
};

MyNetResearch.messages.deleteGrant = function() {
    var conf = confirm("Are you sure you want to delete the selected grants?  This operation cannot be undone.");
    return conf;
};

MyNetResearch.messages.quitProject = function() {
    var conf = confirm( "Are you sure you want to quit the project?\n" +
                        "This operation cannot be undone and you will not be able to rejoin the project unless you are re-invited.\n" +
                        "You will also lose access to all files in the project.");
    return conf;
};

MyNetResearch.messages.archiveProject = function() {
    var conf = confirm("Are you sure you want to archive the project?\n This operation cannot be undone. An archived" +
                    " project becomes read-only.");
    return conf;
};


MyNetResearch.messages.deletePatent = function() {
    var conf = confirm("“Are you sure you want to delete the selected patents?  This operation cannot be undone");
    return conf;
};


MyNetResearch.search = {};

MyNetResearch.search.openSaveSearch = function() 
{
    
    window.open("/FindResearcher/SaveSearchPopup.aspx","Save","toolbar=0,menubar=0,status=0,scrollbars=0,resizable=0,width=400,height=220");
};

MyNetResearch.inviteProject = {};

MyNetResearch.inviteProject.openInviteProject = function(researcherID) 
{
    window.open("/MyProfile/InviteToProjectPopUp.aspx?researcherID="+ researcherID,"InviteToProject","toolbar=0,menubar=0,status=0,scrollbars=0,resizable=0,width=600,height=300");
};

MyNetResearch.validator = {};
MyNetResearch.validator.extractNumber = function(obj, decimalPlaces, allowNegative)
{
	var temp = obj.value;
	
	// avoid changing things if already formatted correctly
	var reg0Str = '[0-9]*';
	if (decimalPlaces > 0) {
		reg0Str += '\\.?[0-9]{0,' + decimalPlaces + '}';
	} else if (decimalPlaces < 0) {
		reg0Str += '\\.?[0-9]*';
	}
	reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
	reg0Str = reg0Str + '$';
	var reg0 = new RegExp(reg0Str);
	if (reg0.test(temp)) return true;

	// first replace all non numbers
	var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (allowNegative ? '-' : '') + ']';
	var reg1 = new RegExp(reg1Str, 'g');
	temp = temp.replace(reg1, '');

	if (allowNegative) {
		// replace extra negative
		var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
		var reg2 = /-/g;
		temp = temp.replace(reg2, '');
		if (hasNegative) temp = '-' + temp;
	}
	
	if (decimalPlaces != 0) {
		var reg3 = /\./g;
		var reg3Array = reg3.exec(temp);
		if (reg3Array != null) {
			// keep only first occurrence of .
			//  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
			var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
			reg3Right = reg3Right.replace(reg3, '');
			reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
			temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
		}
	}
	
	obj.value = temp;
};
MyNetResearch.validator.blockNonNumbers = function(obj, e, allowDecimal, allowNegative)
{
	var key;
	var isCtrl = false;
	var keychar;
	var reg;
		
	if(window.event) {
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	else if(e.which) {
		key = e.which;
		isCtrl = e.ctrlKey;
	}
	
	if (isNaN(key)) return true;
	
	keychar = String.fromCharCode(key);
	
	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl)
	{
		return true;
	}

	reg = /\d/;
	var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
	var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
	
	return isFirstN || isFirstD || reg.test(keychar);
};

MyNetResearch.validator.textAreaMaxLengthSlice = function(textarea, maxlength)
{
    var length = textarea.value.length;

    if (length > maxlength)
    {
        textarea.value = textarea.value.slice(0,maxlength);
    }
};

MyNetResearch.validator.textAreaMaxLengthBlock = function(textarea, maxlength)
{
    var length = textarea.value.length;

    if (length > maxlength)
    {
        alert("Text too long. Must be " + maxlength + " characters or less."); 
    }
};

MyNetResearch.validator.ConfirmAction = function(text)
{
    var result = confirm(text);
    return result;
};


MyNetResearch.validator.ConfirmCheckBox = function(tbl, alertMsg, confirmMsg)
{
    var result = false;
    var isChecked = false;
    var cntTable = document.getElementById(tbl);
    
    if ( cntTable && cntTable !== null )
    {
        var chks = cntTable.getElementsByTagName('input');
        
        if ( chks && chks !== null )
        {
            for( var i = 0; i < chks.length; i++ )
            {
                if ( chks[i].type.toLowerCase() === 'checkbox' )
                {
                    if ( chks[i].checked === true )
                    {
                        isChecked = true;
                        break;
                    }
                }
            }
        }
    }    
    
    if ( isChecked === true )
    {
        result = confirm(confirmMsg);
    }
    else
    {
        alert(alertMsg);
    }
    
    
    return result;
};


MyNetResearch.validator.ConfirmClose = function(text)
{
    var result = confirm(text);
    if(result)
    {
        window.close();
    }    
};
MyNetResearch.validator.toggleCheckBoxes =function toggleCheckBoxes(inputID)
{
    var mainCheckBox = document.getElementById(inputID);
    var cntTbl = MyNetResearch.validator.GetContainingTable(mainCheckBox);
    var webpart = cntTbl.parentNode.parentNode;
    
    if(webpart !== null)
    {
        var checkBoxes = webpart.getElementsByTagName("input");
        for (var i = 0; i < checkBoxes.length; i++) 
        { 
            if(checkBoxes[i].type == "checkbox")
                checkBoxes[i].checked = mainCheckBox.checked;
        }
    }
};

MyNetResearch.validator.GetContainingTable = function(chk)
{
    var el = chk;
    var limit = 50;
    var i = 0;
    while( i < limit && el !== null && el.tagName.toLowerCase() !== "table" )
    {
        el = el.parentNode;
        i++;
    }
    
    if ( el.tagName.toLowerCase() === "table" )
        return el;
    
    return null;
};

/*
 * Check all
 */
MyNetResearch.checkall = function(el) {
    var chkboxes = el.parentNode.parentNode.getElementsByTagName("input");
    for(var i=0; i<chkboxes.length; i++) {
        if(chkboxes[i].type === "checkbox") {
            chkboxes[i].checked = true;
        }
    }
};

MyNetResearch.uncheckall = function(el) {
    var chkboxes = el.parentNode.parentNode.getElementsByTagName("input");
    for(var i=0; i<chkboxes.length; i++) {
        if(chkboxes[i].type === "checkbox") {
            chkboxes[i].checked = false;
        }
    }
};
MyNetResearch.timer = {};
MyNetResearch.timer.StartClock = function()
{
    setTimeout('MyNetResearch.timer.UpdateClock()',10);    
};
MyNetResearch.timer.UpdateClock = function()
{
    var container = document.getElementById("spanTime");
    var spanTimer = container.getElementsByTagName("span");
    var spanInputs = container.getElementsByTagName("input");    
    
    var newDate = new Date(spanInputs[0].value);
    var day = newDate.getDate();
    var month = newDate.getMonth()+1;
    var year = newDate.getFullYear();
    var hours = newDate.getHours();
    var minutes = newDate.getMinutes(); 
    
    var anotherDate = new Date();
    var seconds = anotherDate.getSeconds();
    var nextInterval = 60500 - (seconds*1000);
    
    var am_pm;
    var strHours = hours
    if(hours <= 11)
    {
        am_pm = "AM";
    }
    else
    {
        am_pm = "PM";
        if(hours > 12)
        {
            strHours = hours - 12;
        }
    }
    
    var strMinutes = minutes;
    if(minutes <= 9)
        strMinutes = "0"+minutes;
        
    spanTimer[0].innerHTML = "Today is: " + month + "/" + day + "/" + year;    
    spanTimer[2].innerHTML = "Time: " + hours+":"+strMinutes+" "+am_pm +" EST";
    
    if(minutes == 59){
        minutes = 0;
        hours++;
    }
    else
        minutes++;     
        
    var strTime = month+"/"+day+"/"+year+" "+hours+":"+minutes+":"+seconds;
    spanInputs[0].value = strTime;
    
    
        
    setTimeout('MyNetResearch.timer.UpdateClock()',nextInterval);    
};
MyNetResearch.validator.ValidateDate = function(source, args){
    var txt = args.Value;
    var result = false;
    var d = Date.parse(txt);
    if(!isNaN(d))
        result = true;
    else
        result = false;
        
    args.IsValid = result;
};

MyNetResearch.validations = {};
MyNetResearch.validations.email = {};
MyNetResearch.validations.password = {};
MyNetResearch.validations.password.check = function(source, args){
    var str = args.Value;    
    var len = str.length;
    var num = 0;
    var let = 0;
    var sp = 0;
    var result = true;
    var i;
    if(len > 0)
    {
        for(i = 0 ; i < len ; i++)
        {
            if(!isNaN(parseInt(str.charAt(i))))
            {
                num++;
            }
            else
            {
                if(str.charAt(i).toLowerCase() == str.charAt(i).toUpperCase())
                {
                    //Validates it does not has any spaces
                    if(str.charAt(i) == ' ')
                    {
                        result = false;
                        break;
                    }                             
                    sp++;
                }
                else
                {
                    let++;
                }
            }
        }
        var total = num + let + sp;
        if(result && num > 0 && let > 0 && sp > 0 && total >= 6 && total <= 20)
        {
            result = true;
        }
        else{
            result = false;
        }
    }
    else
    {
        result = false;
    }
    
    args.IsValid = result;
};
MyNetResearch.Utils = {};
MyNetResearch.Utils.CheckboxClick = function(chkBox, ID){    
    if(chkBox.checked){
        MyNetResearch.Utils.AddID(ID);
    }
    else{
        MyNetResearch.Utils.RemoveID(ID);
    }
}
MyNetResearch.Utils.AddID = function(ID){
    var inputs = document.getElementsByTagName("input");
    var hdn = null;
    
    for (var i = 0; i < inputs.length; i++)
    {
        if(inputs[i].type == "hidden" && inputs[i].id == "hdnIDs"){
            hdn = inputs[i];
            var ids = hdn.value;
            var newID = ID+",";
    
            hdn.value = ids.concat(newID);
        }
    }   
}
MyNetResearch.Utils.RemoveID = function(ID){
    var inputs = document.getElementsByTagName("input");
    var hdn = null;
    
    for (var i = 0; i < inputs.length; i++)
    {
        if(inputs[i].type == "hidden" && inputs[i].id == "hdnIDs")
        {
            hdn = inputs[i];
            var ids = hdn.value;
            var oldID = ID+",";
    
            hdn.value = ids.replace(oldID,"");            
        }
     }
}
MyNetResearch.Utils.PassInfo = function(parBtnID, parHdnID){
    var inputs = document.getElementsByTagName("input");
    var hdn = null;
    var ids = "";
    
    for (var i = 0; i < inputs.length; i++)
    {
        if(inputs[i].type == "hidden" && inputs[i].id == "hdnIDs")
        {
            hdn = inputs[i];
            ids = hdn.value;
            ids = ids.substring(0, ids.length -1);            
        }
     }
     
    var parentWindow = window.opener;
    
    if ( parentWindow && parentWindow !== null )
    {
        var hdnInput = parentWindow.document.getElementById(parHdnID);
        var btnInput = parentWindow.document.getElementById(parBtnID);

        if ( hdnInput && btnInput && hdnInput !== null && btnInput !== null )
        {
            if ( hdnInput.value.length === 0 )
            {
                //if empty just assign
                hdnInput.value = ids;
            }
            else
            {
                //if already has something, then we concatenate to avoid losing
                //the already selected ids from the parent.
                hdnInput.value = hdnInput.value + "," + ids;
            }

            parentWindow.focus();
            btnInput.click();
        }
    }
    
    window.close();
}

MyNetResearch.Utils.ToggleTab = function(tab) {
    document.getElementById('BasicInfo').style.visibility = 'hidden';
    document.getElementById('Discipline').style.visibility = 'hidden';
    document.getElementById('Organization').style.visibility = 'hidden';
    document.getElementById('Grants').style.visibility = 'hidden';
    document.getElementById('Patents').style.visibility = 'hidden';
    document.getElementById('Journals').style.visibility = 'hidden';

    document.getElementById('BasicInfo').style.display = 'none';
    document.getElementById('Discipline').style.display = 'none';
    document.getElementById('Organization').style.display='none';
    document.getElementById('Grants').style.display='none';
    document.getElementById('Patents').style.display='none';
    document.getElementById('Journals').style.display='none';
     
    var readLayer = document.getElementById(tab);
    readLayer.style.visibility = 'visible';
    readLayer.style.display='block';
}; 
 
 
 
MyNetResearch.Utils.SetUniqueRadioButton = function(nameregex, current){
   var re = new RegExp(nameregex);
   for(i = 0; i < document.forms[0].elements.length; i++)
   {
      elm = document.forms[0].elements[i]
      if (elm.type == 'radio')
      {
         if (re.test(elm.name))
         {
            elm.checked = false;
         }
      }
   }
   current.checked = true;
};

MyNetResearch.Utils.UpdateFile = function(chkBox, ID){    
    var dvFile = document.getElementById(ID);
    if(chkBox.checked){
        dvFile.style.display = 'block';          
    }
    else{
        dvFile.style.display = 'none';
    }
};

MyNetResearch.Utils.ToogleDivs = function(dvHide, dvShow, valDisable, valDisable2, valEnable){    
    var divHide = document.getElementById(dvHide);
    var divShow = document.getElementById(dvShow);
    divShow.style.display = 'block';          
    divHide.style.display = 'none';
    
    var myVal = document.getElementById(valDisable);
    var myVal2 = document.getElementById(valDisable2);
    var myEnableVal = document.getElementById(valEnable);
    myVal.enabled = false;
    myVal2.enabled = false;
    myEnableVal.enabled = true;
    /**myVal.style.visibility = 'hidden';
    myVal2.style.visibility = 'hidden';
    myEnableVal.visibility = 'visible';**/
};

MyNetResearch.Utils.ToogleDivs2 = function(dvHide, dvShow, valEnable, valEnable2, valDisable){    
    var divHide = document.getElementById(dvHide);
    var divShow = document.getElementById(dvShow);
    divShow.style.display = 'block';          
    divHide.style.display = 'none';
    
    var myVal = document.getElementById(valEnable);
    var myVal2 = document.getElementById(valEnable2);
    var myDisableVal = document.getElementById(valDisable);
    myVal.enabled = true;
    myVal2.enabled = true;
    myDisableVal.enabled = false;
    /**myVal.style.visibility = 'visible';
    myVal2.style.visibility = 'visible';
    myDisableVal.visibility = 'hidden';**/
};

MyNetResearch.Calendar = {};

var temp;

MyNetResearch.Calendar.ClientShown = function(sender, args)
{      
    var fn = function() { MyNetResearch.Calendar.TodayDate(sender); };

    sender._nextArrow.onclick =  function()
    {
        MyNetResearch.Calendar.ClearStyle(sender._daysBody.getElementsByTagName("DIV"))
        setTimeout(fn, 100);
    };      
    
    sender._prevArrow.onclick =  function()
    {   
        MyNetResearch.Calendar.ClearStyle(sender._daysBody.getElementsByTagName("DIV"))
        setTimeout(fn, 100);
    };
    
    for(var i=0;i < sender._monthsBody.rows.length; i++)
    {
        var row = sender._monthsBody.rows[i]
        for(var j=0; j < row.cells.length; j++)
        {
            row.cells[j].firstChild.onclick =  function()
            {
                MyNetResearch.Calendar.ClearStyle(sender._daysBody.getElementsByTagName("DIV"))
                setTimeout(fn, 200);
            };
        }
    } 
    
    MyNetResearch.Calendar.TodayDate(sender);              
};   

MyNetResearch.Calendar.TodayDate = function(sender) {      
    var today = new Date();   
    var currentTitle = today.localeFormat("D");  
    var dayDIVs = sender._daysBody.getElementsByTagName("DIV");   
    for (i = 0; i < dayDIVs.length; i++) {    
        if (dayDIVs[i].title == currentTitle) {   
            dayDIVs[i].style.fontWeight = "bold";
        }   
    }
};   

MyNetResearch.Calendar.ClearStyle = function(sender) {
    var dayDIVs = sender;   
    for (i = 0; i < dayDIVs.length; i++) {  
        dayDIVs[i].style.fontWeight = "normal";    
    }   
};
