/* 
* 
* script.js 
* developed for HumanaOne.com
* 
* Objects declared on this page are 
* 
* window.Humana
* window.Humana.utility
* window.Humana.validation
* 
* window.Humana.homePage
* window.Humana.buildQuoteTell
* window.Humana.quoteResults 
* 
* 
*/

/* Page Load Declarations */
/* Hiding elements while setting up CSS */
document.getElementsByTagName('html')[0].className = 'hide';

$('document').ready(function () {
    Humana.init();
});

window.Humana = {
    /* 
    * init contains calls to any unified functionality that 
    * every page on HumanaOne.com (that contains this script) should call
    * 
    */
    init: function () {
        Humana.utility.init();
        this.selfExecute();
    },
    /* 
    * selfExecute will ascertain page context 
    * and initialize relevant page object
    * 
    * NOTE for HUMANA:  If removing any of this functionality, please remember to 
    * also remove the HTML component as well... This means removing the class="execute"
    * from the HTML that would call this. 
    * 
    */
    selfExecute: function () {
        $('.execute').each(function (i, el) {
            var iDvalue = $(el).attr('id');
            if ($(el).hasClass('clone')) { iDvalue = iDvalue.substring(0, iDvalue.length - 1); }
            Humana[iDvalue].init();
        });
    }
};

/* This will load any overlay within a div with ID="phoneQuote".   Represents Call Center Hours 
* requires div id="phoneQuote", div id="callcenter", div class="mainContent"
* 
* If any of these divs are missing, there may be javascript errors
*/
window.Humana.phoneQuote = {
    init: function () {
        var obj = this;
        var $link = $('#phoneQuote a[rel]');

        $link.overlay({
            absolute: true,
            top: obj.getCoords($('#phoneQuote'), $('#callcenter')).top,
            left: obj.getCoords($('#phoneQuote'), $('#callcenter')).left,
            onLoad: function (event) {
                var ol = this;
                $(window).resize(function () {
                    ol.getOverlay().css({ 'left': obj.getCoords($('#phoneQuote'), ol.getOverlay()).left, 'top': obj.getCoords($('#phoneQuote'), ol.getOverlay()).top });
                });
            },
            onClose: function (event) {
                $(window).unbind('resize');
            }
        }).addClass('overlaySet').click(function (e) {
            e.preventDefault();
        });
    },
    getCoords: function (el, ol) {
        var val = {
            left: (((0 - $(el).position().left) * -1) < ($(window).width() - $(el).position().left)) ? ($(el).position().left + 6) : (($('.mainContainer').position().left + $('.mainContainer').width()) - ol.width()),
            top: $(el).find('a').position().top
        };
        return val;

    }
};

/*
* This will handle form actions for ZIP Search fields.   
* requires div id="searchQuote" and a div id="fldSearchZIP" as well as input class="search"
* See line 109 for where to include javascript to successful validation
* 
*/

window.Humana.searchQuote = {
    init: function () {
        var $button = $('#searchQuote #fldSearchZIP');
        var ol;
        if ($button.size() > 0) {
            $button.find('button.search').click(function () {
                if (Humana.validation.constants.ZIP.test($button.find('input.search').val())) {

                    /* -- HUMANA TODO --  Implement search functionality.  
                    * It would be best to implement via javascript 
                    * So below validation will work in conjunction.  
                    * If validating with ASP, remove entire block.
                    */
                    /*  This is where a form submission would happen, sending user to */

                }
                else {
                    /*  This is where an exception would happen, sending user to */
                    return false;
                }
            });

        }

    }

};

/* 
* Result overlay object
* Requires 1 element with class="execute" and id="resultOverlay"
* Requires a child element to "resultOverlay" with id="tabs"
* 
* 
*/

window.Humana.resultOverlay = {
    init: function () {

        var $link = $('a[rel]:not(.overlaySet)');

        $('#resultOverlay #tabs').tabs('div.panes > div');
        $('#resultOverlay').bgiframe();

        var overlay = $link.overlay({
            zIndex: 100000,
            fadeInSpeed: 1,
            close: 'div.close',
            expose: {
                loadSpeed: 1,
                color: '#666',
                zIndex: 1
            },
            api: true
        });
    },
    setOverlayLinks: function () {

    }

};


/* 
* Find Doctor Results 
* Requires 1 element with class="execute" and id="findDoctorResults"
* div id="divTandC" Requires child elements: ".submitBtn", ".btnCancel", "div.close"
* 
* Represents page level javascript for find-doc-results.html
*/
window.Humana.findDoctorResults = {
    init: function () {
        this.setTermsAndConditions();
    },
    setTermsAndConditions: function () {
        //Establishes page load with a Terms and Conditions overlay.  
        //Humana to establish when user has already been to this page.
        //Possible solution would be to not include <div id="divTandC"> in asp when user has already agreed.

        //The below code is commented because #divTandC is not used on the page.
        /*
        //HUMANA TODO: wrap the following in a conditional statement that will check for a session value about whether they've seen 
        // the terms and conditions previously.
		
		
        // if(<check session variable>===false){
        var overlay = $("#divTandC").overlay({
        zIndex:100000, 
        fadeInSpeed:1,
        expose:{
        loadSpeed:1,
        close:'.btnCancel, div.close',
        color:'#666', 
        zIndex:1},
        api: true 
        }).load();
		
        $('#divTandC').find('.submitBtn input').click(function(){
        overlay.close();
        //HUMANA TODO:  Here is where you will add the session variable that will be checked before displaying the Terms and Conditions. 
        })
        //}
        */
    }

};

/*
* Requires div class="adSpace" (with child element class="body")
* Requires div class="adRow" (with child element class="body")
* Requires div class="planSpace" (with child element class="body")
* 
* 
* Represents page level javascript for index.html and index_logged_in.html
*/

window.Humana.homePage = {
    init: function () {
        this.loadGallery();
        this.alignItems();
        $('#galleryDiv').removeClass('galleryDivHide');
    },
    alignItems: function () {
        var aHeight = $('.adSpace .body').height();
        var pHeight = $('.planSpace .body').height();

        var minHeight = (aHeight > pHeight) ? aHeight : pHeight;
        $('.adRow .body').css({ 'height': minHeight });

    },

    /* 
    * This element represents the image gallery on the home page. 
    * 
    * Requires div id="gallery" 
    * Requires div id="thumbs"
    * Requires div id="thumbwrapper" (with child class="control")
    * Requires div id="caption"
    * 
    */
    loadGallery: function () {
        $('<div id="galTooltip" class="tooltip"></div>').insertAfter('.mainContainer');
        $('#gallery #thumbs img[title]').tooltip({
            tip: '.tooltip',
            relative: false,
            offset: [0, -10],
            position: 'top center'

        });

        $('#thumbs li').opacityrollover({
            mouseOutOpacity: '.67',
            mouseOverOpacity: '1.0'
        });

        var gallery = $('#gallery .thumbwrapper').galleriffic({
            delay: 9000,
            numThumbs: 5,
            preloadAhead: 5,
            enableTopPager: false,
            enableBottomPager: true,
            imageContainerSel: '#image',
            captionContainerSel: '#gallery #caption',
            renderSSControls: true,
            renderNavControls: false,
            autoStart: true,
            syncTransitions: true,
            defaultTransitionDuration: 1000,
            onTransitionOut: function (slide, caption, isSync) {
                $(caption).hide().remove();
            }
        });

        $('#thumbs li a').removeAttr('title');

        $('#gallery .thumbwrapper .control').click(function () {
            var $this = $(this);
            if (gallery.isSlideshowRunning) {
                gallery.pause();
                $this.removeClass('pause').addClass('play');
            }
            else {
                gallery.play();
                $this.removeClass('play').addClass('pause');
            }
            window.gallery = gallery;
        });


    }
};

/*
* Javascript Object representing actions that take place specifically on insurance-quotes.html
* 
* Requires div id="bottom"
* Requires submit button to be wrapped in "span id="btnSubmit"
* Requires div id="divMainPlanInfo"
* 
* 
*/

window.Humana.buildQuoteTell = {
    init: function () {
        var obj = this;
        //$('#bottom').hide();

        this.addChild();
        this.setContactMethod();
        this.setCoverageLength();
        this.buttonActions();

    },
    buttonActions: function () {
        var obj = this;
        this.$form = $('.form');
        this.$form.find('span#btnSubmit input').click(function () {
            /* 
            * HUMANA TODO:
            * 
            * In order to prevent initial submission, first: 
            * 
            * return false; 
            *
            *	Then validate.
            * 
            * Here's an example of using jQuery to submit a form asynchronously: 
            * http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/ 
            *
            */
            if (obj.validateForm('.form')) {
                /*
                * This is where successful validation would end up.
                * In this area now, you can call $('form').submit(); or a similar function
                */
            }
        });
        /*Eric Commented out
        this.$form.find('span#btnMore input').click(function(){
			
        $('#bottom:hidden').slideDown(500, function(){
        $('#divMainPlanInfo .footer:eq(0)').fadeTo(100, '.5', function(){
        $.scrollTo('#divExtraPlanInfo', {duration:1000});
					
        }).parents('.footer:eq(0)').find(':button').attr('disabled','true');
        $('body.ie6 #bottom #divExtraMktgInfo').show();
        });
        });
        $('#divExtraPlanInfo .footer a.toggleDetail').click(function(event){
        //event.preventDefault();
        $('body.ie6 #bottom #divExtraMktgInfo').hide();
        $('#bottom:visible').slideUp(1000, function(){
        $('#divMainPlanInfo .footer:eq(0)').fadeTo(100, 1)
        .parents('.footer:eq(0)').find(':button').attr('disabled','');
															
        });
        }); */
        $('input.txtDateMonth, input.txtDateDay, input.txtDateYear').blur(function () {
            var $par = $(this).parent();
            var curDate = [$par.find('input.txtDateMonth').val(), $par.find('input.txtDateDay').val(), $par.find('input.txtDateYear').val()];
            if (Humana.validation.validateDate($par, ['.txtDateMonth', '.txtDateDay', '.txtDateYear'], false) === true) {
                var today = new Date($('#CoverageStartDate input').val());
                var bd = new Date($par.find('input.txtDateYear').val(), $par.find('input.txtDateMonth').val() - 1, $par.find('input.txtDateDay').val());

                var age = today.getFullYear() - bd.getFullYear();
                if (today.getMonth() <= bd.getMonth() && today.getDate() < bd.getDate()) {
                    age -= 1;
                }

                $(this).parents('tr').find('span.spnAge').text(age);

            }
            else {
                $(this).parents('tr').find('span.spnAge').text('');
            }
            console.log(curDate);
        });

    },

    setContactMethod: function () {
        var $contacts = $('span.contact');
        $contacts.hide();
        $('fieldset#fldOptIn input[type=checkbox]').click(function () {
            $contacts.toggle();
        });
    },
    setCoverageLength: function () {

        $('fieldset#CoverageEndDate').hide();
        $('#fldCoverageLength input[type=radio]').click(function () {
            if ($(this).val() == 'Stm') {
                $('#CoverageStartDate:hidden').slideDown('normal');
                $('#CoverageEndDate:visible').hide();
            }
            else {
                $('#CoverageStartDate:hidden, #CoverageEndDate:hidden ').slideDown('normal');
            }
        });
    },
    addChild: function () {
        $('#fldMemberCoverage table tr.optional').hide();
        $('#btnAddChild').click(function (event) {
            event.preventDefault();
            addRow();
        });
        function addRow() {
            $('#fldMemberCoverage table tr.child:hidden:eq(0)').show();
        }
    },
    validateForm: function (form) {
        Humana.validation.validateEmptyFields(form);
        Humana.validation.validateCoverage(form);
    }

};



/*
* Javascript Object representing actions that take place specifically on find-doc-search.html or find-doc-results.html
* 
*/

window.Humana.findDoctor = {
    init: function () {
        //This is a stub function.  Humana TODO: here is where you will initialize any additional behaviors.
        //Examples of functions would be ajax calls to retrieve doctor information as well as connecting 
        //to any mapping API for map to doctor's office  
    }

};

/*
* Javascript Object representing actions that take place specifically on insurance-quotes
* 
*/

window.Humana.buildQuoteCustomize = {
    init: function () {
        Humana.quoteResults.setSlideDownContent();
    }


};
/*
* Javascript Object representing actions that take place specifically on insurance-quotes
* 
* Requires: "div.planDetails", ".links  a.toggleDetails", "div.planDetails a.toggleDetail"
*/

window.Humana.quoteResults = {
    init: function () {
        this.setSlideDownContent();

    },
    setSlideDownContent: function () {
        $('.planDetails').hide();
        $('.links > a.toggleDetail').live('click', function (event) {
            //event.preventDefault();

            $(this).css({ visibility: 'hidden' }).parent().next('.planDetails:hidden').toggle('normal');

        });
        $('.planDetails a.toggleDetail').live('click', function (event) {
            //event.preventDefault();
            $(this).parents('.planDetails:visible').toggle('normal');
            $(this).parents('.planDetails').prev('.links').find('a').css({ visibility: 'visible' });
            $.scrollTo($(this).parents('.details, .planDetails').prevAll('h3:eq(0)'), { duration: 1000 });
        });
    }
};

/* 
* Utility Functions
* These functions can be shared     
*/


window.Humana.utility = {
    init: function () {
        window.browser = this.browserDetect();
        this.consoleOverride();

        this.setFocusActions();
        this.navigationControl();

        this.fixPNG();
        document.getElementsByTagName('html')[0].className = '';
        this.settooltips();
    },
    settooltips: function () {
        if ($('a.tooltips').size() > 0) {
            //Small Tool Tip case
            $("<div id='contTip2' class='clearfix smToolTip tooltip'><div class='info'></div></div>").appendTo('.mainContainer');
            $('a.tooltips[title]').tooltip({ opacity: 1, tip: '#contTip2', position: 'bottom center',
                lazy: true,
                onBeforeShow: function () {
                    this.getTrigger().attr('title', '');
                    this.getTip().empty().append("<div class='info'></div><p>" + this.getTrigger().data('title') + "</p>");
                }
            });

            $('a.tooltips+div.tooltip').parent().find('a.tooltips').tooltip({
                opacity: 1,
                position: 'bottom right'
            });
        }
    },
    browserDetect: function () {
        /*	appends browser identifier to class of body dynamically.  Helps with Cross-Browser CSS conflicts	
        *
        *	NOTE: do NOT append body classes such as 'ie', 'ie6', 'ie7' to body's class... This script will do that automatically
        */
        var browser;
        var $browser = $.browser;
        if ($browser.msie) {
            if ($browser.version == '6.0') {
                browser = "ie ie6";
            }
            if ($browser.version == '7.0') {
                browser = 'ie ie7';
            }
            if ($browser.version == '8.0') {
                browser = 'ie ie8';
            }
        }
        else if ($browser.mozilla) {
            if ($browser.version < 1.8) {
                browser = "ff1";
            }
            else if ($browser.version > 1.8) {
                browser = "ff2";
            }
            else {
                browser = "ff3";
            }
        }
        else if ($browser.safari) {
            browser = 'safari';
        }
        else if ($browser.opera) {
            browser = 'opera';
        }
        $('body').addClass(browser);
        return browser;
    },
    fixPNG: function () {
        if ($.browser.msie && $.browser.version == '6.0') {
            DD_belatedPNG.fix('input.btnSearch,.thumbwrapper,.tooltip,.recoDetails .body,.recoDetails.bot,.recoField');
        }
    },
    consoleOverride: function () {
        /* console.log override code... Prevents errors when browser doesn't support console */
        if (window['console'] === undefined) {
            window.console = {
                log: function () {
                }
            };
        }
    },
    focusHandle: function (el) {
        /* function to clear text fields on focus.  Compares current value with value in title.
        * If title matches value, then field clears.  On blur, field repopulates with title value if left empty.
        */

        var $texts = $(el).find('input[type=text], textarea').filter(':not(.modal input[type=text], .modal textarea)');

        $texts.each(function () {
            var $this = $(this);
            if ($this.val() == "" || $this.val() == $this.attr('title')) {
                $this.val($this.attr('title')).addClass('default');
            }
        });

        $texts.focus(function () {
            var $this = $(this);
            $this.val(($this.val() === $this.attr('title')) ? '' : $this.val()).removeClass('default');
        }).blur(function () {
            var $this = $(this);
            $this.val(($this.val() === '') ? $this.attr('title') : $this.val()).addClass(($this.val() === $this.attr('title')) ? 'default' : '');
        });
    },
    navigationControl: function () {

        $('ul.globalNavigation li').hover(function () {
            $(this).siblings('li').removeClass('hover').end().addClass('hover');
        }, function () {
            $(this).removeClass('hover');
        });

        $('ul.globalNavigation li:has(ul.subnav)').mouseenter(function () {
            var $this = $(this);
            $this.find('ul.subnav').css({
                'top': ($this.offset({ relativeTo: window }).top) + ($this.outerHeight()),
                'left': $this.position().left,
                'position': 'absolute'
            })
					.find('li').css({ 'width': $this.outerWidth() })
					.end()
					.show();
        });
        $('ul.globalNavigation li:has(ul.subnav)').mouseleave(function () {
            var $this = $(this);
            $this.find('ul.subnav').hide();

        });

    },
    setFocusActions: function () {
        this.focusHandle('body');
    }

};

/* 
* Below are some basic validation functions.  
* 
* To use them for additional validation, reference them as such: 
* 
* Humana.validation.constants.ZIP
* Humana.validation.constants.phonePre
* Humana.validation.constants.phoneSuff
* Humana.validation.constants.dateMon, etc. 
* 
*/

window.Humana.validation = {
    constants: {
        ZIP: /^[0-9]{5}$/,  //Basic 5 digit US ZIP code regex
        phonePre: /^[0-9]{3}$/, //Basic 3 digit US Phone Prefix regex - Can represent prefix OR Area Code
        phoneSuff: /^[0-9]{4}$/, //Basic 4 digit US Phone Prefix regex,
        dateMon: /^[0]?[1-9]|[1][0-2]$/, //Represents 1 or 2 digit month
        dateDay: /^[0]?[1-9]|[1][0-9]|[2][0-9]|[3][0-1]$/, //Represents 1 or 2 digit Day
        dateYear: /^\d{4}$/ //Represents 4 digit Year
    },

    addErrorMessage: function (message, type) {
        if (type == "listing") {
            $('form .errorcollection dl').append('<dd>' + message + '</dd>');
        }
        else if (type == "BlankMessage") {
            $('<dt>' + message + '</dt>').insertBefore('form .errorcollection dl dd:first');
        }
        else if (type == "message") {
            $('<dt>' + message + '</dt>').appendTo('form .errorcollection dl');
        }
    },

    /* 
    * 
    * This function will search the parameterized form for empty fields and display 
    * a message if there are any (using the addErrorMessage function.)
    * 
    * 
    */
    validateEmptyFields: function (form) {

        var obj = this;
        $('.errorcollection').empty().append('<dl></dl>');
        $('.invalid').removeClass('invalid');

        var $collection = $(form).find('label:has(span.MandatoryField:visible), span:has(span.MandatoryField:visible)');

        function checkBlankFields($collection) {
            var flag = false;
            var mes = '';
            $collection.each(function (i, el) {

                if ($(this).siblings(':text').val() == '') {
                    $(this).siblings(':text[value=""]').addClass('invalid');
                    flag = true;
                    var t = $(this).text();
                    obj.addErrorMessage(t.substring(0, t.indexOf('*')), 'listing');
                }

            });

            if (flag === true) {
                obj.addErrorMessage('Please complete required fields: ', 'BlankMessage');
            }
        }

        checkBlankFields($collection);
    },
    validateCoverage: function (form) {
        var obj = this;
        var flag = false;
        var $cov = $(form).find('table.tblCoverage tbody');

        $cov.find('tr label:has(span.MandatoryField)').each(function (i, el) {
            var $this = $(el);
            var t = $this.text();
            if (obj.validateDate($this.parents('tr'), ['.txtDateMonth', '.txtDateDay', '.txtDateYear'], true) === false) {
                flag = true;
            }
            if (obj.validateSelect($this.parents('tr').find('select')) === false) {
                flag = true;
            }
            if (flag) {
                obj.addErrorMessage(t.substring(0, t.indexOf('*')) + ' applicant information', 'listing');
            }
            else {
                obj.validateSpouseGenderRules(form);
            }
        });

    },
    validateSelect: function (select) {
        if ($(select)[0].selectedIndex === 0) {
            $(select).addClass('invalid');
            return false;

        }
    },
    validateSpouseGenderRules: function (form) {
        var obj = this;
        var $prim = $(form).find('tr#rowBeneficiary select.slcGender');
        var $spouse = $(form).find('tr#rowSpouse select.slcGender');

        if ($prim.val() == $spouse.val()) {
            obj.addErrorMessage('Spouse Gender Invalid Message', 'message');
            return false;
        }
    },
    validateDate: function (el, flds, check) {
        var dateVal = [this.constants.dateMon, this.constants.dateDay, this.constants.dateYear];
        var flag = false;

        for (i = 0; i < flds.length; i++) {
            if (dateVal[i].test($(el).find(flds[i]).val()) === false || $(el).find(flds[i]).val() == "") {
                if (check === true) {
                    $(el).find(flds[i]).addClass('invalid');
                }
                flag = true;
            }
        }
        if (flag === true) {
            return false;
        }
        else {
            return true;
        }
    }
};
