﻿// JS Document
// Author: tnewton@rosettamarketing.com

var racDataString; // compiled data path string

// Init error message constants
var racShowErrors = [];

var racErrorContainer; // error msg container obj
var racErrorContainerId = "formError"; // id of error msg container

var tmpFirstNameValue;
var tmpLastNameValue;
var tmpEmailValue;
var tmpTelephoneValue;
var tmpContactTimeValue;
var tmpBornMonthValue;
var tmpBornYearValue;
var tmpGenderValue;
var tmpRefOfficeId;
var tmpRefInstId;
var tmpRefDeptId;
var tmpRefPhysId;


/* Request a call form - validation and submission
--------------------------------------------------------------------*/
function checkRequestForm(objID) {
    var numErrors = 0;
    var goConfirmEmail = true; // assume compare email addresses = true for now
    var tmpRefPhysWebsite = null;
    racErrorContainer  = document.getElementById(racErrorContainerId);
    if (objID >= Locator.Config.resultLimit){
        tmpRefOfficeId = tierResults[objID - Locator.Config.resultLimit].returnId();
        tmpRefInstId = tierResults[objID - Locator.Config.resultLimit].officeInstitutionId;
        tmpRefDeptId = tierResults[objID - Locator.Config.resultLimit].officeDeptId;
        tmpRefPhysId = tierResults[objID - Locator.Config.resultLimit].physicianId;
        tmpRefPhysWebsite = tierResults[objID - Locator.Config.resultLimit].officeWeb;
	tmpRefOfficeEmail = tierResults[objID - Locator.Config.resultLimit].officeEmail;
    } else {
        tmpRefOfficeId = clinicResults[objID].returnId();
        tmpRefInstId = clinicResults[objID].officeInstitutionId;
        tmpRefDeptId = clinicResults[objID].officeDeptId;
        tmpRefPhysId = clinicResults[objID].physicianId;
        tmpRefPhysWebsite = clinicResults[objID].officeWeb;
	tmpRefOfficeEmail = clinicResults[objID].officeEmail;
    }
    resetRacForm(); // reset
	// email, confirm email, and telephone targets    

    
    tmpTelephoneValue = stripSpaces(document.getElementById("telephone").value);
    document.getElementById("telephone").value = tmpTelephoneValue;
    var tmpTelephoneLabel = document.getElementById("label_telephone");
    var tmpTelephoneField = document.getElementById("telephone");

	var tmpConfirmEmailValue = stripSpaces(document.getElementById("confirmemail").value);
    var tmpConfirmEmailLabel = document.getElementById("label_confirmemail");
    var tmpConfirmEmailField = document.getElementById("confirmemail");

	tmpEmailValue = stripSpaces(document.getElementById("email").value);
    var tmpEmailLabel = document.getElementById("label_email");
    var tmpEmailField = document.getElementById("email");

	// Validate Telephone Field
    if (!validatePhone(tmpTelephoneValue) || tmpTelephoneValue == "") {
		// only show error if email field is blank
		if(tmpEmailValue == "") {
        	numErrors += 1;
        	showErrorField(tmpTelephoneLabel, tmpTelephoneField, true);
		}
    }

	// Validate Email field 
    if (!validateEmail(tmpEmailValue)) {
		//only show error and validate if telephone field is blank
		if(tmpTelephoneValue == "") {
	        numErrors += 1;
	        // racShowErrors.push(1); // Uncomment to display error message
	        showErrorField(tmpEmailLabel, tmpEmailField, true);
	        goConfirmEmail = false;
		}
    }    

    // Validate Confirm Email field
    if (!validateEmail(tmpConfirmEmailValue)) {
		//only show error and validate if telephone field is blank
		if(tmpTelephoneValue == "") {
	        numErrors += 1;
	        // racShowErrors.push(2); // Uncomment to display error message
	        showErrorField(tmpConfirmEmailLabel, tmpConfirmEmailField, true);
	        goConfirmEmail = false;
		}
    }
    
    // Validate Last Name field is not blank
    tmpLastNameValue = stripSpaces(document.getElementById("lname").value);
    var tmpLastNameLabel = document.getElementById("label_lname");
    var tmpLastNameField = document.getElementById("lname");
    if (tmpLastNameValue == "") {
        numErrors += 1;
        showErrorField(tmpLastNameLabel, tmpLastNameField, true);
    }
    
    // Validate First Name field is not blank
   tmpFirstNameValue = stripSpaces(document.getElementById("fname").value);
    var tmpFirstNameLabel = document.getElementById("label_fname");
    var tmpFirstNameField = document.getElementById("fname");
    if (tmpFirstNameValue == "") {
        numErrors += 1;
        showErrorField(tmpFirstNameLabel, tmpFirstNameField, true);
    }
    
    // Check that email and confirm email fields are identical
	// this fires only if both email and confirm email are not blank AND
	// both are valid email address format
    if (goConfirmEmail) {
        if (tmpEmailValue != tmpConfirmEmailValue) {
            numErrors += 1;
            racShowErrors.push(3);
            showErrorField(tmpEmailLabel, tmpEmailField, true);
            showErrorField(tmpConfirmEmailLabel);
        }
    }
    
    // Validate Contact Time Selected
    var tmpContactTime = document.getElementById("contacttime");
    var tmpContactTimeLabel = document.getElementById("label_contacttime");
    tmpContactTimeValue = tmpContactTime.options[tmpContactTime.selectedIndex].value;
    if (tmpContactTime.selectedIndex == 0) {
        numErrors += 1;
        showErrorField(tmpContactTimeLabel);
    }
    /* Validate Birth Year Selected
     * LEGACY AS OF 16wk CR
    var tmpBornYear = document.getElementById("yearborn");
    var tmpBornLabel = document.getElementById("label_born");
    tmpBornYearValue = tmpBornYear.options[tmpBornYear.selectedIndex].value;
    if (tmpBornYear.selectedIndex == 0) {
        numErrors += 1;
        showErrorField(tmpBornLabel);
    }*/
    /* Validate Gender Selected
     * LEGACY AS OF 16wk CR
    var tmpGender = document.getElementById("gender");
    var tmpGenderLabel = document.getElementById("label_gender");
    tmpGenderValue = tmpGender.options[tmpGender.selectedIndex].value;
    if (tmpGender.selectedIndex == 0) {
        numErrors += 1;
        showErrorField(tmpGenderLabel);
    }*/
    
    
    if (numErrors > 0) {
        racShowErrors.push(0);
        showErrorMessages();
    } else {
        // all data valid, send to server
        var tmpsubmit = document.getElementById("racSubmit");
        tmpsubmit.style.background = "url('/Style%20Library/images/btn_loading.gif')";
        tmpsubmit.style.width = "77px";
        tmpsubmit.style.height = "21px";
        tmpsubmit.style.cursor = "normal";
        racSendDataStart();
        if(Locator.Config.enableTracking){ 
        	scAjaxEvent(Locator.Config.scConsultationSubmitted, Locator.Config.scEvarEmail, tmpRefOfficeEmail, Locator.Config.scEvarAccountNumber, tmpRefDeptId );
        } //capture SC event click
    }
}


// displays requested error messages above the form
function showErrorMessages() {
    racErrorContainer.innerHTML = ""; // reset any prev msg area text
    racErrorContainer.style.height = "auto";
    var tmpErrorString = "";
    document.getElementById("mapOverlayContentArea").scrollTop = 0;
    for(i=0;i<racShowErrors.length;i++) {
        tmpErrorString += (Locator.Config.racForm.errorMessages[racShowErrors[i]] + "<br />");
    }
    racErrorContainer.innerHTML = tmpErrorString;
}
// highlights error field label and/or sets focus/select on specified field
function showErrorField(tmpLabel, tmpField, setFieldFocus) {
    tmpLabel.className = "fieldLabel fieldError";
    if (tmpField && setFieldFocus) {
        tmpField.focus();
        tmpField.select();
    }
}

// RegEx validate email address
function validateEmail(tmpEmailAddress) {
	var validator = new ROSETTA.forms.validation();
	return validator.validateEmail(tmpEmailAddress);
}

// RegEx validate telephone
function validatePhone(str) {
	var tmpRegEx = /^\+?\d+\s?\d+\s?\d+\s?\d+$/; 
	if (tmpRegEx.test(str)) {
   		return true;
 	} else {
 		return false;
 	}
}


// strip leading/trailing whitespaces from string
function stripSpaces(tmpString) {
    var returnVal = (tmpString.replace(/^\s+/,'')).replace(/\W+$/,'');
    return returnVal;
} 
// removes all spaces from a string
function noSpace(str) {
    var tstring = "";
    str = '' + str;
    splitstring = str.split(" ");
    for (n=0;n<splitstring.length;n++) {
        tstring += splitstring[n];
    }
    return tstring;
}
// resets form/error msgs etc
function resetRacForm() {
    resetErrorLabels(); // reset form field label classes
    racShowErrors.length = 0; // reset error messages array
    racErrorContainer.innerHTML = ""; // reset msg area
    racErrorContainer.style.height = "0px";
    
}
// reset error labels
function resetErrorLabels() {
    var tmpFormDivs = document.getElementById("mapOverlayContentArea").getElementsByTagName("div");
    for (j=0;j<tmpFormDivs.length;j++) {
        if (tmpFormDivs[j].className == "fieldLabel fieldError") {
            tmpFormDivs[j].className = "fieldLabel";
        }
    }
}

// build string to send to server
function racSendDataStart() {
    racDataString = Locator.Config.racbaseDataPath;
    
    var tmpQueryParams = [];
    var tmpSid = YAHOO.util.Cookie.get("sessionId");
    if(Locator.getUrlParam("sessionid")){
        tmpSid = Locator.getUrlParam("sessionid");
    }

	// set fake email and or telephone values if they dont exist
	var emailValToSend = escape(tmpEmailValue);
	var phoneValToSend = escape(noSpace(tmpTelephoneValue));
	if(emailValToSend == "") {
		emailValToSend = "NULL";
	}
	if(phoneValToSend == "") {
		phoneValToSend = "NULL";
	}

    tmpQueryParams[0] = "?sessionid=" + tmpSid;
    tmpQueryParams[1] = "&fname=" + escape(tmpFirstNameValue);
    tmpQueryParams[2] = "&lname=" + escape(tmpLastNameValue);
    tmpQueryParams[3] = "&email=" + emailValToSend;
    tmpQueryParams[4] = "&telephone=" + phoneValToSend;
    tmpQueryParams[5] = "&contacttime=" + tmpContactTimeValue;
    tmpQueryParams[6] = "&yearborn=" + tmpBornYearValue;
    tmpQueryParams[7] = "&gender=" + tmpGenderValue;
    
    // Process checkboxes
    var tmpFacialQuestions = [];
    var tmpProductQuestions = [];
    var tmpBreastQuestions = [];
    
    var tmpFormInputs = document.getElementById("requestCallForm").getElementsByTagName("input"); 
    for (k=0;k<tmpFormInputs.length;k++) {
        if (tmpFormInputs[k].type == "checkbox" && tmpFormInputs[k].checked == true) {
            if (tmpFormInputs[k].name == "Facial") {
                tmpFacialQuestions.push(tmpFormInputs[k].id);
            } else if (tmpFormInputs[k].name == "Breast") {
            // question is breast (ouch) checkbox.id carries question text
                tmpBreastQuestions.push(escape(tmpFormInputs[k].id));
            } else if (tmpFormInputs[k].name == "Products") {
            // question is breast (ouch) checkbox.id carries question text
                tmpProductQuestions.push(escape(tmpFormInputs[k].id));
            }
        }
    }
    if (tmpFacialQuestions.length > 0) {
        tmpQueryParams.push("&facial=" + tmpFacialQuestions.join("|"));
    }
    if (tmpBreastQuestions.length > 0) {
        tmpQueryParams.push("&breast=" + tmpBreastQuestions.join("|"));
    }
    if (tmpProductQuestions.length > 0) {
        tmpQueryParams.push("&products=" + tmpProductQuestions.join("|"));
    }

    
    // append dept, phys, and inst id params
    tmpQueryParams.push("&institutionId=" + tmpRefInstId, "&departmentId=" + tmpRefDeptId, "&physicianId=" + tmpRefPhysId);
    
    // append all query param strings to url
    for (l=0;l<tmpQueryParams.length;l++) {
        racDataString += tmpQueryParams[l];
    }
    // do ajax request with compiled url
    sendRacData(racDataString);
    
    // output to screen for debugging
    // document.getElementById(debugDivId).innerHTML = racDataString;
}

function sendRacData(tmpUrl) {
    //document.getElementById("debug").innerHTML = tmpUrl;
    GDownloadUrl(tmpUrl, function(data, responseCode) {
        if (responseCode == 200) {
            if (data.indexOf("success") >= 0) {
                showReponsePanel(true);
            } else {
                showReponsePanel(false);
            }
        } else {
            showReponsePanel(false);
        }
    });
   
    
}

function showReponsePanel(suc) {
    // Clear the current overlay content container to make way for the new content
    var tmpOverlayContainer = document.getElementById('mapOverlayContentArea');
    Locator.clearContainer(tmpOverlayContainer);
    // tmpRefOfficeId is officeid of object
    var tmpDisplayName = clinicResults[tmpRefOfficeId].showDisplayName();
    
    var racResponseDiv = document.createElement("div");
    racResponseDiv.id = "racResponse";
    
    if (suc) {
        var racResponseHeadline1 = document.createElement("h1");
        var racResponseHeadline1Text = document.createTextNode(Locator.Config.racForm.labelResponseHeadline);
        racResponseHeadline1.appendChild(racResponseHeadline1Text);
        
        var racResponseHeadline2 = document.createElement("h2");
        var racResponseHeadline2Text = document.createTextNode(tmpDisplayName);
        racResponseHeadline2.appendChild(racResponseHeadline2Text);
        
        var racResponseCopy = document.createElement("span");
        racResponseCopy.className = "copy";
        var racResponseCopyText = document.createTextNode(Locator.Config.racForm.labelResponseMessage.replace(/DISPLAYNAME/, tmpDisplayName));
        racResponseCopy.appendChild(racResponseCopyText);
        
        //create a hidden div via dom to output the server reponse page to for sc purposes
        var tmpDiv = document.createElement("div");
        tmpDiv.style.visibility = "hidden";
        tmpDiv.style.position = "absolute";
        //alert(r);
            
        //Media tracking tags
        var trackingImg = document.createElement("img");
        trackingImg.width = "1";
        trackingImg.height = "1";
        trackingImg.style.position = "absolute";
        trackingImg.style.left = "-10000";
        trackingImg.src = "http://switch.atdmt.com/action/umcall_080718submissionoftherequestacallform_1";
        tmpDiv.appendChild(trackingImg);
        racResponseDiv.appendChild(tmpDiv);
        
        //Track rac success event
		//if(Locator.Config.enableTracking) {
        	//s.events = "event12";
        	//void(s.t());
        	//s.events = "";
		//}
    } else {
        var racResponseHeadline1 = document.createElement("h1");
        var racResponseHeadline1Text = document.createTextNode(Locator.Config.racForm.labelNegResponseHeadline);
        racResponseHeadline1.appendChild(racResponseHeadline1Text);
        
        var racResponseHeadline2 = document.createElement("h2");
        var racResponseHeadline2Text = document.createTextNode(Locator.Config.racForm.labelNegResponseHeadline2);
        racResponseHeadline2.appendChild(racResponseHeadline2Text);
        
        var racResponseCopy = document.createElement("span");
        racResponseCopy.className = "copy";
        var racResponseCopyText = document.createTextNode(Locator.Config.racForm.labelNegResponseMessage);
        racResponseCopy.appendChild(racResponseCopyText);
    
    }
    var racResponseLink = document.createElement("a");
    racResponseLink.href = "javascript: Locator.closeMapOverlay();";
    var racResponseLinkText = document.createTextNode(Locator.Config.racForm.labelNegResponseReturn);
    racResponseLink.appendChild(racResponseLinkText);
    
    racResponseDiv.appendChild(racResponseHeadline1);
    racResponseDiv.appendChild(racResponseHeadline2);
    racResponseDiv.appendChild(racResponseCopy);
    racResponseDiv.appendChild(racResponseLink);
    
    tmpOverlayContainer.appendChild(racResponseDiv);   
}
