var GLOBAL_sentQuery = false;
var GLOBAL_dayhours = [];
var GLOBAL_afterhours = [];
var GLOBAL_datetargetId;
var cal_pd;
var cal_rd;
var cal_pd_over=false;
var cal_rd_over=false;

function Cleanup() {
    document.getElementById('dynaSearchForm_pt').value = document.getElementById('dynaSearchForm_ptsel').value;
    document.getElementById('dynaSearchForm_rt').value = document.getElementById('dynaSearchForm_rtsel').value;
    
    if (document.getElementById('dynaSearchForm_pl') != null && document.getElementById('dynaSearchForm_pl').value == "") {
        document.getElementById('dynaSearchForm_pl').value = document.getElementById('dynaSearchForm_locDesc').value;
    }
}

function generateSixtURL(aid) {
    var pl = document.getElementById("dynaSearchForm_pl").value;

    var pd = document.getElementById("dynaSearchForm_pd").value;
    var pt = document.getElementById("dynaSearchForm_pt").value;

    var rd = document.getElementById("dynaSearchForm_rd").value;
    var rt = document.getElementById("dynaSearchForm_rt").value;

    url = "/affiliate/redirect.do?aid=" + aid +
                        "&pl=" + pl +
                        "&pd=" + pd +
                        "&pt=" + pt +
                        "&rd=" + rd +
                        "&rt=" + rt;
    return url;
}

function checkAffiliate(o) {
    if (aff.toUpperCase() == "SIXT") {
        popupAffiliate(generateSixtURL("sixt"), "This location is serviced by our affiliate, Sixt Holiday Car.  To continue, please click Yes.");
        return false;
    }
    return true;
}
function IsDate(dateStr) {
    var datePat = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
    var matchArray = dateStr.match(datePat); // is the format ok?
    
    if (matchArray==null || matchArray[1]==null) { return false; }
    if (matchArray[2]==null || matchArray[3]==null) { return false; }
    
    month = matchArray[1]; // p@rse date into variables
    day = matchArray[2];
    year = matchArray[3];
    
    if (month < 1 || month > 12) { return false; }
    if (day < 1 || day > 31) { return false; }
    if ((month==4 || month==6 || month==9 || month==11) && day==31) { return false; }
    if (month == 2) {
        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            return false;
        }
    }
    return true;
}

function ParseHours(strHours)  {
    var ahours;
    var parts;
    var i;
    GLOBAL_dayhours = [];
    GLOBAL_afterhours = [];
    
    if (strHours != "") {
        ahours = strHours.split(',');    
        for (i=0; i < ahours.length; i++) {
            parts = ahours[i].split(' ');
            GLOBAL_dayhours[parseInt(parts[0], 10)]  = parts[1];
            GLOBAL_afterhours[parseInt(parts[0], 10)] = (parts[2]=='Y');
        }
    } else {
        for (i=0; i < 7; i++) {
            GLOBAL_dayhours[i] = GLOBAL_CONSTANT_default_hours;
            GLOBAL_afterhours[i] = false;
        }        
    }
}

function CreateTimeOption(dateObj) {
    var iHours = dateObj.getHours();
    var iMinutes = dateObj.getMinutes();
    var sHour;
    
    if (iHours > 12) {
        sHour = iHours - 12;
    } else if (iHours == 0) {
        sHour = 12;
    } else {
        sHour = iHours;
    }
    var oOption = new Option(sHour+':'+(100+iMinutes).toString().substr(1,2)+' '+(iHours >= 12 ? 'PM' : 'AM'),
                             (10000+iHours*100+iMinutes).toString().substr(1,4));
    return oOption;
}
function UpdateHours(sField, sDateValue) {
    var timeselfld = document.getElementById(sField+'sel');
    var selOptionValue = "";
    var selIndex = -1;
    var selDefaultIndex = -1;
    
    if (timeselfld.options.length > 0) {
        selOptionValue = document.getElementById(sField).value;
        while (timeselfld.options.length > 0) {
            timeselfld.options[0]=null;
        }
    }
    
    var timeOpen = null;
    var timeClose = null;
    var dayOfWeek;
    
    if (sField == 'dynaSearchForm_rt' && GLOBAL_afterhours.length > 0) {
        for (var i=0; i < 7; i++) {
            if (GLOBAL_afterhours[i]) {
                timeOpen = new Date();
                timeClose = new Date();
                timeClose.setTime(timeOpen.getTime());
                
                timeOpen.setHours(0);
                timeOpen.setMinutes(0);
                timeClose.setHours(23);
                timeClose.setMinutes(59);
                break;
            }
        }
    }
    if (timeOpen == null && timeClose == null) {
        timeOpen = new Date();
        timeClose = new Date();
        
        if (IsDate(sDateValue)) {
            timeOpen.setTime(Date.parse(sDateValue));
            timeClose.setTime(timeOpen.getTime());
            dayOfWeek = timeOpen.getDay();
        } else {
            timeClose.setTime(timeOpen.getTime());
            dayOfWeek = -1;
        }
        if (GLOBAL_dayhours.length > 0 && GLOBAL_dayhours[dayOfWeek] != null) {
            
            timeOpen.setHours(GLOBAL_dayhours[dayOfWeek].substr(0,2));
            timeOpen.setMinutes(GLOBAL_dayhours[dayOfWeek].substr(3,2));
            
            timeClose.setHours(GLOBAL_dayhours[dayOfWeek].substr(6,2));
            timeClose.setMinutes(GLOBAL_dayhours[dayOfWeek].substr(9,2));
        } else {
            timeOpen.setHours(GLOBAL_CONSTANT_default_hours.substr(0,2));
            timeOpen.setMinutes(GLOBAL_CONSTANT_default_hours.substr(3,2));
        
            timeClose.setHours(GLOBAL_CONSTANT_default_hours.substr(6,2));
            timeClose.setMinutes(GLOBAL_CONSTANT_default_hours.substr(9,2));
        }        
    }
    
    // set to non-DST date
    timeOpen.setMonth(0);
    timeOpen.setDate(1);
    timeClose.setMonth(0);
    timeClose.setDate(1);
    
    if (timeOpen.valueOf() >= timeClose.valueOf()) {
        timeClose.setDate(timeClose.getDate()+1);
    }
    
    var oOption;
    var timeCur = new Date();
    var timeLast = new Date();
    timeCur.setTime(timeOpen.getTime());
    timeLast.setTime(timeClose.getTime());
     
    timeCur.setMinutes(timeCur.getMinutes() < 30 ? 30 : 60);
    timeLast.setMinutes(timeLast.getMinutes() <= 30 ? (timeLast.getMinutes() == 0 ? -30 : 0) : 30);
    
    oOption = CreateTimeOption(timeOpen);                         
    timeselfld.options[0] = oOption;
    if (oOption.value == selOptionValue) {
        selIndex = timeselfld.options.length-1;
    } else if (oOption.value == GLOBAL_CONSTANT_default_time) {
        selDefaultIndex = timeselfld.options.length-1;
    }

    while (timeCur.valueOf() <= timeLast.valueOf()) {

        oOption = CreateTimeOption(timeCur);
                             
        timeselfld.options[timeselfld.options.length] = oOption;
        if (oOption.value == selOptionValue) {
            selIndex = timeselfld.options.length-1;
        } else if (oOption.value == GLOBAL_CONSTANT_default_time) {
            selDefaultIndex = timeselfld.options.length-1;
        }
        
        timeCur.setMinutes(timeCur.getMinutes()+30);
    }
    
    oOption = CreateTimeOption(timeClose);                   
    timeselfld.options[timeselfld.options.length] = oOption;
    if (oOption.value == selOptionValue) {
        selIndex = timeselfld.options.length-1;
    } else if (oOption.value == GLOBAL_CONSTANT_default_time) {
        selDefaultIndex = timeselfld.options.length-1;
    }
    
    if (selIndex != -1) {
        timeselfld.selectedIndex = selIndex;
    } else if (selDefaultIndex != -1) {
        timeselfld.selectedIndex = selDefaultIndex;
    }
}

function SetDataAC(DescCode, Hours, Code, Affl, Ctry) {
    document.getElementById("dynaSearchForm_locDesc").value = DescCode;
    document.getElementById("dynaSearchForm_locHours").value = Hours;
    ParseHours(Hours);
    SetAffiliate(Affl);

    document.getElementById("dynaSearchForm_pl").value = Code;
    
    UpdateHours('dynaSearchForm_pt', document.getElementById('dynaSearchForm_pd').value);
    UpdateHours('dynaSearchForm_rt', document.getElementById('dynaSearchForm_rd').value);

    // if china location, then popup chaffeur service type dropdown
    if (Ctry.toUpperCase() == "CN") {
        toggleChauffeurType(true);
    } else {
        toggleChauffeurType(false);
    }
}
function SetAffiliate(strAff) {
    aff = strAff;
}

// data holders for autoselecting the first item of a no-click:
var acData = [];
var aff = "";

// event handlers
var procTextboxKeyEvent = function(sType, aArgs) {
    var oAutoComp = aArgs[0];
    
    document.getElementById("dynaSearchForm_pl").value = "";
};
var procTextboxFocusEvent = function(sType, aArgs) {
    var oAutoComp = aArgs[0];

    oAutoComp.sendQuery("");
};

function toggleChauffeurType(show) {
    var ct = document.getElementById("chauffeur_type");
    var dod = document.getElementById("dropoff_date");

    if (ct == null || dod == null)
        return;

    ct.style.display = show ? "" : "none";

    var cft = document.getElementById("dynaSearchForm_cft");
    if (show && (cft.value == "AP" || cft.value == "AD")) {
        dod.style.display = "none"
    } else {
        dod.style.display = "";
    }
}

var procItemSelectEvent = function(sType, aArgs) {
    var oAutoComp = aArgs[0];
    var elItem = aArgs[1];
    var oData  = aArgs[2];
                         
    SetDataAC(oData[0], oData[1], oData[2], oData[3], oData[4]);
};
var procUnmatchedItemSelectEvent = function(sType, aArgs) {
    var oAutoComp = aArgs[0];
    var sQuery = aArgs[1];

    if (GLOBAL_sentQuery) {
        document.getElementById("dynaSearchForm_locHours").value = "";
        ParseHours("");
        SetAffiliate("");
    }

    if (sQuery != null) {
        if (typeof acData[0].DescCode != "undefined") {
            var oData = acData[0];
            SetDataAC(oData.DescCode, oData.Hours, oData.Code, oData.Affl, oData.Ctry);
        }
    }
};
var procQueryEvent = function(sType, aArgs) {
    var oAutoComp = aArgs[0];
    var sQuery = aArgs[1];
    var oRequest = aArgs[2];
    
    document.getElementById('location_loading_icon').style.visibility = 'visible';

    GLOBAL_sentQuery = true;
};
var procGetResultsEvent = function(sType, aArgs) {
    var oAutoComp = aArgs[0];
    var sQuery = aArgs[1];
    var aResults = aArgs[2];

    // store data for auto-selecting first item:
    acData = aResults;

    document.getElementById('location_loading_icon').style.visibility = 'hidden';
};


var popupAffiliate = function(url, msg) {
    // affiliate popup
    var handleYes = function() {
        window.location = url;
        this.hide();
    };

    var handleNo = function() {
        this.hide();
    }

    // Define various event handlers for Dialog
    YAHOO.namespace("example.container");

    // Instantiate the Dialog
    YAHOO.example.container.simpledialog1 = new YAHOO.widget.SimpleDialog("simpledialog1",
                                                                             { width: "300px",
                                                                               fixedcenter: true,
                                                                               visible: false,
                                                                               draggable: false,
                                                                               zIndex: 2000,
                                                                               modal: true,
                                                                               close: true,
                                                                               text: msg,
                                                                               constraintoviewport: true,
                                                                               buttons: [ { text:"Yes", handler:handleYes, isDefault:true },
                                                                                          { text:"No",  handler:handleNo } ]
                                                                             } );
    YAHOO.example.container.simpledialog1.setHeader("Payless Car Rental Notification");

    // Render the Dialog
    YAHOO.example.container.simpledialog1.render("affiliatepopup");

    YAHOO.example.container.simpledialog1.show(); //, YAHOO.example.container.simpledialog1, true);
    //YAHOO.util.Event.addListener("hide", "click", YAHOO.example.container.simpledialog1.hide, YAHOO.example.container.simpledialog1, true);
}

// calendar
function calHide(e) {
    switch (GLOBAL_datetargetId) {
        case 'dynaSearchForm_pd':
            if (!cal_pd_over) { cal_pd.hide(); }
            break;
        case 'dynaSearchForm_rd':
            if (!cal_rd_over) { cal_rd.hide(); }
    }
}
function calMouseOver(e) {
    switch (this.id) {
        case 'calpdholder':
            cal_pd_over=true;
            break;
        case 'calrdholder':
            cal_rd_over=true;
    }
}
function calMouseOut(e) {
    switch (this.id) {
        case 'calpdholder':
            cal_pd_over=false;
            break;
        case 'calrdholder':
            cal_rd_over=false;
    }
}
function calSetTarget(e) {
    var cal;
    var pagedate=null;
    var dateval_pd;
    var dateval_rd;
    
    switch (this.id.substr(this.id.length-3,3)) {
        case '_pd':
            GLOBAL_datetargetId = 'dynaSearchForm_pd';
            cal = cal_pd;
            cal_rd.hide();
            
            dateval_pd = document.getElementById('dynaSearchForm_pd').value;
            if (IsDate(dateval_pd)) {
                pagedate = dateval_pd.substring(0,2)+"/"+dateval_pd.substring(6,10);
            }
            break;
        case '_rd':
            GLOBAL_datetargetId = 'dynaSearchForm_rd';
            cal = cal_rd;
            cal_pd.hide();

            dateval_pd = document.getElementById('dynaSearchForm_pd').value;
            dateval_rd = document.getElementById('dynaSearchForm_rd').value;
            if (IsDate(dateval_rd) && IsDate(dateval_pd)) {
                if (Date.parse(dateval_pd) > Date.parse(dateval_rd)) {
                    pagedate = dateval_pd.substring(0,2)+"/"+dateval_pd.substring(6,10);
                } else {
                    pagedate = dateval_rd.substring(0,2)+"/"+dateval_rd.substring(6,10);
                }
            } else if (IsDate(dateval_rd)) {
                pagedate = dateval_rd.substring(0,2)+"/"+dateval_rd.substring(6,10);
            } else if (IsDate(dateval_pd)) {
                pagedate = dateval_pd.substring(0,2)+"/"+dateval_pd.substring(6,10);
            }
    }
    if (document.getElementById(GLOBAL_datetargetId).value.length > 0) {
        cal.cfg.setProperty('selected', document.getElementById(GLOBAL_datetargetId).value, false);
        if (pagedate != null) {
            cal.cfg.setProperty('pagedate', pagedate, false);
        }
    }
    cal.render();
}
function calHandleSelect(type,args,obj) {
    var dates = args[0]; 
    var date = dates[0];
    var year = date[0];
    var month = date[1];
    var day = date[2];
    var dateObj = new Date();
    dateObj.setFullYear(year,month-1,day);
    
    var targetFld = document.getElementById(GLOBAL_datetargetId);                            
    targetFld.value = (month+100).toString().substr(1,2)+'/'+(day+100).toString().substr(1,2)+'/'+year;
    
    if (GLOBAL_datetargetId == 'dynaSearchForm_pd') {
        var dropoffFld = document.getElementById('dynaSearchForm_rd');
        
        dateObj.setDate(dateObj.getDate()+GLOBAL_CONSTANT_rdos);

        year = dateObj.getFullYear();
        month = dateObj.getMonth()+1;
        day = dateObj.getDate();

        dropoffFld.value = (month+100).toString().substr(1,2)+'/'+(day+100).toString().substr(1,2)+'/'+year;
        
        UpdateHours('dynaSearchForm_rt', dropoffFld.value);        
        UpdateHours('dynaSearchForm_pt', targetFld.value);
        
    } else if (GLOBAL_datetargetId == 'dynaSearchForm_rd') {
        
        UpdateHours('dynaSearchForm_rt', targetFld.value);
    }
    obj.hide();
}
var OffdateRenderer = function(workingDate, cell) {
    var min;
    var max;
    var selectSuff = GLOBAL_datetargetId.substring(GLOBAL_datetargetId.length-3);
    if (selectSuff=='_pd') {
        min = cal_pd.cfg.getProperty('mindate');
        max = cal_pd.cfg.getProperty('maxdate');
    } else if (selectSuff=='_rd') {
        min = cal_rd.cfg.getProperty('mindate');
        max = cal_rd.cfg.getProperty('maxdate');
    }
    if (workingDate >= min && workingDate <= max && GLOBAL_dayhours[workingDate.getDay()] == null) {
        cell.innerHTML = workingDate.getDate();
        YAHOO.util.Dom.addClass(cell, "offdate");
        return YAHOO.widget.Calendar.STOP_RENDER;
    }
};

var reserveFormInit = function() {
    if (document.getElementById('dynaSearchForm_locDesc') != null) {
        // ac inits
        if (typeof LocationsArray == "undefined") {
            var rezds = new YAHOO.util.XHRDataSource(GLOBAL_CONSTANT_url);
            rezds.responseType = YAHOO.util.DataSource.TYPE_XML;
            rezds.responseSchema = {
                resultNode: "Location",
                fields: ["DescCode", "Hours", "Code", "Affl", "Ctry"]
            };
            rezds.maxCacheEntries = 5;
        } else {
            var rezds = new YAHOO.widget.DS_JSArray(LocationsArray);
        }
        
        var rezac = new YAHOO.widget.AutoComplete('dynaSearchForm_locDesc','pl_container', rezds);
        rezac.dataRequestEvent.subscribe(procQueryEvent);
        rezac.dataReturnEvent.subscribe(procGetResultsEvent);
        rezac.prehighlightClassName = "yui-ac-prehighlight";
        rezac.minQueryLength = 3;
        rezac.useShadow = true;
        rezac.itemSelectEvent.subscribe(procItemSelectEvent);
        rezac.unmatchedItemSelectEvent.subscribe(procUnmatchedItemSelectEvent);
        rezac.textboxKeyEvent.subscribe(procTextboxKeyEvent);
        rezac.allowBrowserAutocomplete = false;
        rezac.queryDelay = 0.1;
        if (YAHOO.env.ua.ie && YAHOO.env.ua.ie <= 6) { rezac.useIFrame = true; }
        
        if (typeof LocationsArray != "undefined") {
            rezac.textboxFocusEvent.subscribe(procTextboxFocusEvent);
            rezac.minQueryLength = 0;
            rezac.forceSelection = true;
            rezac.maxResultsDisplayed = 50;
        }
    }

    if (document.getElementById("dynaSearchForm_pd") != null && document.getElementById("dynaSearchForm_rd") != null) {
        // html:text doesn't support autocomplete attribute therefore we have to do it via DOM manipulation.
        document.getElementById("dynaSearchForm_pd").setAttribute('autocomplete', 'off');
        document.getElementById("dynaSearchForm_rd").setAttribute('autocomplete', 'off');
        
        var vmindate = new Date();
        var vmaxdate = new Date();
        var sDate;
    
        vmindate.setFullYear(parseInt(GLOBAL_CONSTANT_today.substring(6,10),10),
                             parseInt(GLOBAL_CONSTANT_today.substring(0,2),10)-1, 
                             parseInt(GLOBAL_CONSTANT_today.substring(3,5),10));
        
        if (document.getElementById('dynaSearchForm_sd') != null && document.getElementById('dynaSearchForm_sd').value.length > 0) {
            sDate = document.getElementById('dynaSearchForm_sd').value;
            var tempdate = new Date();
            tempdate.setFullYear(parseInt(sDate.substring(6,10),10), 
                                 parseInt(sDate.substring(0,2),10)-1, 
                                 parseInt(sDate.substring(3,5),10));
            if (vmindate < tempdate) { vmindate = tempdate; }
        }
        if (document.getElementById('dynaSearchForm_ed') != null && document.getElementById('dynaSearchForm_ed').value.length > 0) {
            sDate = document.getElementById('dynaSearchForm_ed').value;
            vmaxdate.setFullYear(parseInt(sDate.substring(6,10),10), 
                                 parseInt(sDate.substring(0,2),10)-1, 
                                 parseInt(sDate.substring(3,5),10));
        } else {
            vmaxdate.setFullYear(vmindate.getFullYear(), vmindate.getMonth()+GLOBAL_CONSTANT_mmba, vmindate.getDate());
        }
        
        sDate = (vmindate.getMonth()+1)+"/"+vmindate.getFullYear();
        
        cal_pd = new YAHOO.widget.CalendarGroup("cal_pd","calpdholder",{title:GLOBAL_CONSTANT_cal_tiles["dynaSearchForm_pd"],pagedate:sDate,mindate:vmindate,maxdate:vmaxdate,PAGES:2,close:true});
        cal_pd.selectEvent.subscribe(calHandleSelect,cal_pd,true);
        
        vmaxdate = new Date();    
        vmaxdate.setFullYear(vmindate.getFullYear(), vmindate.getMonth()+GLOBAL_CONSTANT_mmba, vmindate.getDate());
    
        sDate = (vmindate.getMonth()+1)+"/"+vmindate.getFullYear();
        
        cal_rd = new YAHOO.widget.CalendarGroup("cal_rd","calrdholder",{title:GLOBAL_CONSTANT_cal_tiles["dynaSearchForm_rd"],pagedate:sDate,mindate:vmindate,maxdate:vmaxdate,PAGES:2,close:true});
        cal_rd.selectEvent.subscribe(calHandleSelect,cal_rd,true);
    
        for (var i=1; i<=7; i++) {
            cal_pd.addWeekdayRenderer(i, OffdateRenderer);
            cal_rd.addWeekdayRenderer(i, OffdateRenderer);
        }
        
        YAHOO.util.Event.addListener(['calpdholder','calrdholder'], 'mouseover', calMouseOver); 
        YAHOO.util.Event.addListener(['calpdholder','calrdholder'], 'mouseout', calMouseOut); 
            
        YAHOO.util.Event.addListener(["dynaSearchForm_pd","dynaSearchForm_rd"], "focus", calSetTarget);
        YAHOO.util.Event.addListener(["dynaSearchForm_pd","dynaSearchForm_rd"], "click", calSetTarget);
        YAHOO.util.Event.addListener(["cal_icon_pd","cal_icon_rd"], "click", calSetTarget);
    
        YAHOO.util.Event.addListener("dynaSearchForm_pd", "focus", cal_pd.show, cal_pd, true);
        YAHOO.util.Event.addListener("dynaSearchForm_rd", "focus", cal_rd.show, cal_rd, true);
        YAHOO.util.Event.addListener("dynaSearchForm_pd", "click", cal_pd.show, cal_pd, true);
        YAHOO.util.Event.addListener("dynaSearchForm_rd", "click", cal_rd.show, cal_rd, true);
        YAHOO.util.Event.addListener("cal_icon_pd", "click", cal_pd.show, cal_pd, true);
        YAHOO.util.Event.addListener("cal_icon_rd", "click", cal_rd.show, cal_rd, true);
    
        YAHOO.util.Event.addListener(["dynaSearchForm_pd","dynaSearchForm_rd","cal_icon_pd","cal_icon_rd"], "blur", calHide);
        
        // init select box
        if (document.getElementById("dynaSearchForm_locHours").value.length == 0) {
            document.getElementById("dynaSearchForm_locHours").value = '0 '+GLOBAL_CONSTANT_default_hours+',1 '+GLOBAL_CONSTANT_default_hours+',2 '+GLOBAL_CONSTANT_default_hours+',3 '+GLOBAL_CONSTANT_default_hours+',4 '+GLOBAL_CONSTANT_default_hours+',5 '+GLOBAL_CONSTANT_default_hours+',6 '+GLOBAL_CONSTANT_default_hours;
        }
        ParseHours(document.getElementById("dynaSearchForm_locHours").value);
        UpdateHours('dynaSearchForm_pt', document.getElementById('dynaSearchForm_pd').value);
        UpdateHours('dynaSearchForm_rt', document.getElementById('dynaSearchForm_rd').value);
    }
};
//YAHOO.util.Event.onDOMReady(reserveFormInit);

function RemovePopupPanel(popUpID) {
    if (document.getElementById(popUpID) != null) {
        document.getElementById(popUpID).style.visibility = "hidden";
        document.getElementById(popUpID).parentNode.removeChild(document.getElementById(popUpID));
    }
}
function ShowPopupPanel(popUpID, containerObj, srcNoticeID, title, widthsize) {
    RemovePopupPanel(popUpID);
    var popupPanelObj = new YAHOO.widget.Panel(popUpID, {
            width: widthsize,
            zIndex: 2000,
            close: true,
            context: [containerObj, "tl", "bl"],
            underlay: "none"} );
    popupPanelObj.setHeader(title);
    popupPanelObj.setBody(document.getElementById(srcNoticeID).innerHTML);
    popupPanelObj.render(containerObj);
}

function subscribeSpecialsBadEmail() {
    var emailInput = document.getElementById("email");
    emailInput.style.border = "2px solid #DE434A";
}

function subscribeSpecialsLoading(on) {
    var sbutton = document.getElementById("subscribeSpecialsButton");
    var sloading = document.getElementById("subscribe_loading_icon"); 
    if (on) {
        sbutton.style.display = "none";
        sloading.style.display = "block";
    } else {
        sloading.style.display = "none";
        sbutton.style.display = "block";
    }
    
}

function subscribeSpecials(e) {
    var emForm = document.getElementById("emform");
    var email = emForm.elements['email'].value;
    var sUrl = "/subscribe/signing-up-specials.do?email=" + encodeURIComponent(email);

    var regex = /^[A-Z0-9._%-][+A-Z0-9._%-]*@([A-Z0-9-]+\.)+[A-Z]{2,6}$/i
    if (email.length == 0 || !regex.test(email)) {
        subscribeSpecialsBadEmail();
    } else {
        subscribeSpecialsLoading(true);
        var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: subscribeSpecialsSuccess, failure: subscribeSpecialsFailure });
    }
    YAHOO.util.Event.stopEvent(e);
}

function subscribeSpecialsSuccess(o) {
    // check if o has data first

    var root = o.responseXML.documentElement;
    var success = root.getElementsByTagName('success')[0].firstChild.nodeValue;

    if (success == "true") {
        var successBlock = document.getElementById("email_signup_success");
        var emailBlock = document.getElementById("email_signup");
        var additionalText = document.getElementById("email_signup_success_complete");

        emailBlock.style.display = "none";
        successBlock.style.display = "block";
        additionalText.style.display = "block";
    } else if (success == "email") {
        var successBlock = document.getElementById("email_signup_success");
        var emailBlock = document.getElementById("email_signup");
        var additionalText = document.getElementById("email_signup_success_mail");

        emailBlock.style.display = "none";
        successBlock.style.display = "block";
        additionalText.style.display = "block";

    } else {
        var emailInput = document.getElementById("email");

        var errCode = root.getElementsByTagName('code');
        if (errCode.length == 0) return;

        if (errCode[0].firstChild.nodeValue == -1) { // bad email address
            subscribeSpecialsBadEmail();
            subscribeSpecialsLoading(false);
        }
    }
}

function subscribeSpecialsFailure(o) {
    subscribeSpecialsLoading(false);
    alert("An error occured while trying to process your request to sign up for Specials Deals.  Please try again.");
}


function perksResendActivation(id) {
    var sUrl = "/perks/resend-activation.do?id=" + id

    perksResendLoading(true);
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, { success: resendActivationSuccess, failure: resendActivationFailure });
    
}

function perksResendLoading(on) {
    var sLoading = document.getElementById("resend_loading"); 

    if (on) {
        var sError = document.getElementById("resend_error");
        var sSent = document.getElementById("resend_sent"); 
        var pError = document.getElementById("perks_error");

        sSent.style.display = "none";
        sError.style.display = "none";
        pError.style.display = "none";
        sLoading.style.display = "block";
    } else {
        sLoading.style.display = "none";
    }
}

function resendActivationFailure(o) {
    perkResendLoading(false);
    var sError = document.getElementById("resend_error");
    sError.style.display = "block";
}

function resendActivationSuccess(o) {
    // check if o has data first

    var root = o.responseXML.documentElement;
    var success = root.getElementsByTagName('success')[0].firstChild.nodeValue;

    if (success == "true") {
        perksResendLoading(false);

        var sError = document.getElementById("resend_error");
        var sSent = document.getElementById("resend_sent"); 

        sSent.style.display = "block";
        sError.style.display = "none";
    } else {
        perksResendLoading(false);

        var sError = document.getElementById("resend_error");
        var sSent = document.getElementById("resend_sent"); 

        sSent.style.display = "none";
        sError.style.display = "block";

        /*
        var errCode = root.getElementsByTagName('code');
        if (errCode.length == 0) return;

        if (errCode[0].firstChild.nodeValue == -1) { // -1 == bad id; -2 == no account
        }
        */
    }
}

function showMoreInfo(containerObj, code, title) {
    ShowPopupPanel("noticepanel", containerObj, "mi_" + code, title, "400px");
}

function toggleDropoff(e) {
    var dod = document.getElementById("dropoff_date");
    if (dod == null) return;

    if (!e) e = window.event;

    var ctype = (e.target || e.srcElement).value;

    if (ctype == "AP" || ctype == "AD") {
        dod.style.display = "none";
    } else {
        dod.style.display = "";
    }
}
