//HCF main javascript. By David Nash (david@pollen.com.au) / Pollen Digital

//no conflicts
jQuery.noConflict();

jQuery(document).ready(function () {

    var debug = true;

    var SearchFocus = true;

    var PageURL = window.location.pathname;

    //Handling CSS MyPostcode class
    if (jQuery('.MyPostcode').length > 0) {
        jQuery('.MyPostcode').numeric().textLimit(4);
    }

    // Removed the old Nav bar js from here: Samir

    jQuery('.labelify').labelify(); //this shows the text field label inside the text until the user enters something


    /*
    Home page: hero panel tabs
    */
    jQuery('#Hero ul.nav li a.tab').click(function () {
        jQuery(this).parent().parent().find('.active').removeClass('active');
        jQuery(this).addClass('active');
        jQuery('.heroPanel').hide(); //hide all panels
        jQuery('#Panel' + jQuery(this).attr('id').substr(7)).show();
        return false;
    });

    jQuery('#HomeTab1').click(function () {
        jQuery('#GetAQuote').show();
        jQuery('#ResumeAQuote').hide();
        //don't return, we want to run the general link code too
    });

    jQuery('#HomeTab1').click(); //fire the click event to display the first tab

    jQuery('.resumeAQuoteButton').click(function () {
        if (jQuery('#GetAQuote:visible').length > 0) {
            jQuery('#GetAQuote').hide();
            jQuery('#ResumeAQuote').show();
        }
        else {
            jQuery('#GetAQuote').show();
            jQuery('#ResumeAQuote').hide();
        }
    });

    TriggerSubmitButtton('QuoteNumber', 'btnResumeQuote');

    //Home page: link items
    jQuery('.linkItem').click(function () {
        window.location = jQuery('a', this).attr('href');
    });


    /*
    Nice drop-downs
    */
    // create fancy dropdowns
    // THIS WAS MOVED OUT OF THE DOCUMENT READY CALL AND MADE INTO A FUNCTION
    createFancyDropdowns();

    //add functionality to our "select" list
    jQuery('.styleselect').live('click', function () {
        var ddlID = jQuery(this).attr('id');
        jQuery(".styleselect ul:not(#" + ddlID + " ul)").hide(); //hide any open drop-downs
        jQuery('ul', this).toggle(); //show/hide the list of options when clicked
        jQuery('.styleselect').css('z-index', 1); //ie bugfix: set all others zindex to 1
        jQuery(this).css('z-index', 2); //ie bugfix: set this zindex to 2 (ie over the others)
        return false; //stop event propagation
    });

    jQuery('.styleselect ul li').live('click', function () {
        var ss = jQuery(this).parent().parent();
        ss.find('div').text(jQuery(this).text()); //update the 'label'
        ss.find('select').val(jQuery(this).data('value')); //set the value of the select
        var myId = ss.find('select').attr("id");
        var onChangeEventSelect = ss.find('select').attr("onchange");
        if (onChangeEventSelect != null) {
            //setTimeout('__doPostBack(\'' + myId + '\',\'\')', 0)
            setTimeout(onChangeEventSelect);
        }

        jQuery(this).parent().hide(); //hide the list
        return false;
    });

    //if we click elsewhere, we want the drop-down to close
    jQuery(document).mousedown(function (event) {
        if (!(jQuery(event.target).hasClass('styleselect') || jQuery(event.target).parents().hasClass('styleselect'))) {
            jQuery('.styleselect ul').hide();
        }
    });

    /*
    Side-scrolling carousels
    */

    jQuery('.carousel').each(function () {
        jQuery(this).append('<div class="controls"><div class="prev"></div><div class="thumbs"></div><div class="next"></div></div>');

        var currentItem = 0;
        var ul = jQuery(this).find('ul');
        var liWidth = jQuery('li', ul).outerWidth(true);

        var maxItem = jQuery('li', ul).length - 1;
        var thumbs = jQuery('.thumbs', jQuery(this));
        var rate = 500;

        //insert a control item for each item in the list
        count = 0;
        jQuery('ul li', this).each(function () {
            thumbs.append('<div class="item"></div>');
            count++;
        });

        //allow user to skip straight to a page
        jQuery('.item', thumbs).click(function () {
            jQuery('.item', thumbs).removeClass('active');
            index = jQuery(this).index();
            ul.css('left', -index * liWidth);
            currentItem = index;
            jQuery('.item', thumbs).eq(currentItem).addClass('active');
        });

        ul.width(liWidth * count); //set the width of the <li>s

        //sets the 'thumbs' width so we can center
        thumbs.width(count * jQuery('.carousel .item').outerWidth(true));
        jQuery('.item', thumbs).eq(0).addClass('active'); //set the first 'thumb' active

        //click next button
        jQuery('.next', jQuery(this)).click(function () {
            scrollCarousel();
        });




        //click prev button
        jQuery('.prev', jQuery(this)).click(function () {
            jQuery('.item', thumbs).removeClass('active');
            currentItem--;
            if (currentItem < 0) {
                //clone last item and add to start
                var lastItem = jQuery('li', ul).eq(-1).clone();
                ul.prepend(lastItem).css('left', -liWidth);
                ul.width(liWidth * (count + 1));

                ul.animate({ left: '+=' + liWidth }, rate,
					function () {
					    jQuery('li', ul).eq(0).detach(); //detach the item we put on the front
					    ul.width(liWidth * count); //reset the width
					    ul.css('left', -ul.width() + liWidth); //move the view to the end
					    currentItem = maxItem;
					    jQuery('.item', thumbs).eq(-1).addClass('active');
					}
				);
            }
            else
                ul.stop(true, true).animate({ left: '+=' + liWidth }, rate);

            jQuery('.item', thumbs).eq(currentItem).addClass('active');

        });



        var nextButton = jQuery('.next', jQuery(this));

        var autoscroll = true;

        if (autoscroll) {
            var timeOutID = setInterval(function () { scrollCarousel(); }, 5000);
            jQuery(this).data('timeOutID', timeOutID);

            jQuery(this).hover(
				function () { clearTimeout(jQuery(this).data('timeOutID')); },
				function () {
				    var timeOutID = setInterval(function () { scrollCarousel(); }, 5000);
				    jQuery(this).data('timeOutID', timeOutID);
				}
			); //pause the auto-scroll on hover
        }

        function scrollCarousel() {
            jQuery('.item', thumbs).removeClass('active'); //unset active thumb

            currentItem++;
            if (currentItem > maxItem) {
                //clone the first item and add to the end
                var firstItem = jQuery('li', ul).eq(0).clone();
                ul.append(firstItem);

                ul.width(liWidth * (count + 1));
                //animate to the clone item, then skip back to the real start
                ul.stop(true, true).animate({ left: '-=' + liWidth }, rate,
					            function () {
					                ul.css('left', 0);
					                currentItem = 0;
					                jQuery('.item', thumbs).eq(0).addClass('active');
					                ul.width(liWidth * count); //set the real width
					                firstItem.detach();
					            }
				            );

            }
            else
                ul.stop(true, true).animate({ left: '-=' + liWidth }, rate);

            jQuery('.item', thumbs).eq(currentItem).addClass('active');
        }

    }); //end carousel.each()


    /*
    "Accordion" headings
    */
    jQuery('#PageContent .product h6').click(function () {
        jQuery(this).next().toggle('fast');
        jQuery(this).toggleClass('expanded');
    });

    SegmentJoinTrigger();

    /*
    Product and health insurance page header functions
    */

    var fontzoom = 100;

    jQuery('#FontPlus').click(function () {
        if (fontzoom >= 140)
            return;

        fontzoom += 10;

        if (jQuery('.tabContent').length)
            jQuery('.tabContent').css({ fontSize: fontzoom + '%' });

        if (jQuery('.itemGrid').length)
            jQuery('.itemGrid').css({ fontSize: fontzoom + '%' });

        if (jQuery('#singleColumnContent').length)
            jQuery('#singleColumnContent').css({ fontSize: fontzoom + '%' });

        if (jQuery('#twoColumnContentLeft').length)
            jQuery('#twoColumnContentLeft').css({ fontSize: fontzoom + '%' });

        if (jQuery('.fontzoom').length)
            jQuery('.fontzoom').css({ fontSize: fontzoom + '%' });

        return false;
    });

    jQuery('#FontMinus').click(function () {

        if (fontzoom <= 80)
            return;

        fontzoom -= 10;

        if (jQuery('.tabContent').length)
            jQuery('.tabContent').animate({ fontSize: fontzoom + '%' }, 0);

        if (jQuery('.itemGrid').length)
            jQuery('.itemGrid').css({ fontSize: fontzoom + '%' });

        if (jQuery('#singleColumnContent').length)
            jQuery('#singleColumnContent').css({ fontSize: fontzoom + '%' });

        if (jQuery('#twoColumnContentLeft').length)
            jQuery('#twoColumnContentLeft').css({ fontSize: fontzoom + '%' });

        if (jQuery('.fontzoom').length)
            jQuery('.fontzoom').css({ fontSize: fontzoom + '%' });

        return false;
    });



    jQuery('#Print').click(function () {
        window.print();
        return false;
    });

    createToolTip();



    /*
    Apply asterisks to required "labels"
    */
    addRequiredFieldIndicators();


    /*
    Product page - item divs are made to "link" via the title
    */

    if (jQuery('.itemGrid .item').length) { //if we're on the product page
        jQuery('.itemGrid .item').click(function () {
            if (jQuery(this).attr('title')) //if this div has title set
                window.location = jQuery(this).attr('title'); //send the browser to it
        });
    }


    /*
    Close window - set a link or button with id="CloseWindow" to do so.
    For this to work the window must have been opened by the script
    */
    jQuery('#CloseWindow').live('click', function () {
        //window.opener = 'x';
        window.close();
    });



    if (jQuery().numeric) {
        jQuery('.numeric').numeric();
    }

    createPopUpWindow();

    jQuery('div.popUpDialog a.button').click(function () {

        jQuery(this).parent('div.popUpDialog').jqprint();

        return false;

    })


    /*
    Get A Quote page
    */

    if (jQuery('#Quote').length > 0) {

        jQuery('Body').attr('id', 'QuotePage');
    }

    if (jQuery('#popUpDialog').length)
        jQuery('#popUpDialog').jqm({ trigger: '#popUpTrigger', modal: true, toTop: true });



    //    if (jQuery('#SaveThisQuoteDialog').length) {
    //        jQuery('#SaveThisQuoteDialog').jqm({ trigger: '#SaveQuote', modal: true, toTop: true });
    //    
    //        jQuery('#SaveThisQuoteDialog').css('z-index', 101);
    //        jQuery('#jqmOverlay').css('z-index', 100);
    //    }



    //load quotes when different time period (day, week etc) clicked
    if (jQuery('#QuoteOptions').length) {
        jQuery('#PriceByDay').click(function () {
            jQuery('#QuoteOptions').html(jQuery('#QuoteDay').clone(true));
            jQuery(this).siblings().addClass('period');
            jQuery(this).removeClass('period');
            return false;
        });

        jQuery('#PriceByWeek').click(function () {
            jQuery('#QuoteOptions').html(jQuery('#QuoteWeek').clone(true));
            jQuery(this).siblings().addClass('period');
            jQuery(this).removeClass('period');
            return false;
        });

        jQuery('#PriceByMonth').click(function () {
            jQuery('#QuoteOptions').html(jQuery('#QuoteMonth').clone(true));
            jQuery(this).siblings().addClass('period');
            jQuery(this).removeClass('period');
            return false;
        });

        jQuery('#PriceByYear').click(function () {
            jQuery('#QuoteOptions').html(jQuery('#QuoteYear').clone(true));
            jQuery(this).siblings().addClass('period');
            jQuery(this).removeClass('period');
            return false;
        });

    } //end if QuoteOptions



    //sharethis code
    var delay = 400;

    function hideMenu() {
        if (!jQuery('.custom_button').data('in') && !jQuery('.hover_menu').data('in') && !jQuery('.hover_menu').data('hidden')) {
            jQuery('.hover_menu').fadeOut('fast');
            jQuery('.custom_button').removeClass('active');
            jQuery('.hover_menu').data('hidden', true);
        }
    }

    jQuery('.custom_button, .hover_menu').mouseenter(function () {
        jQuery('.hover_menu').fadeIn('fast');
        //jQuery('.custom_button').addClass('active');
        jQuery(this).data('in', true);
        jQuery('.hover_menu').data('hidden', false);
    }).mouseleave(function () {
        jQuery(this).data('in', false);
        setTimeout(hideMenu, delay);
    });

    // Compare Other funds section

    jQuery("#otherFundsStepOne").click(function () {
        compareShowHideStep1();
    });

    jQuery("#otherFundsStepTwo").click(function () {
        compareShowHideStep2();
    });

    //End Compare Other funds section
    jQuery('#coverOrPackageDetails').addClass('hidden');

    togglePackageTemplateTables(1); //default state of tabs and corresponding tables

    // Start Packages 
    //PageURL: initialised at the beginning of document.ready and captures current page url.

    if (PageURL.toLowerCase().indexOf('hospital-only') >= 0) {

        jQuery("li [name='Extras']").hide();
        togglePackageTemplateTables(2);
    }

    else if (PageURL.toLowerCase().indexOf('extras-only') >= 0) {
        jQuery("li [name='Hospital']").hide();
        togglePackageTemplateTables(1);
    }

    else if (PageURL.toLowerCase().indexOf('packages') >= 0) {
        togglePackageTemplateTables(1);
    }
    else {

        jQuery("li [name='Extras']").hide();
        jQuery("li [name='Hospital']").hide();
    }


    jQuery('#RightCol .priceBy .period').live('click', function () {
        //remove old classes
        jQuery('#RightCol .priceBy .inactive').removeClass('inactive');
        //add new classes        
        jQuery(this).addClass("inactive");

        jQuery('#RightCol .showExcess').removeClass('showExcess');

        var name = jQuery(this).attr('name');
        jQuery('#ExcessList' + name).addClass("showExcess");
    });

    jQuery('#JoinRightCol .priceBy .period').live('click', function () {
        //remove old classes
        jQuery('#JoinRightCol .priceBy .inactive').removeClass('inactive');
        //add new classes        
        jQuery(this).addClass("inactive");

        jQuery('#JoinRightCol .showExcess').removeClass('showExcess');

        var name = jQuery(this).attr('name');
        jQuery('#ExcessList' + name).addClass("showExcess");
    });

    ExcessListControlTrigger();
    ExcessListJoinTrigger();


    jQuery('#packagesTable .subNav a').click(function () {
        //jQuery('#packagesTable .active').addClass('last');
        //setTab(this, 'active');
        tabID = jQuery(this).attr("id").replace("tab", "");
        togglePackageTemplateTables(tabID);
    });


    jQuery('#packagesTable ul li').each(function () {
        var width = jQuery(this).outerWidth();
        jQuery(this).attr('style', 'width=' + width + 'px;');
    });

    //End Packages


    // **********************************************
    // **********************************************
    // FAQs js scripts
    // Will have to be integrated with .net
    // Only to show interaction design
    // **********************************************
    // **********************************************
    jQuery("#triggerFaqCategories").click(function () {
        jQuery('#triggerFaqCategories').toggleClass('opened shut');
        jQuery('#faqCategories').slideToggle();
    });

    jQuery(".categoryContent a.question").click(function () {
        var isHidden = jQuery('.categoryContent a.question').next('div').hasClass('hidden');
        var currentSelecton = jQuery(this).next('div');

        jQuery(this).toggleClass('opened shut');

        if (!isHidden) {
            jQuery(currentSelecton).removeClass('hidden');
            jQuery(currentSelecton).slideToggle();
        }
        else {
            jQuery(currentSelecton).slideToggle();
        }



    });

    // Routine for direct anchor linking / targetting
    jQuery('a.shut.question').each(function () {

        var tagContent = jQuery.trim(jQuery(this).text());
        jQuery(this).attr('id', tagContent);

    });

    if (PageURL.toLowerCase().indexOf('faqs/') >= 0) {

        var hashValue = window.location.hash.split("#")[1];

        if (typeof hashValue != 'undefined' && hashValue != '') {
            hashValue = hashValue.replace(/%20/g, ' ');
            jQuery("a[id=\"" + hashValue + "\"]").trigger("click");
            SearchFocus = false;
            window.location.href = "#" + hashValue;

        }

    }

    // **********************************************
    // **********************************************
    // Corporate governance js scripts    
    // **********************************************
    // **********************************************
    //hide all tabs
    jQuery('#CorporateGovernance > .tabContent > div').hide();

    //show the first tab
    jQuery('#CorporateGovernance > #Tab1').addClass('active');
    jQuery('#CorporateGovernance #Tab1Content').show();

    //make the layout a little nicer
    jQuery('.director').addClass('collapsed');

    //set up tab click functions
    jQuery('#CorporateGovernance > ul.subNav li a').click(function () {
        content_id = jQuery(this).attr('id') + 'Content';
        jQuery('ul.subNav li a').removeClass('active'); //make all inactive
        jQuery(this).addClass('active'); //set active - highlights it
        jQuery('.tabContent > div').hide(); //hide all
        jQuery('#' + content_id).show(); //show this tab's content
        return false;
    });


    //the 'read more' links, when clicked, reveal more content
    //add the link
    jQuery('span.moreinfo').each(function () {
        jQuery(this).hide().after('<a href="#" class="readmore readmore_or_less">Read more...</a>');
    });

    jQuery('.readmore').live('click', function () {
        jQuery(this).removeClass('readmore').addClass('readless').text('Read less...');
        jQuery(this).parent().find('.moreinfo').slideDown();
        jQuery('.director').removeClass('collapsed');
        jQuery(this).parent('.director').addClass('collapsed');
        return false;
    });

    jQuery('.readless').live('click', function () {
        jQuery(this).removeClass('readless').addClass('readmore').text('Read more...');
        jQuery(this).parent().find('.moreinfo').slideUp();
        jQuery(this).parent('.director').addClass('collapsed');
        return false;
    });


    // **********************************************
    // **********************************************
    // My Health Guardian
    // **********************************************
    // **********************************************

    jQuery("#twoColumnContentLeft .readMore").each(function () {
        var currentSelecton = jQuery(this).parent().next('div');
        jQuery(currentSelecton).hide('fast');
    });

    jQuery("#twoColumnContentLeft .readMore").click(function () {

        var isHidden = jQuery(this).parent().next('div').hasClass('hide');
        var currentSelecton = jQuery(this).parent().next('div');

        if (isHidden) {
            jQuery(this).html('Read less&hellip;');
            jQuery(currentSelecton).removeClass('hide');
        }
        else {
            jQuery(this).html('Read more&hellip;');
            jQuery(currentSelecton).addClass('hide');
        }
        jQuery(currentSelecton).slideToggle();
    });

    if (PageURL.toLowerCase().indexOf('my-health-guardian/') >= 0) {

        var hashValue = window.location.hash.split("#")[1];

        if (typeof hashValue != 'undefined' && hashValue != '') {

            jQuery("a[id=\"" + hashValue + "\"]").trigger("click");
            SearchFocus = false;
            window.location.href = "#" + hashValue;

        }
    }

    // End My Health Guardian


    //Strip HTML tags from Title
    if (jQuery.browser.msie) {
        document.title = StripHTMLTags(jQuery('title').html());
    }
    else {
        document.title = StripHTMLTags(jQuery('title').text());
    }


    //Normalise resource paths required only in dev/localhost environment
    NormaliseResourcePaths();
    // ******************************************************************************
    // ******************************************************************************
    // Search functionality
    // ******************************************************************************
    // ******************************************************************************

    //Search button click event
    jQuery('#btnSearch').click(function () {

        var searchText = jQuery.trim(jQuery('#SearchField').val());
        if (searchText.length > 0) {
            searchText = searchText.replace(/ /g, '-');
            searchText = searchText.replace(/&/g, 'and');
            try {                
                window.location.href = jQuery(this).attr('href') + searchText + "/";

            } catch (e) {

                var assumeInput = searchText.replace(/[$#@%^&!*()]/g, '');
                window.location.href = jQuery(this).attr('href') + assumeInput + "/";

            }
        }
    });

    TriggerSubmitButtton('SearchField', 'btnSearch');

    // End Search functionality


    //put the cursor in the search box 
    if (SearchFocus) {
        jQuery('#SearchField').focus();
    }

    //Register startupscript for errMsg

    var errMsg = getQuerystring('errMsg', null);
    if (errMsg != '') {
        alert(errMsg.replace(/\+/g, ' '));
    }

    //added by Gemma 22/12/2011
    // Overseas Visitors Health Cover ------------------
    jQuery("#ifrmEnquiry").attr("src", "/healthinsurance/secured/OVHCEnquiryForm.aspx");

    //--------------------------------------------------

    //added by Gemma 22/12/2011
    //these functions are used by the travel insurance page
    //Travel Insurance popup - Travel Insurance MemberYN radio button click event
    jQuery('input:radio[name=MemberYN]').click(function () {
        var rdoValue = jQuery('input:radio[name=MemberYN]:checked').val();
        if (rdoValue == 1) {
            jQuery('#InputMember').css("display", "");
            jQuery('#txtMemberNo').focus();
        }
        else {
            jQuery('#InputMember').css("display", "none");
            jQuery('#msgError').css("display", "none");
        }
    });

    jQuery('#TravelContinueButton').click(function () {
        var rdoValue = jQuery('input:radio[name=MemberYN]:checked').val();
        if (rdoValue == 1) {
            jQuery('#txtMemberNo').numeric().textLimit(8);
            if (jQuery('#txtMemberNo').val() == "" || jQuery('#txtMemberNo').val() == null) {
                jQuery('#msgError').css("display", "");
                jQuery('#txtMemberNo').focus();
            } else {
                var winTravel = window.open("https://travel.qbe.com/qbe/QBETravel?login=true&aid=P6C6I37DPR3H3OE4SUHOKRHKWE", "winTravel");
                jQuery('#msgError').css("display", "none");
                winTravel.focus();

                jQuery(this).siblings('.jqmClose').click();
            }
        }
        else {
            var winTravel = window.open("https://travel.qbe.com/qbe/QBETravel?login=true&aid=SSGOJ5FRQJQQM4QBDVOT3JMWSU", "winTravel");
            winTravel.focus();

            jQuery(this).siblings('.jqmClose').click();
        }

    });

    jQuery('#GetAQuoteDialog .jqmClose').click(function () {
        jQuery('#txtMemberNo').attr('value', '');
        jQuery('#MemberY').attr('checked', 'checked');
        jQuery('#InputMember').css("display", "");
        jQuery('#msgError').css("display", "none");
    });
    //end Travel Insurance functions


    PreventCopyPasteinTextBox("txtSuburb");
    //end startupscript

});                                                                              //end jQuery / document ready.


/*
Set Current Tab for insurance page.
Added by HCF (Samir) 
*/

function setTab(elem, className) {
    //remove old classes
    jQuery('.' + className).removeClass(className);
    //add new classes        
    jQuery(elem).addClass(className);
} //end setTab


// ******************************************************************************
// ******************************************************************************
// Turns select html control into a fancy drop down control
// THIS WAS MOVED OUT OF THE DOCUMENT READY CALL AND MADE INTO A FUNCTION
// ******************************************************************************
// ******************************************************************************
function createFancyDropdowns() {
    /*
    Nice drop-downs
    */
    //replace <select>s with nice styleable <div>s

    jQuery('select.styleMe').each(function () {
        var select = jQuery(this);
        select.hide(); //hide the original select
        select.removeClass('styleMe'); //remove the class

        var genId = ''; //if the <select> has an id, prepend 'SS' and apply the id to the generated element (so we can target the new element with CSS)
        if (select.attr('id').length)
            genId = ' id="SS' + select.attr('id') + '" ';

        var genClass = ''; //if the <select> has a class, copy it to the parent
        if (select.attr('class').length)
            genClass = select.attr('class');

        select.wrap('<div class="styleselect ' + genClass + '" ' + genId + '></div>');
        var selectwrap = select.parent();

        //use the first option as the label
        var myValue = jQuery('option:selected', select).index();
        myValue = jQuery('option', select).eq(myValue).text();
        select.after('<div class="selected">' + myValue + '</div>');

        //if the value of the first option is "label", don't show it as an option
        if (jQuery('option', select).eq(0).val() == 'label')
            jQuery('option', select).eq(0).remove();

        //generate the list
        selectwrap.append('<ul></ul>');
        var list = jQuery('ul', selectwrap);
        jQuery('option', select).each(function () {
            var li = jQuery('<li>' + jQuery(this).text() + '</li>'); //create new list item
            li.data('value', jQuery(this).val()); //set the value to the value of this option
            list.append(li); //append to list
        });
    });
}


function createToolTip() {

    /*
    Tool tips / hints / help
    */

    //Mini tool tips: similar but not the same as the above code, these are inline    
    jQuery('.miniToolTip').each(function () {

        jQuery('.hidden', this).after('<span class="toolTipIcon"></span>');
        var tipText = jQuery('.hidden', this).html();
        jQuery('.hidden', this).remove(); //this is good but probably not essential
        jQuery(this).append('<div class="tip arrow"></div><div class="tip tipContent">' + tipText + '</div>');

        if (jQuery(this).is(':visible')) {
            var contentDiv = jQuery('.tipContent', this).eq(0);
            contentDiv.css('top', -(contentDiv.outerHeight() / 2) + 10); //vertical centering
        }

        jQuery(this).hover(
			function () {  //mouse in
			    jQuery(this).css('z-index', 3);
			    jQuery('.tip', this).stop(true, true).fadeIn('fast');
			    return false;

			},
			function () {  //mouse out
			    jQuery(this).css('z-index', 1);
			    jQuery('.tip', this).stop(true, true).fadeOut('fast');
			    return false;
			}
		);

    }); //end each miniToolTip




    jQuery('.toolTip').each(function () {

        var tipTextWidth = 260; //pixels
        var tipTextPaddingBoth = 30; //left and right padding total
        var arrowWidth = 21; //width of the arrow

        tipWidth = tipTextWidth + 47; //width in pixels plus left, right padding, border, shadow etc

        var tip = jQuery(this);
        tip.attr('style', 'float:right;')
        var toolTipHTML = jQuery('<span class="toolTipHidden"><span class="replaceClass"><span class="toolTipText">' + tip.text() + '</span></span></span>');
        tip.text('');

        //get distance from right edge to right edge of the window 
        var distance = jQuery(window).width() - tip.offset().left - tipWidth - arrowWidth;


        if (distance > 0) {
            //there is space, show horizontal
            jQuery('.replaceClass', toolTipHTML).addClass('horiz').removeClass('replaceClass');
            //the element has not yet been rendered but we need to know how tall it will be once it is
            var tempClone = jQuery('.toolTipText', toolTipHTML).clone().css({ visibility: "hidden", display: "block", position: "absolute" });
            jQuery('body').append(tempClone);
            var moveUp = (tempClone.height() / 2) + 27; //padding and border etc
            jQuery('.horiz', toolTipHTML).css('top', '-' + moveUp + 'px'); //move up half of height
        }
        else {
            //not enough space, vertical
            jQuery('.replaceClass', toolTipHTML).addClass('vert').removeClass('replaceClass');
            //the element has not yet been rendered but we need to know how tall it will be once it is
            var tempClone = jQuery('.toolTipText', toolTipHTML).clone().css({ visibility: "hidden", display: "block", position: "absolute" });
            jQuery('body').append(tempClone);
            var moveUp = tempClone.height() + 100; //inc padding, border, arrow
            var moveLeft = (tipTextWidth + tipTextPaddingBoth) / 2 + 8;
            jQuery('.vert', toolTipHTML).css({ top: '-' + moveUp + 'px', left: '-' + moveLeft + 'px' }); //move up half of height			
        }

        tempClone.remove();
        tip.append(toolTipHTML);

        tip.hover(
			function () { jQuery(this).css('z-index', 3); toolTipHTML.stop(true, true).show(); },
			function () { jQuery(this).css('z-index', 1); toolTipHTML.stop(true, true).hide(); }
		);

    }); //end each
}

function createPopUpWindow() {

    /*
    PopUpWindow
    */

    jQuery("[id^='popUpTrigger']").each(function () {

        var PopUpDialog = "#" + (jQuery(this).attr('id')).replace('popUpTrigger', '') + "Dialog";
        if (jQuery(PopUpDialog).length) {

            if (!jQuery.browser.msie && jQuery(PopUpDialog + " > iframe").length > 0) { // check to display iframes in jqmModal popup in non-IE browsers
                jQuery(PopUpDialog).jqm({ trigger: '#' + jQuery(this).attr('id'), modal: true });
            }
            else {
                jQuery(PopUpDialog).jqm({ trigger: '#' + jQuery(this).attr('id'), modal: true, toTop: true });
            }

            jQuery(PopUpDialog).attr('class', 'popUpDialog');
            jQuery(PopUpDialog).css('z-index', 101);
            jQuery('#jqmOverlay').css('z-index', 100);


            jQuery(this).bind('click', function () {
                jQuery('html, body').animate({
                    scrollTop: 0
                }, 500);
            });

        }

    });
}


// QuoteSelections
function QuoteSelections(index) {
    setTab('#Tab' + index, 'active');
    setTab('#Product' + index, 'show');
    setTab('#ExcessList' + index, 'showExcess');
    setTab('#Bubble' + index, 'showBubble');
    jQuery('#hdnSelectedTab').attr('value', index);
    jQuery("#hdnExcess").attr('value', jQuery("input[name='excess" + index + "']:checked").val());
    //alert(jQuery('#hdnSelectedTab').attr('value'));
}


//Quote page scripts
function SetExcess(radio) {
    jQuery("[id$=hdnExcess]").attr('value', jQuery(radio).val()); //Get the Excess Id for the Joinnow Landing page
    jQuery('#hdnExcess').attr('value', jQuery(radio).val());
}
function QuotePopUp(mode) {

    var index = jQuery('#hdnSelectedTab').attr('value');


    var HospitalCover = jQuery('#HospitalCover' + index).attr('value'); // Hospital Cover
    var ExtrasCover = jQuery('#ExtrasCover' + index).attr('value'); // Extras Cover
    var SegmentType = jQuery("select[id$='ddlSegments']").val(); //Segment Type
    var Scale = jQuery("select[id$='ddlScale']").val(); //Scale
    var State = jQuery("select[id$='ddlState']").val(); //State
    var ProductDescription = jQuery("<div/>").text(jQuery("#Product" + index).html()).html(); //Product Description
    var ProductName = jQuery("#Product" + index + " h2:first-child").html(); //Product Name
    var PriceFrequency = jQuery("a[class='inactive']").attr('name');    //Price Frequency


    var Excess = jQuery("#hdnExcess").val(); // Excess


    var Price = jQuery("#Excess" + Excess + index).next().html();    //Price        

    jQuery('#hdnSegmentType').attr('value', SegmentType);
    jQuery('#hdnProductName').attr('value', ProductName);
    jQuery('#hdnProductDescription').attr('value', ProductDescription);
    jQuery('#hdnPrice').attr('value', Price);
    jQuery('#hdnPriceFrequency').attr('value', PriceFrequency);
    SetFormValues(HospitalCover, Excess, ExtrasCover, Scale, State, ""); //Set Form Values
    var ActionURL = '';
    if (mode == 'save') {
        ActionURL = BuildURL(true, jQuery('#hdnSaveQuote').val(), "secured/save-quote/");
        jQuery('#frmProductDetails').attr('action', ActionURL);
        jQuery('#frmProductDetails').attr('target', 'SaveQuote');
        jQuery('#frmProductDetails').submit();
    }
    else {
        ActionURL = BuildURL(true, jQuery('#hdnSaveQuote').val(), "join/gettingstarted.aspx");
        Joinnow(ActionURL); //window.open and set Guid
    }
}

//Toggle Package tables display
function togglePackageTemplateTables(tabID) {
    if (jQuery('#packagesTable').length > 0) {

        jQuery(" [id^='tab']").each(function () {
            var thisID = jQuery(this).attr('id').replace("tab", "");
            if (thisID == tabID) {
                jQuery(this).addClass("active");
                jQuery(this).removeClass("inactive");
            }
            else {
                jQuery(this).removeClass("active");
                jQuery(this).addClass("inactive");
            }
        });

        jQuery(" [id^='tblFeatures']").each(function () {
            var thisID = jQuery(this).attr('id').replace("tblFeatures", "");
            if (thisID == tabID) {
                jQuery(this).show();
            }
            else {
                jQuery(this).hide();
            }

        });
    }
}

function CompareOtherFund() {
    if (jQuery('#otherFundsStepTwo').hasClass('disabled')) {
        jQuery('#otherFundsStepOne').html("STEP 1 &ndash; Edit your current fund details");
        jQuery('#otherFundsStepTwo').removeClass('disabled');
        jQuery('#otherFundsStepTwo').addClass('enabledShut');
    }

    var isvisible = jQuery('#coverOrPackageDetails').is(':visible');
    if (!isvisible) {
        compareShowHideStep2();
    }
}
function compareShowHideStep1() {
    var isDisabled = jQuery('#otherFundsStepOne').hasClass('disabled');
    if (!isDisabled) {
        jQuery('#otherFundsStepOne').toggleClass('enabledShut enabledOpen');
        jQuery('#otherFundDetails').slideToggle();
    }
}

// ----------------------------------------------
// toggle step 2
// ----------------------------------------------
function compareShowHideStep2() {
    var isDisabled = jQuery('#otherFundsStepTwo').hasClass('disabled');
    if (!isDisabled) {
        jQuery('#otherFundsStepTwo').toggleClass('enabledShut enabledOpen');
        jQuery('#coverOrPackageDetails').slideToggle();
    }
}

function SegmentJoinTrigger() {

    jQuery('.tabContent .product .button').click(function () {
        if (jQuery(this).siblings("[class^='Product']").length > 0) {
            var Hospital = jQuery(this).siblings('.ProductHospital').val();
            var Extras = jQuery(this).siblings('.ProductExtras').val();
            var Excess = jQuery(this).siblings('.ProductExcess').val();
            var Scale = jQuery(this).siblings('.ProductScale').val();
            var State = "NSW";
            SetFormValues(Hospital, Excess, Extras, Scale, State, "Segment"); //Set Form Values
            var JoinURL = BuildURL(false, "segment-products", "join-now/");
            JoinNowLanding(JoinURL)
        }
    });
    return false;
}

function ExcessListJoinTrigger() {
    jQuery('#JoinRightCol #SelectPrice .actions .button').click(function () {
        var Hospital = jQuery('.ProductHospital').val();
        var Extras = jQuery('.ProductExtras').val();
        var ActiveFreq = jQuery('.inactive').attr('name');
        var Excess = jQuery("input[name='excess" + ActiveFreq + "']:checked").val();
        var Scale = "S";

        if (jQuery("select[id$='Scale']").length > 0) {
            Scale = jQuery("select[id$='Scale']").val();
        }
        var State = "NSW";
        if (jQuery("select[id$='State']").length > 0) {
            State = jQuery("select[id$='State']").val();
        }
        SetFormValues(Hospital, Excess, Extras, Scale, State, ""); //Set Form Values
        var JoinURL = BuildURL(true, null, "healthinsurance/Join/GettingStarted.aspx");
        Joinnow(JoinURL); //window.open and set Guid
    });
}

function ExcessListControlTrigger() {
    jQuery('#RightCol .actions .button').click(function () {
        var Hospital = jQuery('.ProductHospital').val();
        var Extras = jQuery('.ProductExtras').val();
        var ActiveFreq = jQuery('.inactive').attr('name');
        var Excess = jQuery("input[name='excess" + ActiveFreq + "']:checked").val();
        var Scale = "S";

        if (jQuery("select[id$='ddlScale']").length > 0) {
            Scale = jQuery("select[id$='ddlScale']").val();
        }
        var State = "NSW";
        if (jQuery("select[id$='ddlState']").length > 0) {
            State = jQuery("select[id$='ddlState']").val();
        }
        jQuery('#hdnPriceFrequency').attr('value', ActiveFreq);
        SetFormValues(Hospital, Excess, Extras, Scale, State, "Package"); //Set Form Values
        var JoinURL = BuildURL(false, "segment-products", "healthinsurance/join-now/");
        JoinNowLanding(JoinURL)
    });
}

function Joinnow(Url) {
    var frmGuid = jQuery.Guid.New();
    jQuery("#hdnGuid").attr('value', frmGuid);
    var windowW = 870 // wide
    var windowH = 580 // hig
    var windowX = (screen.width / 2) - (windowW / 2);
    var windowY = (screen.height / 2) - (windowH / 2);

    //Height,left,location=yes|no|1|0,menubar=yes|no|1|0,resizable=yes|no|1|0,scrollbars=yes|no|1|0,status=yes|no|1|0,titlebar=yes|no|1|0,toolbar=yes|no|1|0,top=pixels,width=pixels
    var WinParms;
    WinParms = 'scrollbars=yes,toolbar=no,height=' +
                                    (window.screen.availHeight - 100).toString() + ',width=' + (window.screen.availWidth - 10).toString() + ',screenX=0,screenY=0,left=0,top=0, resizable=yes';

    if (jQuery.browser.safari) //Safari browser do not support readonly address bar so hide the location
        WinParms = WinParms + ',location = no';
    else
        WinParms = WinParms + ',location = 1';

    winName = frmGuid.replace(/-/g, '') //IE window name will not allow '-'. hence - is removed
    var Join = window.open('about:blank', winName, WinParms);
    jQuery('#frmProductDetails').attr('action', Url);
    jQuery('#frmProductDetails').attr('target', winName);
    jQuery('#frmProductDetails').submit();
    if (typeof (Join) != 'undefined') {
        Join.focus();
    }
}

function JoinNowLanding(Url) {
    jQuery('#frmProductDetails').attr('action', Url);
    jQuery('#frmProductDetails').submit();
}
function SetFormValues(HospitalCover, Excess, ExtrasCover, Scale, State, strReference) {

    var frmHospital, frmExtras, frmExcess, frmScale, frmState, frmSegment;

    //check for any undefined values in the above variables and assign to string empty before assigning to the hidden variables 
    frmHospital = typeof (HospitalCover) == 'undefined' ? "" : HospitalCover;
    frmExcess = typeof (Excess) == 'undefined' ? "" : Excess;
    frmExtras = typeof (ExtrasCover) == 'undefined' ? "" : ExtrasCover;
    frmScale = typeof (Scale) == 'undefined' ? "" : Scale;
    frmState = typeof (State) == 'undefined' ? "" : State;
    jQuery('#hdnReference').attr('value', strReference);
    frmSegment = typeof (jQuery("[id$=hdnSegment]").attr('value')) == 'undefined' ? "" : jQuery("[id$=hdnSegment]").attr('value');
    if (frmSegment != "")
        jQuery('#hdnSegmentType').attr('value', frmSegment);
    jQuery('#hdnHospitalCover').attr('value', frmHospital);
    jQuery('#hdnExtrasCover').attr('value', frmExtras);
    jQuery('#hdnScale').attr('value', frmScale);
    jQuery('#hdnState').attr('value', frmState);
    jQuery("#hdnExcess").attr('value', frmExcess);

}

function BuildURL(isSecured, stripUrlStartString, UrlAppendString) {
    var ReturnURL = '';
    var endIndex = window.location.href.length;
    var isStripStringFound = false;
    if (window.location.href.toLowerCase().indexOf(stripUrlStartString) >= 0) {
        endIndex = window.location.href.toLowerCase().indexOf(stripUrlStartString)
        isStripStringFound = true;
    }
    else {
        endIndex = window.location.href.toLowerCase().indexOf("/", 7)
    }
    var URL = window.location.href.substring(0, endIndex);

    if (URL.toLowerCase().indexOf('hcf.com.au') >= 0) {

        if (isSecured) {

            if (isStripStringFound) {
                ReturnURL = URL.replace('http', 'https') + UrlAppendString;
            }
            else {
                ReturnURL = URL.replace('http', 'https') + "/" + UrlAppendString;
            }

        }
        else {

            if (isStripStringFound) {

                ReturnURL = URL + UrlAppendString;

            }
            else {

                ReturnURL = URL + "/" + UrlAppendString;

            }
        }
    }
    else {
        if (isStripStringFound) {
            ReturnURL = URL + UrlAppendString;
        }
        else {
            ReturnURL = URL + "/hcfwebsite/" + UrlAppendString; //Note: "hcfwebsite" is hardcoded
        }
    }

    return ReturnURL;
}

function addRequiredFieldIndicators() {
    jQuery('span.label.req').append('<span class="pink">*</span>');
}

function PrefixZeros(Control, Maxlength) {
    var FieldValue = Control.value;
    var ZerosRequired = Maxlength - FieldValue.length;
    var strPrefixZero = "";
    if (FieldValue != "") {
        for (var i = 1; i <= ZerosRequired; i++) {
            strPrefixZero += "0";
        }
        Control.value = strPrefixZero + Control.value;
    }

}
function StripHTMLTags(content) {
    var contentText = jQuery('<div></div>').append(content).text();
    return contentText;
}

function NormaliseResourcePaths() {
    if (window.location.href.toLowerCase().indexOf('localhost') >= 0) {

        var targetAttributes = new Array("src", "href");

        for (var countAttr = 0; countAttr < targetAttributes.length; countAttr++) {

            jQuery("[" + targetAttributes[countAttr] + "^='/']").each(function () {

                if (jQuery(this).attr(targetAttributes[countAttr]).toLowerCase().indexOf("hcfwebsite") == -1) {

                    jQuery(this).attr(targetAttributes[countAttr], '/hcfwebsite' + jQuery(this).attr(targetAttributes[countAttr]));

                }

            });

        }
    }

}

function TriggerSubmitButtton(fieldID, buttonID) {

    jQuery('#' + fieldID).keyup(function (event) {
        if (event.keyCode == 13) {
            jQuery('#' + buttonID).click();
        }
    });

}

function GetQuote() {
    var fsegmentType = jQuery("select[id$='ddlSegments']").val();
    var fstate = jQuery("select[id$='ddlState']").val();
    var fcoverFor = jQuery("select[id$='ddlScale']").val();
    if (fcoverFor != "" && fstate != "" && fsegmentType != "") {
        //jQuery("#spnQuoteRequired").addClass('hidden');
        jQuery('#hdnSegmentType').attr('value', fsegmentType);
        jQuery('#hdnState').attr('value', fstate);
        jQuery('#hdnCoverFor').attr('value', fcoverFor);
        jQuery('#frmSegmentDetails').attr('action', 'healthinsurance/get-a-quote/');
        jQuery('#frmSegmentDetails').submit();
    }
    else {
        if (fsegmentType == "") {
            jQuery("select[id$='ddlSegments']").parent().addClass('error');
        }
        else {
            jQuery("select[id$='ddlSegments']").parent().removeClass('error');
        }

        if (fstate == "") {
            jQuery("select[id$='ddlState']").parent().addClass('error');
        }
        else {
            jQuery("select[id$='ddlState']").parent().removeClass('error');
        }

        if (fcoverFor == "") {
            jQuery("select[id$='ddlScale']").parent().addClass('error');
        }
        else {
            jQuery("select[id$='ddlScale']").parent().removeClass('error');
        }
        alert("Please select your criteria.");
    }

}

function ResumeQuote() {
    var Quote = jQuery.trim(jQuery('#QuoteNumber').val());
    if (Quote == jQuery('#QuoteNumber').attr("title") || Quote == "") {
        jQuery('#QuoteNumber').val('');
        jQuery("#resumeError").addClass('error');
        alert("Please enter your quote number");
    }
    else {
        jQuery('#hdnQuoteReference').attr('value', Quote);
        jQuery('#frmSegmentDetails').attr('method', 'post');
        jQuery('#frmSegmentDetails').attr('action', 'healthinsurance/your-quote/');
        jQuery('#frmSegmentDetails').submit();
    }
}

function CompareOtherFund() {//this will be changed  to use the form values user control
    var CFFund = jQuery("select[id$='ddlCFFund']").val();
    var CFstate = jQuery("select[id$='ddlCFState']").val();
    var CFcoverFor = jQuery("select[id$='ddlCFScale']").val();
    var CFcoverType = jQuery("select[id$='ddlCFCoverType']").val();
    if (CFFund != "" && CFstate != "" && CFcoverFor != "") {
        //jQuery("#spnCompareRequired").addClass('hidden');
        jQuery('#hdnOtherFund').attr('value', jQuery("select[id$='ddlCFFund']").val());
        jQuery('#hdncfState').attr('value', jQuery("select[id$='ddlCFState']").val());
        jQuery('#hdncfScale').attr('value', jQuery("select[id$='ddlCFScale']").val());
        jQuery('#hdncfCoverFor').attr('value', jQuery("select[id$='ddlCFCoverType']").val());
        jQuery('#frmCompareProduct').attr('action', 'healthinsurance/Compare-other-funds/');
        jQuery('#frmCompareProduct').submit();
    }
    else {
        if (CFFund == "") {
            jQuery("select[id$='ddlCFFund']").parent().addClass('error');
        }
        else {
            jQuery("select[id$='ddlCFFund']").parent().removeClass('error');
        }

        if (CFstate == "") {
            jQuery("select[id$='ddlCFState']").parent().addClass('error');
        }
        else {
            jQuery("select[id$='ddlCFState']").parent().removeClass('error');
        }

        if (CFcoverFor == "") {
            jQuery("select[id$='ddlCFScale']").parent().addClass('error');
        }
        else {
            jQuery("select[id$='ddlCFScale']").parent().removeClass('error');
        }
        alert("Please select your criteria.");
    }
}

function gaEv(c, a, v, u) {
    try { pageTracker._trackEvent(c, a, v); }
    catch (err) { }
    if (u.indexOf(".pdf") != -1) {
        var newWindow = window.open(u, '_blank');
        newWindow.focus();
    }
    else {
        document.location.href = u;
    }
}



function AgentsValidateGender(source, args) {
    var blnVal = false;
    var id = GetIdFromCustomValidators(source);
    var msgFor = MsgFor(source);
    var rbtnGenderValue = jQuery("[id$=" + id + "rbtnGender] :radio:checked").val();
    var SelectedTitle = jQuery("#" + id + "ddlTitle :selected").val();
    if (rbtnGenderValue != null) {
        blnVal = AgentsMatchGenderTitle(SelectedTitle, rbtnGenderValue);
        source.errormessage = msgFor + " Title does not match with gender";
    }
    else {
        source.errormessage = "Please select your " + msgFor.toLowerCase() + " gender";
        blnVal = false;
    }
    args.IsValid = blnVal;
}



function AgentsMatchGenderTitle(Title, Gender) {
    var Valid = "";
    if (Title == "Dr" || Title == "Professor") {
        Valid = true;
    }
    else if (Gender != "") {
        switch (Gender) {
            case "M":
                if (Title.match(regexMaleTitle) && Title != "Mrs")
                    Valid = true;
                break;
            case "F":
                if (Title.match(regexFemaleTitle))
                    Valid = true;
                break;
            default:
                Valid = false;
                break;
        }
    }
    else {
        Valid = false;
    }

    return Valid;
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}

function ValidateStudentDependantConfirmation(source, args) {
    var confirm = jQuery("[id$='chkConfirm']");
    args.IsValid = confirm.attr("checked");
}

function HookupSuburbChangeandLoadEvent() {

    if (jQuery("[id$='txtSuburb']").length > 0) {
        if (jQuery("[id$='txtSuburb']").attr('onchange') == null) {
            jQuery("[id$='txtSuburb']").change(function () {
                getPostcode("'" + jQuery("[id$='txtSuburb']").attr('id') + "','" + jQuery("[id$='ddlState']").attr('id') + "','" + jQuery("[id$='ddlPostCode']").attr('id') + "'");
            });
        }

        jQuery("[id$='txtSuburb']").change();
    }
}

//prevent user to paste text in suburb textbox
function PreventCopyPasteinTextBox(ctrltxt) {
    jQuery('input[id$=' + ctrltxt + ']').bind('cut copy paste', function (e) { e.preventDefault(); });  //Prevent cut copy pate on suburb textbox
}



