//misc
var preloadFlag = false;

//FUNCTIONS START
function changeImages()	{
	if (document.images && (preloadFlag == true)){
		for (var i=0; i<changeImages.arguments.length; i+=2){
			document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
		}
	}
}

function imgOn (imgName){
	if (document.images)
		document[imgName].src = eval(imgName + "on.src");
}

function imgOff (imgName){
	if (document.images)
		document[imgName].src = eval(imgName + "off.src");
}

function SubmitTopNav(form)
{
	var url = form.selContactLens.options[form.selContactLens.selectedIndex].value;
	if (url.length > 0) {
		document.location.href= url;		//form.submit();
	}
}

function setDefaultFocus()
{
	if (!document.getElementById) return;
	if (!document.forms[0]) return;
	
	try
	{
		for(var f = 0; f < document.forms.length; ++f)
		{
			var frm = document.forms[f];
			
				for(var e = 0; e < frm.elements.length; ++e)
				{
					var fld = frm.elements[e];
					if(fld.type == "hidden")
						continue;
					else if(fld.tabIndex <= 0)
						continue;
					else if(fld.getAttribute("nodefaultfocus") != null)
						continue;
					else if(fld.value.length >0)
						continue;
					else
					{
						fld.focus();
						return;
					}
				}
		}
	}
	catch(ex)
	{
		return;
	}
}

function areTheseElementsFilled()
{
	for(var i=0; i<arguments.length; ++i)
	{
		var arg = arguments[i];
		if(arg.value.length == 0)
		{
			var szMsg = arg.getAttribute("empty_msg");
			if(szMsg == null)
				szMsg = arg.form.getAttribute("empty_msg");
			if(szMsg != null) alert(szMsg);
			arg.focus();
			return false;
		}
	}
	return true;
}

// ####################################
// SHOPPING CART...
// ####################################
function submitCartPlaceOrder(p_szDitac, p_szTrx) {
	document.frmRecalc.ditac.value = p_szDitac;
	document.frmRecalc.trx.value = p_szTrx;

	document.frmRecalc.submit();
	if (document.frmAutoReorder) {
		document.frmAutoReorder.submit();
	}
}

// ####################################
// FIND MY DOCTOR FORM....
// ####################################

var _doctorSearch;

function InitDoctorSearch()
{
	try
	{
		_doctorSearch = new DoctorSearch();
		_doctorSearch.Init(new DoctorSearchConfig());
	}
	catch(e)
	{}
}

function DoctorSearch()
{
	this.Init = function(config)
	{
		this.Config = config;
		this.WireEvents();
	}
	
	this.WireEvents = function()
	{
		var searchButton = this.GetSearchForDoctorButtonElement();
		attachEventListener(searchButton, "click", onSearchForDoctorClick);
	}
	
	this.Submit = function()
	{
		var formName = this.GetFormName();
		if(formName)
		{
			document.forms[this.Config.FormName].submit();
		}
	}
	
	this.Validate = function()
	{
		var okToSubmit = false;
		var cityElement = this.GetSearchCityElement();
		var stateElement = this.GetSearchStateElement();
		if(formElementIsEmpty(cityElement) || formElementIsEmpty(stateElement))
		{
			alert("To search, you must provide a city and state. Please enter them and try again.");
		}
		else
		{
			var searchForDoctorElement = this.GetSearchForDoctorElement();
			if(searchForDoctorElement)
			{
				searchForDoctorElement.value = "True";
				okToSubmit = true;
			}
		}
		
		var searchButtonClickedElement = this.GetSearchButtonClickedElement();
		if(searchButtonClickedElement)
		{
			searchButtonClickedElement.value = "True";
		}
		
		return okToSubmit;
	}
	
	this.GetFormName = function()
	{
		var formName = this.Config.FormName;
		return formName;
	}
	
	this.GetSearchForDoctorButtonElement = function()
	{
		var searchForDoctorButtonElement = document.getElementById(this.Config.SearchForDoctorButtonId);
		return searchForDoctorButtonElement;
	}
	
	this.GetSearchCityElement = function()
	{
		var searchCityElement = document.getElementById(this.Config.SearchCityId);
		return searchCityElement;
	}
	
	this.GetSearchStateElement = function()
	{
		var searchStateElement = document.getElementById(this.Config.SearchStateId);
		return searchStateElement;
	}
	
	this.GetSearchForDoctorElement = function()
	{
		var searchForDoctorElement = document.getElementById(this.Config.SearchForDoctorId);
		return searchForDoctorElement;
	}
	
	this.GetSearchButtonClickedElement = function()
	{
		var searchForDoctorButtonClicked = document.getElementById(this.Config.SearchForDoctorButtonClicked);
		return searchForDoctorButtonClicked;
	}
}

function onSearchForDoctorClick()
{
	if(_doctorSearch != undefined && _doctorSearch != null)
	{
		if(_doctorSearch.Validate())
		{
			_doctorSearch.Submit();
		}
	}
}

function formElementIsEmpty(p_oElement) {
	var l_f = true;
	if (p_oElement != null) {
		var l_szValue = Trim(p_oElement.value);
		if (l_szValue.length > 0) {
			l_f = false;
		}
	}
	return l_f;
}

function validatePhoneNumber(elementValue)
{
    var phoneNumberPattern = /^([0-9]( |-)?( |.)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?( |.)?([0-9]{3}( |-)?( |.)?[0-9]{4}|[a-zA-Z0-9]{7})$/;
	return phoneNumberPattern.test(elementValue);
}

// for applying the doctor information from the previous page to the current page
function copyPreviousDrInfo() {
	document.CLPINFO.txtDoctorName.value = document.CLPINFO.txtPreviousDoctorName.value;
	document.CLPINFO.txtDoctorPhone.value = document.CLPINFO.txtPreviousDoctorPhone.value;
}

// for selecting the informaton from the Doctor Search results
function updateParent(p_szName, p_szPhone) {
	document.CLPINFO.txtDoctorName.value = p_szName;
	document.CLPINFO.txtDoctorPhone.value = p_szPhone;

	var l_checkboxSameDoc = document.CLPINFO.cbPrevDr;
	if (l_checkboxSameDoc != null) {
		l_checkboxSameDoc.checked = false;
	}

	// reload the page to the "Find My Doctor" anchor
	document.location = document.location.toString();
}

// STRING TRIMMING FUNCIONS (http://www.apriori-it.co.uk/Trim.asp)
function Trim(TRIM_VALUE){
	if(TRIM_VALUE == undefined)
	{
		return "";
	}
	if(TRIM_VALUE.length < 1) {
		return "";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if (TRIM_VALUE==""){
		return "";
	}
	else{
		return TRIM_VALUE;
	}
}
function RTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0) {
		return "";
	}
	var iTemp = v_length -1;

	while (iTemp > -1) {
		if (VALUE.charAt(iTemp) == w_space) {
		}
		else {
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	}
	return strTemp;
}
function LTrim(VALUE){
	var w_space = String.fromCharCode(32);
	if (v_length < 1){
		return "";
	}
	var v_length = VALUE.length;
	var strTemp = "";
	var iTemp = 0;
	while(iTemp < v_length) {
		if (VALUE.charAt(iTemp) == w_space) {
		}
		else {
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	}
	return strTemp;
}

// <Bill Me Later functionality>

// Select Credit Card as the payment type
function selectPaymentTypeCC(p_nTypeCC)
{
	document.getElementById('paymentmethod').value = p_nTypeCC;

	// reset the credit card fields - there is the case where the customer hits the back button and could see the BML info
	if (document.getElementById('txtCCNumber').value == '5049990000000000' || document.getElementById('selCCType').value == '12')
	{
		var l_oCCTypes = document.getElementById('selCCType');
		var l_oCCOption;
		for(var i = 0; i < l_oCCTypes.childNodes.length; i++)
		{
			l_oCCOption = l_oCCTypes.childNodes[i];
			if (i == 0)
			{
				l_oCCOption.setAttribute('selected', 'selected');
			}
			else
			{
				l_oCCOption.setAttribute('selected', '');
			}
		}

		setDropdownValue('selCCExpMonth', 0);								// The first month from the month dropdown
		setDropdownValue('selCCExpYear', 0);								// The first year from the expiration year dropdown

		document.getElementById('txtCCNumber').value = '';
		document.getElementById('txtCCNameOnCard').value = '';
	}

	// show credit card fields
	toggleVisibleContent('dvCreditcard', true);

	// show the billing address form
	toggleVisibleContent('dvBillAddress', true);

	// hide BML
	toggleVisibleContent('dvBML', false);

	// hide PayPal
	toggleVisibleContent('dvPayPal', false);
}

// Select Bill Me Later as the payment type
function selectPaymentTypeBML(p_nTypeBML)
{
	document.getElementById('paymentmethod').value = p_nTypeBML;

	// hide credit card fields
	toggleVisibleContent('dvCreditcard', false);

	// show the billing address form
	toggleVisibleContent('dvBillAddress', true);

	// show BML
	toggleVisibleContent('dvBML', true);

	// hide PayPal
	toggleVisibleContent('dvPayPal', false);
}

function selectPaymentTypePayPal(TypePayPal)
{
    document.getElementById('paymentmethod').value = TypePayPal;

    // hide credit card fields
    toggleVisibleContent('dvCreditcard', false);

    // show the billing address form
    toggleVisibleContent('dvBillAddress', true);

    // hide BML
    toggleVisibleContent('dvBML', false);

    // show PayPal
    toggleVisibleContent('dvPayPal', true);
}

// switch UI from the enabled version of the button to the disabled version
function fnUseThisCardDisable() {
    toggleVisibleContent('btnAddCC', false);
    toggleVisibleContent('btnAddCCDisabled', true);
}
// when customer submits payment information
function doPaymentSubmit(p_oForm) {
    // required for Address Verification Service (AVS), these forms need this value set to 'true'...
    var l_oAVS;
    for (var k = 0; k < document.forms.length; k++) {
        l_oAVS = document.forms[k].jsenabled;
        if (l_oAVS != null) {
            l_oAVS.value = 'true';
        }
    }

    var l_fBMLChecked = false;
    var l_fPayPalChecked = false;
    for (i = 0; i < p_oForm.paymentmethod.length; i++) {
        if (p_oForm.paymentmethod[i].checked) {
            switch (p_oForm.paymentmethod[i].value) {
                case '11':
                    l_fBMLChecked = true;
                    break;
                case '12':
                    l_fPayPalChecked = true;
                    break;
            }
        }
    }

    // For Bill Me Later or PayPal, update the credit card fields appropriately.
    // Note: this has to be done on submit, because doing earlier risks getting wiped out by Google toolbar and the like...
    if (l_fBMLChecked || l_fPayPalChecked) {
        // Deselect whatever credit card type they may have previously selected...
        var l_oCCTypes = document.getElementById('selCCType');
        var l_oCCOption;
        for (var i = 0; i < l_oCCTypes.childNodes.length; i++) {
            l_oCCOption = l_oCCTypes.childNodes[i];
            l_oCCOption.setAttribute('selected', '');
        }

        if (l_fBMLChecked) {
           
            // Add Bill Me Later as a credit card type to the dropdown, and select it...
            var optionBML = document.createElement('option');
            optionBML.setAttribute('value', '11');
            optionBML.setAttribute('selected', 'selected');
            optionBML.innerHTML = 'Bill Me Later'
            l_oCCTypes.appendChild(optionBML);

            // Select the first month from the month dropdown, and the last year from the expiration year dropdown...
            setDropdownValue('selCCExpMonth', 0);
            setDropdownValue('selCCExpYear', -1);

            // Enter the official Bill Me Later credit card number...
            document.getElementById('txtCCNumber').value = '5049990000000000';

            // Enter the official name on the Bill Me Later credit card...
            document.getElementById('txtCCNameOnCard').value = 'Bill Me Later';
        }

        if (l_fPayPalChecked) //PayPal
        {
            // Add PayPal as a credit card type to the dropdown, and select it...
            var optionPPL = document.createElement('option');
            optionPPL.setAttribute('value', '12');
            optionPPL.setAttribute('selected', 'selected');
            optionPPL.innerHTML = 'PayPal';
            l_oCCTypes.appendChild(optionPPL);

            if (document.getElementById('txtCCNumber').value.length == 0 && document.getElementById('txtCCNameOnCard').value.length == 0 ) 
            {
                // Enter the PayPal credit card number...
                document.getElementById('txtCCNumber').value = document.getElementById('hdnPayPalPayerID').value;
                // Enter the name on the PayPal credit card...
                document.getElementById('txtCCNameOnCard').value = document.getElementById('hdnPayPalName').value;
            }            
        }
        // Select the first month from the month dropdown, and the last year from the expiration year dropdown...
        setDropdownValue('selCCExpMonth', 0);
        setDropdownValue('selCCExpYear', -1);
    }
}


// hide or unhide a given block of content
function toggleVisibleContent(p_szID, p_fShow)
{
	var l_oElement = document.getElementById(p_szID);
	
	if (l_oElement != null)
	{
		if (p_fShow == true)
		{
			l_oElement.style.visibility = 'visible';
			l_oElement.style.display = 'block';
		}
		else
		{
			l_oElement.style.visibility = 'hidden';
			l_oElement.style.display = 'none';
		}
	}
}

//***********************************************************************************************************
//Function Name	:	getDropdownValue
//Purpose		:	To retrieve either the first or the last value in a dropdown form field.
//Prameters		:	p_szElementID	- the element ID
//					p_nOrdinal		- if -1, get the last; otherwise get the value of this ordinal
//***********************************************************************************************************
// TODO -- 1. verify that it IS a dropdown, 2. verify the length
function getDropdownValue(p_szElementID, p_nOrdinal)
{
	var l_sz;
	l_sz = '';

	var l_oElement;	
	l_oElement = document.getElementById(p_szElementID)

	if (l_oElement != null)
	{
		if (p_nOrdinal >= 0)
		{
			l_sz = l_oElement.options[p_nOrdinal].value;
		}
		else
		{
			l_sz = l_oElement.options[l_oElement.length - 1].value;
		}
	}

	return l_sz;
}

function setDropdownValue(p_szElementID, p_nOrdinal)
{
	var l_oElement;
	l_oElement = document.getElementById(p_szElementID)

	if (l_oElement != null)
	{
		l_oElement.value = getDropdownValue(p_szElementID, p_nOrdinal);
	}
}

// IVD has different forms surrounding the place order buttin, so we need to capture the user selection and pass through as a hidden field...
function handle90DayCheckboxOnPlaceOrder(p_oCheckbox, bRequiresReAuth)
{
    var l_oHiddenField;
    var bResponse;
    if (bRequiresReAuth) {
        bResponse = confirm("You have selected the BillMeLater option which requires you to re-authenticate with BillMeLater. Would you like to continue?");
    } 
    else {
        bResponse = true;
    }
    for (var k = 0; k < document.forms.length; k++) {
        l_oHiddenField = document.forms[k].elements[p_oCheckbox.name];
        if (l_oHiddenField != null) {
            //Commented the below line since uniqueID doesnot work in Mozilla and the below would not have been working in Mozilla for years
            //if (l_oHiddenField.uniqueID != p_oCheckbox.uniqueID) {
                if (bResponse) {
                    if (p_oCheckbox.checked == true) {
                        l_oHiddenField.value = 'on';
                    }
                    else {
                        l_oHiddenField.value = '';
                    }
                    if (bRequiresReAuth) {
                        document.forms[k].elements["hdnBMLChanged"].value = "1";
                        document.forms[k].submit();
                    }
                }
            //}
        }
    }
    if (bResponse == false) {
        if (p_oCheckbox.checked) {
			p_oCheckbox.checked = false;
		}
		else {
			p_oCheckbox.checked = true;
		}
    }
}


function GetCheckedControl(objControls)
{
	if(!objControls)
		return;
		
	for(var i = 0; i <= objControls.length -1; i++)
	{
		if(objControls[i].checked)
		{
			return objControls[i];
		}
	}
	return null;
}

function GetControlByValue(objControls, value)
{
	if(!objControls)
		return;
		
	for(var i = 0; i <= objControls.length -1; i++)
	{
		if(objControls[i].value == value)
		{
			return objControls[i];
		}
	}
	return null;
}

function AddOptions(objSelect, strArray)
{
	if(!objSelect || !strArray)
		return;
		
	for(var i = 0; i <= strArray.length -1; i++)
	{
		AddOption(objSelect, strArray[i], strArray[i], false);
	}
}

function AddOption(objSelect, text, value, selected)
{
	if(!objSelect)
		return;
		
	var option = document.createElement("option");
	option.text = text;
	option.value = value;
	objSelect.options.add(option);
}

function OptionIsSelected(objSelect)
{
	if(!objSelect)
		return false;
	
	if(objSelect.selectedIndex == 0)
		return false;
	
	return true;
}

function SetSelectedOption(objSelect, optionValue)
{
	for(var i = 0; i <= objSelect.options.length -1; i++)
	{
		if(objSelect.options[i].value == optionValue)
		{
			objSelect.options[i].selected = true;
			return;
		}
	}
}

function RedirectToPayPal(btnUsePayPal, paypalURL) 
{
    btnUsePayPal.form.action = paypalURL;
}

function ShowProductTabs(activeTable, pdetailTabs) {
    var activeTab = 'ActivekeyTab';
    var inactiveTab = 'InactivekeyTab';
    var tabContent = 'keyTab';

    var pdetailTabIds = pdetailTabs.split(',');
    for (i = 0; i < pdetailTabIds.length; i++){
        var tempActiveTab = activeTab.replace("key", pdetailTabIds[i]);
        var tempInactiveTab = inactiveTab.replace("key", pdetailTabIds[i]);
        var tempTab = tabContent.replace("key", pdetailTabIds[i]);

        if (activeTable == pdetailTabIds[i]) {
            document.getElementById(tempActiveTab).style.display = 'inline';
            document.getElementById(tempActiveTab).style.visibility = 'visible';

            document.getElementById(tempInactiveTab).style.display = 'none';
            document.getElementById(tempInactiveTab).style.visibility = 'hidden';

            document.getElementById(tempTab).style.display = 'block';
            document.getElementById(tempTab).style.visibility = 'visible';
        }
        else {
            document.getElementById(tempActiveTab).style.display = 'none';
            document.getElementById(tempActiveTab).style.visibility = 'hidden';

            document.getElementById(tempInactiveTab).style.display = 'inline';
            document.getElementById(tempInactiveTab).style.visibility = 'visible';

            document.getElementById(tempTab).style.display = 'none';
            document.getElementById(tempTab).style.visibility = 'hidden';
        }
    }
         }

         function showReorderTab(id) {
         	if (document.getElementById('chkAutoReorder' + id).checked == true) {
         		document.getElementById('reorderBasket' + '_' + id).style.display = "block";
         		document.getElementById('chkAutoReorder' + id).value = "True";
         		document.getElementById('selQuantity' + id).disabled = false;
         		document.getElementById('selMonths' + id).disabled = false;
         		document.getElementById('selBeginMonths' + id).disabled = false;
         	}
         	else {
         		document.getElementById('reorderBasket' + '_' + id).style.display = "none";
         		document.getElementById('chkAutoReorder' + id).value = "False";
         		document.getElementById('selQuantity' + id).disabled = true;
         		document.getElementById('selMonths' + id).disabled = true;
         		document.getElementById('selBeginMonths' + id).disabled = true;
         	}
         }

        



        



