var xmlHttp
var g_rtn = null
function fireMyPopup() {
  	var scrolledX, scrolledY;
	if( self.pageYOffset ) {
	  scrolledX = self.pageXOffset;
	  scrolledY = self.pageYOffset;
	} else if( document.documentElement && document.documentElement.scrollTop ) {
	  scrolledX = document.documentElement.scrollLeft;
	  scrolledY = document.documentElement.scrollTop;
	} else if( document.body ) {
	  scrolledX = document.body.scrollLeft;
	  scrolledY = document.body.scrollTop;
	}
	
	// Determine the coordinates of the center of the page
	
	var centerX, centerY;
	if( self.innerHeight ) {
	  centerX = self.innerWidth;
	  centerY = self.innerHeight;
	} else if( document.documentElement && document.documentElement.clientHeight ) {
	  centerX = document.documentElement.clientWidth;
	  centerY = document.documentElement.clientHeight;
	} else if( document.body ) {
	  centerX = document.body.clientWidth;
	  centerY = document.body.clientHeight;
	}
	
	
	var leftOffset = scrolledX + (centerX - 350) / 2;
	var topOffset = scrolledY + (centerY - 300) / 2;

	document.getElementById("popup").style.top = topOffset + "px";
	document.getElementById("popup").style.left = leftOffset + "px";
	document.getElementById("popup").style.display = "block";
}

function closeMyPopup() {
	document.getElementById("popup").style.display = "none";
	document.getElementById("popup").innerHTML = "";
}

function resetPasscode(id) { 
	xmlHttp=GetXmlHttpObject();
	
	if (xmlHttp==null) {
	  alert ("Your browser does not support AJAX!");
	  return;
	} 
	
	var url="merchresetpasscode.php?id=" + id;
	
	xmlHttp.onreadystatechange=function() {
		stateChanged('passcode');
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function resetPassword(id) { 
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    }

    var url="merchresetaccountpw.php?id=" + id + "&cache=" + new Date().getTime();
    xmlHttp.onreadystatechange=function() {
        stateChanged(id);
    }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

function changeDuedate(id, date) { 
	var text = "New Date: <input type=\"text\" name=\"date\" value=\"" + date + "\"/><input type=\"hidden\" name=\"id\" value=\"" + id + "\"/><input type=\"submit\" value=\"Set Date\"/>";
	document.getElementById(id).innerHTML = text;
}

function checkLogin() { 
    g_rtn = "";
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert("Your browser does not support AJAX!");
        return;
    } 
    var url="include/checklogin_inc.php?ajaxCheck=1" + "&cache=" + new Date().getTime();
	
    xmlHttp.open("GET",url,false);
    xmlHttp.send(null);
    
    if (xmlHttp.responseText == 1) {
        return true;
    } else {
        return false;
    }
}

function updateDuedate(form) {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }

    var RegExPattern = /^(?=\d)(?:(?:(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})|(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))|(?:(?:0?[1-9])|(?:1[0-2]))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2}))($|\ (?=\d)))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\ [AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$/;
    var errorMessage = 'Please enter valid date as month, day, and four digit year.\nYou may use a slash, hyphen or period to separate the values.\nThe date must be a real date. 2-30-2000 would not be accepted.\nFormat mm/dd/yyyy.';
			
    if (form.date.value.match(RegExPattern) && (form.date.value != "")){
    	//Submitted date
        var date = new Date(form.date.value);
        var mon = date.getMonth() + 1;
        var getdate = date.getFullYear()+"-"+mon+"-"+date.getDate();
        
        //Today's date
        var curDate = new Date();
        var curMonth = curDate.getMonth() + 1;
        
        if(date < curDate){
        	alert ("The due date cannot be on or before today's date.");
            return false;
        }
        
        //Task creation date
        var dtCreated = new Date(form.dateCreated.value);
        var createdMonMax = dtCreated.getMonth() + 3;
        dtCreated.setMonth(createdMonMax);
        var dispMonth = dtCreated.getMonth() + 1;
        var maxDate = dispMonth +"/" + dtCreated.getDate() +"/"+dtCreated.getFullYear()+".";

        if(date > dtCreated){
        	alert ("The maximum due date is " + maxDate);
            return false;
        }
	
        xmlHttp=GetXmlHttpObject();
        if (xmlHttp==null) {
            alert ("Your browser does not support AJAX!");
            return false;
        } 
        var url = "surveyupdateduedate.php?id=" + form.id.value + "&date=" + getdate + "&cache=" + new Date().getTime();
        xmlHttp.onreadystatechange=function() {
            stateChanged(form.id.value);
        }
        xmlHttp.open("GET",url,true);
        xmlHttp.send(null);
    } else {
        alert(errorMessage);
        form.date.focus;
    }	
	
    return false; 
}

function surveyGoInit(stid, recert) { 
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }

    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var url="surveyreturn.php?id=" + stid + "&init=1&recert_flag="+ recert + "&cache=" + new Date().getTime();
    xmlHttp.open("GET",url,false);
    xmlHttp.send(null);

    if (xmlHttp.responseText == "ERROR") {
    	location.replace("error.php");
        return false;
    }

    document.getElementById("survey").innerHTML = xmlHttp.responseText;
    return false;
}

function surveyBack(stid, recert) {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }

    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var url="surveyback.php?id=" + stid + "&recert_flag="+ recert +"&cache=" + new Date().getTime();
    xmlHttp.onreadystatechange=function() {
        if (xmlHttp.readyState==4) {
            rtn=xmlHttp.responseText;
            if (xmlHttp.responseText == "ERROR") {
                alert("There was an error going back, please logout and try again.");
            } else {
                location.replace("take.php?id=" + stid);
            }	
        }
    }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);	
}

function surveySkip(stid, recert) {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }

    var xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    }
    var url="surveyskip.php?id=" + stid + "&recert_flag="+ recert + "&cache=" + new Date().getTime();
    xmlHttp.onreadystatechange=function()
    {
        if (xmlHttp.readyState==4) {
            if (xmlHttp.responseText == "ERROR") {
                alert("There was an error skipping, please logout and try again.");
            } else {
                location.replace("take.php?id=" + stid);
            }
        }
    }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

function surveyGlossary(id, stid) {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }

    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var url="glossary.php?id=" + id + "&stid=" + stid + "&cache=" + new Date().getTime();
    xmlHttp.onreadystatechange=function() {
        stateChanged("popup");
    }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
    fireMyPopup();
}

function surveyHelp(id, stid) {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }
		
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var url="help.php?id=" + id + "&stid=" + stid + "&cache=" + new Date().getTime();
    xmlHttp.onreadystatechange=function() {
        stateChanged("popup");
    }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
    fireMyPopup();
}

function aiComplete(stid, saaiid) {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }

    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var url="aicomplete.php?id=" + saaiid;
    xmlHttp.open("GET",url,false);
    xmlHttp.send(null);
    if (xmlHttp.responseText == "ERROR") {
        alert("There was an error marking this Action Item complete, please logout and try again.");
    } else if(xmlHttp.responseText == "needScanVendor"){
    	document.getElementById("link"+saaiid).innerHTML = '<span class="error">The PCI ToolKit must receive notice of your passing scan before you can complete this item.  Please return to the Home page and register for your scan.  You can complete this item as soon as your system or computer passes the scan. </span>';
    }
    else {
    	window.location.replace('remainingtasks.php?id='+ stid);
    }
}

function confirmSurvey(form) {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }
    
    if (form.attestName.value == '' || form.attestTitle.value == '') {
        alert("You must enter in your name and title.");	
        return false;
    }
    
    if (!form.confirmed.checked) {
        alert("You must check that you confirm these items.");	
        return false;
    }
    
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    }

    var url="surveyconfirm.php?stid=" + form.id.value +"&attestTitle=" + form.attestTitle.value + "&attestName=" +form.attestName.value;
    xmlHttp.open("GET",url,false);
    xmlHttp.send(null);

    if (xmlHttp.responseText == "ERROR") {
        alert("There was an error confirming this survey, please logout and try again.");
    } else {
    	window.location.replace('dashboard.php');
    }
    return false;
}

function spConfirm(form) {
	
	var answer1 = new Array(); 
	var answer2 = new Array();
	
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }
    
    a = document.getElementsByName("answer1[]");
	var p = 0;
	var count1 = 0;
	for(i=0; i < a.length; i++){
		if(a[i].checked){
			answer1[count1] = a[i].value;
			p = 1;
			count1++;
		}
	}
	if (p == 0){
		alert('You must select at least one service that was included.');
		return false;
	}
	
	var answer1string = answer1.join(", "); 
	
	b = document.getElementsByName("answer2[]");
	var q = 0;
	var count2 = 0;
	for(i=0 ; i < b.length; i++){
		if(b[i].checked){
			answer2[count2] = b[i].value;
			q = 1;
			count2++;
		}
	}
	if (q == 0){
		alert('You must select at least one service that was NOT included.');
		return false;
	}
	
	var answer2string = answer2.join(", "); 
	
    
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    }

    var url="spconfirm.php?stid=" + form.surveytakerID.value +"&included=" + answer1string + "&notincluded=" + answer2string;
    xmlHttp.open("GET",url,false);
    xmlHttp.send(null);

    if (xmlHttp.responseText == "ERROR") {
        alert("There was an error confirming this survey, please logout and try again.");
    } else {
    	window.location.replace("remainingtasks.php?id=" + form.surveytakerID.value);
    }
    return false;
}

function startGroupChange(form){
	
    var group="";
    
    for(var i = 0; i < form.group.length; i++) {
        if(form.group[i].checked) {
            group = form.group[i].value;
        }
    }
    
    if (group == "refresh") {
        window.location.reload();
        return false;
    }

    var cfm	= true;
    
    if (group=="askC") {
        groupCompare = "3";
    } else if (group=="askD") {
        groupCompare = "6";
    } else {
        groupCompare = group;
    }
    
    if (form.recert_flag.value==1 && groupCompare!=form.old_group.value) {
        cfm = false;
        cfm = confirm('You have chosen a different group for recertifcation. If you choose a new group for your recertification interview, you will need to start with a blank interview. Would you like to proceed with this group change?');
    }
    
    if (cfm == true) {
        xmlHttp=GetXmlHttpObject();
        if (xmlHttp==null) {
            alert ("Your browser does not support AJAX!");
            return;
        } 
        var url = "modgroupconfirm.php?group=" + group + "&oldgroup="+ form.old_group.value + "&id=" + form.id.value + "&recert=" + form.recert_flag.value + "&headerLoc=" + form.headerLoc.value + "&cache=" + new Date().getTime();
        xmlHttp.open("GET",url,false);
        xmlHttp.send(null);
        stateChanged("groupform",xmlHttp);
        return false;
    }
}

function loginchange(type) {
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
        alert ("Your browser does not support AJAX!");
        return;
    } 
    var url="loginchange.php?type=" + type + "&cache=" + new Date().getTime();
    xmlHttp.onreadystatechange=function() {
        stateChanged('login');
    }
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

function stateChanged(input) { 
    if (xmlHttp.readyState==4) { 	
        document.getElementById(input).innerHTML=xmlHttp.responseText;
    }
}

function GetXmlHttpObject() {
    var xmlHttp=null;
    try {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    } catch (e) {
        // Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

function populateUsername() {
	var a = document.getElementById("email").value;
	document.getElementById("username").value = a;
}

function submitScanDataLink() {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }

    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert ("Your browser does not support AJAX!");
        return;
    }
	
    var stid = document.getElementById("stid").value;
    var scanner = document.getElementById("scanner").value;
    var scandate = document.getElementById("scandate").value;
    var scanresult = document.getElementById("scanresult").value;
    var nextscandate = document.getElementById("nextscandate").value;

    var url="Endpoints/saveScanInfo.php?scanner=" + scanner + "&scandate="
        + scandate + "&scanresult=" + scanresult + "&nextscandate=" +
        nextscandate + "&stid=" + stid;
		
    var validScanDate = checkscandate(scandate);
		
    if(validScanDate) {
        xmlHttp.open("GET",url, false);
        xmlHttp.send(null);
        response = xmlHttp.responseText;
        
        if (response == "ERROR") {
            alert("Please fill the fields marked with *.");
        } else {
        	window.location.replace('dashboard.php');
        }
    }
}

function submitCgCredentials() {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }

    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert ("Your browser does not support AJAX!");
        return;
    } 
		
    var email1 = document.getElementById("email1").value;
    var email2 = document.getElementById("email2").value;
		
    var password1 = document.getElementById("password1").value;
		
    if (email1 != email2) {
        return;
    }
    var merchantNumber = document.getElementById("merchantnumber").value;
    
    var surveytakerID = document.getElementById("stid").value;
    
    var url="Endpoints/boardToCG.php?email=" 
    + email1 + "&pssw=" + password1 + "&stid=" + surveytakerID;
    
    xmlHttp.open("GET",url, false);
    xmlHttp.send(null);
    response = xmlHttp.responseText;
    
    document.getElementById("cgCredentialsResult").innerHTML = response;
    document.getElementById("credentials_form").innerHTML = "";
}

function changeScanAnswer() {
    if (!checkLogin()) {
        window.location.replace('logout.php');
        return false;
    }

    var stid = document.getElementById("stid").value;
    var cid = document.getElementById("cid").value;
    var email = document.getElementById("email").value;
    
    xmlHttp = GetXmlHttpObject();
    if (xmlHttp == null) {
        alert ("Your browser does not support AJAX!");
        return;
    }
		
    var url="Endpoints/changeScanAnswer.php?stid=" + stid + "&cid=" + cid + "&email=" + email;
				
    xmlHttp.open("GET",url, false);
    xmlHttp.send(null);

    window.location="dashboard.php";
}

function displaySAQCertificateLinks(stid, datecompleted, isCSClient) {
	
	var text = "<p><a href=\"#\" onclick=\"javascript:window.open('saqprint.php?id=" + stid +
			"', 'barWindow', 'width=800,toolbar=0, location=0, directories=0, status=0,menubar=0, scrollbars=1, resizable=1')\">View your SAQ</a></p>";
			
	if(!isCSClient) {
		text += "<p><a href=\"../compliancePdf/generateReport.php?datecomp="+datecompleted+"&id="+stid+"\">Get Compliance Certificate</a></p>";
	}
	
	return text;
}

function verifyAttestCheckbox() {
		
		if(document.attest_check.confirmed.checked == true) {
			document.attest_check.submit();
		} else {		

			alert ('You must attest that the information is true by clicking the checkbox above before continuing.');
		}
}

function checkdate(input){
	var validformat = /^\d{2}\/\d{2}\/\d{4}$/;
	
    if (!validformat.test(input)) {
        alert("Invalid Date Format. Please correct and submit again.");
        return;
    }	

    var monthfield=input.split("/")[0];
    var dayfield=input.split("/")[1];
    var yearfield=input.split("/")[2];
    var dayobj = new Date();
    
    var currentYear = dayobj.getFullYear();
    var currentMonth = dayobj.getMonth();
    currentMonth++;
    var currentDay = dayobj.getDate();
    
    if (
        (yearfield>currentYear) || 
        ((yearfield==currentYear) && (monthfield>currentMonth)) ||
        ((yearfield==currentYear) && (monthfield==currentMonth) && (dayfield>currentDay))
        ) {
        alert("Date cannot be greater than today's date.");
    } else {
        return true;
    }
    return false;
}

function chooseAcc() {
	var selectedOption = document.getElementById("accountSelect").value;

	if(selectedOption != "none") {
		document.getElementById("username").value = selectedOption;
	} else {
		var merchantNum = document.getElementById("merchantNum").value;
		var currenturl = document.location.href;
		var tokenizedUrl = currenturl.split("/");
		var linkurl = tokenizedUrl[0] + tokenizedUrl[1] + "//" + tokenizedUrl[2] + "/" + tokenizedUrl[3] + "/contactSupportNotLogged.php";
		
		document.getElementById("emailSupport").innerHTML = "If you don't recognize any of these as" + ' your username please contact support by clicking <a href="'+ linkurl +'?merchantNum='+merchantNum+'&iso='+tokenizedUrl[3]+'"> this link.</a>';
	}
}

function qsaChange(show)
{
	if (show == 'hide')
		document.getElementById('qsaDetails').style.display="none";
	else
		document.getElementById('qsaDetails').style.display="";
}

function ValidateCompanyProfile()
{
	var passed = true;
	if (document.getElementsByName("prcsname").value == '')
		passed = false;
	else if (document.getElementsByName("name").value == '')
		passed = false;
	else if (document.getElementById("hasqsaYes").checked == false && document.getElementById("hasqsaNo").checked == false)
		passed = false;
	if (!passed)
		alert("You must fill out all of the required fields.");
	return passed;
}

function checkscandate(input){
	var validformat = /^\d{2}\/\d{2}\/\d{4}$/;
	
    if (!validformat.test(input)) {
        alert("Invalid Date Format. Please correct and submit again.");
        return;
    }	

    var monthfield=input.split("/")[0];
    var dayfield=input.split("/")[1];
    var yearfield=input.split("/")[2];
    var dayobj = new Date();
   
    var currentYear = dayobj.getFullYear();
    var currentMonth = dayobj.getMonth();
    currentMonth++;
    var currentDay = dayobj.getDate();
    
    var dayobjExpired = new Date();
    var dayobjEntered = new Date();
    
    dayobjExpired.setYear(currentYear);
    dayobjExpired.setMonth(currentMonth - 4);
    dayobjExpired.setDate(currentDay);
    
    dayobjEntered.setYear(yearfield);
    dayobjEntered.setMonth(monthfield - 1);
    dayobjEntered.setDate(dayfield);

    if (
        (yearfield>currentYear) || 
        ((yearfield==currentYear) && (monthfield>currentMonth)) ||
        ((yearfield==currentYear) && (monthfield==currentMonth) && (dayfield>currentDay))
        ) {
        alert("Date cannot be greater than today's date.");
    } 
    else if (dayobjEntered < dayobjExpired){
    	alert("Scan date must be within the last three months.");
    }
    else {
        return true;
    }
    
    return false;
}

