﻿function ShowPopup(hoveritem, hoverpopup, message, popupclass)
{


//var hp = document.getElementById(hoverpopup);
var hp = $get(hoverpopup);

//if element doesn't exist, create it
if(hp==null)
    hp = CreatePopup(hoverpopup, message,popupclass);
// Set position of hover-over popup
//SetPopupPosition(hoveritem, hp);

//var hi = $get('UpdatePanel1');
var hi = hoveritem;


hp.style.position  = 'absolute';
var bounds = Sys.UI.DomElement.getBounds(hi);

//hp.style.top = bounds.y + "px";
//hp.style.left = bounds.width + bounds.x + 10 + "px";
//hp.style.left = bounds.x + "px";
//Sys.UI.DomElement.setLocation(hp,bounds.x,bounds.y);
var hiBounds = Sys.UI.DomElement.getBounds(hi);
var hpBounds = Sys.UI.DomElement.getBounds(hp);
var offset = Sys.UI.DomElement.getBounds(hp.offsetParent);

var defaultLeft = hiBounds.x;
var offsetLeft = offset.x;
var deltaLeft = -hp.offsetWidth;

var defaultTop = hiBounds.y;
var offsetTop = offset.y;
var deltaTop = -hp.offsetHeight;

var x = deltaTop - offsetTop + defaultTop;
var y = deltaLeft - offsetLeft + defaultLeft;



//var relX = hiBounds.x - hpBounds.x;
//var relY = hiBounds.y - hpBounds.y;

Sys.UI.DomElement.setLocation(hp,x,y);


// Set popup to visible
hp.style.visibility = "Visible";
}


function HidePopup(hoverpopup)
{
hp = document.getElementById(hoverpopup);
hp.style.visibility = "Hidden";
}

function SetPopupPosition(obj, popup)
{


    
    var curLeft = curTop = 0;
    var original = obj;
    if(obj.offsetParent)
    {
        do
        {
            curLeft +=obj.offsetLeft;
            curTop +=obj.offsetTop;
            
        } while(obj=obj.offsetParent);
        
    }
    else if(obj.x)
        curLeft = obj.x;
    
    
    popup.style.position  = 'absolute';
    popup.style.top = curTop + "px";
    popup.style.left = original.offsetWidth + curLeft + 10 + "px";
    
}

function CreatePopup(id, message, popupClass)
{
    //create a popup for validation messages that hover
    
    var div = document.createElement('div');
    div.innerHTML = message;
    

    
    
    div.setAttribute('id', id);
    div.className = popupClass;
   
   
    var obj = document.getElementById('UpdatePanel1');
   
    //document.body.appendChild(div);
    obj.appendChild(div);
    return(div);   
    
    
}

function OnPopupValidationControlChange(validationControlID,mainControlID) {
   // Do nothing if client validation is not active
   if (typeof(Page_Validators) == "undefined")  return;
   // Change the color of the label
   
   var validationControl = document.getElementById(validationControlID);
   var mainControl = document.getElementById(mainControlID);

   //mainControl.style.color = validationControl.isvalid ? "Black" : "Red";
   if(validationControl!=null && mainControl!=null)
     mainControl.style.backgroundColor = validationControl.isvalid ? "White" : "Red";
}

function ValidateEmailAddress(source,args)
{

//    if(source.length<8)
//    {
//        args.IsValid = false;
//    }
//    else
//        args.IsValid = true;
    args.IsValid = false;
    
    
}

//function Validate(source,args)
//{
//    TestValidate(source,"","","DisplayValid","DisplayInvalid");    
//}

function TestValidate(source,ctlToValidateName,controlValues, validCss, invalidCss)
{
    var i;
    var ctlName;
    var ctl;
    var isValid=true;
    var ctlToValidate;
    var controls;
    controls = [eval(controlValues)];
    
    ctlToValidate = document.getElementById(ctlToValidateName);
    
    for(i=0;i<controls.length;i++)
    {
            ctlName = controls[i];
            ctl = document.getElementById(ctlName);
 
            if(!IsValid(ctl))
            {
                isValid = false;
                break;
            }               
    }
    if(isValid)
        ctlToValidate.className = validCss;
    else
        ctlToValidate.className = invalidCss;
 
       
}

function IsValid(ctl)
{
    if (typeof(ctl.isvalid) == "string")
    {
        if (ctl.isvalid == "False")
        {
            return(false);
        }
        else
        {
            return(true);
        }
    }
    else
    {
        return(true);
    }    

}

function UpdateDayValue(dropdownDayID, dayValueID)
{
    //update hidden field so dynamic items can be handled in postback
    var dropdownDay = $get(dropdownDayID);  
    var dayValue= $get(dayValueID);
    dayValue.value = GetDropdownValue(dropdownDay);
}

function SetDropdownDays(dropdownMonthID, dropdownDayID, dropdownYearID)
{
    var dropdownMonth = $get(dropdownMonthID);
    var dropdownDay = $get(dropdownDayID);  
    var dropdownYear = $get(dropdownYearID);

    //save the day so it can be re-selected if possible.  We can assume it is always the same as the index
    var dayIndex = dropdownDay.selectedIndex;
    
    ClearDropdown(dropdownDay);
    
    //javascript works with days starting from 0, so adjust
    var month = GetDropdownValue(dropdownMonth)-1;
    var year = GetDropdownValue(dropdownYear);
    
    var numDays = daysInMonth(month,year);
    
        
    var opt = document.createElement('option');
    opt.text = 'Day';
    opt.value= '0';
    dropdownDay.options.add(opt);
    for(i=1;i<=numDays;i++)
    {          
        opt = document.createElement('option');
        opt.text = i.toString();
        opt.value = i.toString();

        dropdownDay.options.add(opt);
    }

    if(dayIndex <= numDays)
    {
        dropdownDay.selectedIndex = dayIndex;
    }
    else
    {
        dropdownDay.selectedIndex = 0;
    }
}


function GetDropdownValue(dropdown)
{
    var option = dropdown.options[dropdown.selectedIndex];
    return option.value;
}

function ClearDropdown(dropdown)
{
 var length = dropdown.options.length;
 
    //clear all items except first element which is for unselected option
    for(var i=length-1;i>=0;i--)
    {
        dropdown.options[i]=null;
    }
}

function daysInMonth(month, year)
{
	return 32 - new Date(year, month, 32).getDate();
}

function setValidator(ctlName, highlightCss)
{
    var ctl = $get(ctlName);
    var originalValidator = ctl.evaluationfunction;
    var isValid=false;
    
    var newValidator = function(val){
           if(!originalValidator(val))
           {
                Sys.UI.DomElement.addCssClass(ctl, highlightCss);
                isValid = false;
                return false;
           }
           else
           {
            Sys.UI.DomElement.removeCssClass(ctl, highlightCss)
            isValid = true;
            return true;
           }
           
    }

    ctl.evaluationfunction = newValidator;
    
}

function validateCityState(cond)
{

    if (cond.IDToEval == "" || cond.IDToEval2 == "") // ControlIDToEvaluate is unassigned
        return -1;   
        
    var cityValue = DES_GetTextValue(cond.IDToEval, cond.Trim, cond.GetText);
    var stateSelIdx= DES_GetSelIdx(cond.IDToEval2, cond.GetSelIdx2);
    
    if(cityValue=="")
        return -1;
        
    if(cityValue!="" && stateSelIdx == 0)
        return 0;
    else
        return 1;
}

function incrementSlider(c_sliderExtenderID)
{
    var c_sliderExtender = $find(c_sliderExtenderID);
    var value = c_sliderExtender.get_Value();    
    c_sliderExtender.set_Value(value + 1);       
}

function decrementSlider(c_sliderExtenderID)
{
    var c_sliderExtender = $find(c_sliderExtenderID);
    var value = c_sliderExtender.get_Value();    
    c_sliderExtender.set_Value(value - 1);       
}

function getRadioButtonValue(tableName, index)
{
    var table = $get(tableName);
    
    var row = table.rows[index];
    var cell = row.cells[0];
    var rbl = cell.childNodes[0];
    return rbl.checked;    

}
function setQuoteSum()
{
    var total =0;
    
    //set the quote total based on each quote textbox value in array
    for(i=0;i<_quotes.length;i++)
    {
        var c_quote = $get(_quotes[i]);
        total+=c_quote.value;
    }
    var c_quoteResultsQuoteAmount = $get('c_quoteResultsQuoteAmount');
    c_quoteResultsQuoteAmount.value = total;
    
}

//function setPremium(quoteName, finalPremium, hipDysplasiaPercentName, hipDysplasiaPercent,c_quoteTotalName)
//{
//    var c_quote = $get(quoteName);
//    var c_hipDysplasiaPercent= $get(hipDysplasiaPercentName);
//    
//    //add subtotal in hidden field that sums all other pets not selected, needed because those controls  don't show in client
//    var c_quoteTotal = $get(c_quoteTotalName);
//    var c_quoteTotalSub = $get(c_quoteTotalName + 'Sub');
//    
//    //subtotal to current quote
//    var total = parseFloat(c_quoteTotalSub.value) + finalPremium;
//    total = Math.round(total * 100)/100;
//    
//    //c_quoteTotal.value = total;
//    setInnerText(c_quoteTotal,String.format("{0:N}",total));
//    
//}

function sliderChanged(
    sliderName,
    quoteName,
    premium,
    c_hipDisplasiaAmountName,  
    panelName,
    movingDeductibleName,
    actualDeductibleName,
    quoteTotalName,
    quoteTotalNameSub,
    intervalCount,
    sliderValuesString,
    sliderLength)
{

    var c_slider = $get(sliderName);
    var c_quote = $get(quoteName);
        
    var c_panel = $get(panelName);
    var c_movingDeductible = $get(movingDeductibleName);    
    var c_actualDeductible = $get(actualDeductibleName);
    
    //add subtotal in hidden field that sums all other pets not selected, needed because those controls  don't show in client
    var c_quoteTotal = $get(quoteTotalName);
    var c_quoteTotalSub = $get(quoteTotalNameSub);
    var c_hipDisplasiaAmount = $get(c_hipDisplasiaAmountName);

    
    //calculate new position of div/panel based on slider position
    var panelBounds = Sys.UI.DomElement.getBounds(c_panel);    
    var totalLength = intervalCount;  
    //var sliderLength = 400;      
    
    //must be whole number
    var relPosition = parseInt((c_slider.value/totalLength) * sliderLength);        
    c_panel.style.position = 'relative';  
    c_panel.style.left = relPosition + "px" ; 
    

    var sliderValues = eval(sliderValuesString);
    var sliderValue = c_slider.value;
    
    var item = sliderValues[sliderValue];    
    var deductible = item.Deductible;
    var payment = item.Payment;
    var hipDysplasia = item.HipDysplasia;
    
    setInnerText(c_movingDeductible,deductible);
    c_actualDeductible.value = deductible;
    setInnerText(c_quote,String.format("{0:N}",payment));
        
    if(c_hipDisplasiaAmount!=null)
    {
        setInnerText(c_hipDisplasiaAmount,String.format("{0:N}", hipDysplasia));
    }
    
    var total = parseFloat(c_quoteTotalSub.value) + parseFloat(payment);
    total = Math.round(total * 100)/100;
    
    setInnerText(c_quoteTotal,String.format("{0:N}",total));
}




function recalcValues(linkedDeductibleName)
{
    var c_linkedDeductible = $get(linkedDeductibleName);
   //do postback of panel so slider control is updated for user
    fireEvent(c_linkedDeductible,'change');
    

}


function setInnerText(ctl, value)
{
    if (document.all)
        ctl.innerText = value;
    else
        ctl.innerHTML = value;  
}


function fireEvent(element,event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

function checkModalPopup()
{
        var myBehavior = $find("modalBehavior"); 
        myBehavior.show();
 
//    if(DES_ValidateGroup('QuoteInfo'))
//    {
//        
//        var myBehavior = $find("modalBehavior"); 
//        myBehavior.show();
//        
//    }
//    return false;
}

function checkBeforeEnroll(inEdit)
{
    
//    var oForm = $get('aspnetForm');
//    var c_InAddMode = $get(inAddModeName);
//    
//    if(c_InAddMode.value=="true" || isDirty(oForm))
    //{
    
        if(inEdit)
        {
            alert("You must save any changes before enrolling.");       
            return false;
         }    
     //}
     
//         else
//         {
//            var myBehavior = $find("modalBehavior"); 
//            myBehavior.show();
//          
//         }
//         return false;
}

var _bSubmitted=false;

function isDirty(oForm)
{
    if(_bSubmitted) return false;
    var iNumElems = oForm.elements.length;
    for (var i=0;i<iNumElems;i++)
    {
    var oElem = oForm.elements[i];

    if ("text" == oElem.type || "TEXTAREA" == oElem.tagName)
    {
    if (oElem.value != oElem.defaultValue) return true;
    }
    else if ("checkbox" == oElem.type || "radio" == oElem.type)
    {
    if (oElem.checked != oElem.defaultChecked) return true;
    }
    else if ("SELECT" == oElem.tagName)
    {
    var oOptions = oElem.options;
    var iNumOpts = oOptions.length;
    for (var j=0;j<iNumOpts;j++)
    {
    var oOpt = oOptions[j];
    if (oOpt.selected != oOpt.defaultSelected) return true;
    }
    }
    }
    return false;
}



    function InitializeRequest(sender, args) {
      document.body.style.cursor = "wait"; 
      if (prm.get_isInAsyncPostBack())
       {
           
  
          args.set_cancel(true);
       }
    }
 function EndRequest(sender, args) 
  {
    document.body.style.cursor = "default"; 
 
    // Get a reference to the element that raised the postback
    //   which is completing, and enable it.
    //$get(sender._postBackSettings.sourceElement.id).disabled = false;
  }
    
    function AbortPostBack() {
      if (prm.get_isInAsyncPostBack()) {
           prm.abortPostBack();
      }        
      document.body.style.cursor = "default"; 
    }
    
    
    
    function ConfirmDelete()
    {
    
    
    }
    
function ValidatePetName(cond)
{
return 1;
}
function ValidateZipCode(cond)
{
    var val= DES_GetTextValue(cond.IDToEval, cond.Trim, cond.GetText);
    if(val=="")
    {
        cond.Action.ErrMsg = "Value must be entered.";        
        return 0;        
    }
    else
    {
        var exp = new RegExp(/^(\d{5})$/);
        if(exp.test(val))
            return 1;
        else
        {
            cond.Action.ErrMsg = "Invalid zip code.";        
            return 0;
        }
    }
}

function EnableItem(actionName)
{
    var action = DES_FindAOById(actionName);
    if(action)
    {
        action.Enabled = true;
    }
}

function setIndex(obj, ctlName)
{
    var index = obj.selectedIndex;
    var ctl = $find(ctlName);
    ctl.set_activeTabIndex(index);    
    
}

function setNumberedIndex(index, ctlName)
{
    var ctl = $find(ctlName);
    ctl.set_activeTabIndex(index);        
}

function setRegisterButtonState(checkBoxID, buttonID)
{
    var checkbox = $get(checkBoxID);
    var button = $get(buttonID);
    
    if(checkbox.checked)
    {
        button.disabled = "";
        button.className = "Button ButtonRight";
    }
    else
    {
        button.disabled = "disabled";
        button.className = "ButtonDisabled ButtonRight";
    }
    
    
}