﻿/**
* Common Javascript Methods
*
* @author 		Zone
* @email		info@zonecontent.com
* @url 		http://www.zonecontent.com/
* @copyright 	Copyright (c) 2011, zonecontent.com. All rights reserved.
* @version		0.0.1
*/

(function ($) {

    $.fn.bupaTooltips = function () {

    return this.each(function () {
      var $this = $(this);
      var $tooltipText = $this.css('display', 'none').html();
      var $tooltipBtn = $('<a href="#" class="help-button">Help</a>');
      $this.siblings(':first-child').prepend($tooltipBtn);
      var $dialog = $('<div class="tooltip-dialog"><span class="tooltip-arrow"></span><a href="#" class="tooltip-close">Close</a><span class="tooltip-text">' + $tooltipText + '</span></div>').hide();
      $('body').append($dialog);
      var $close = $dialog.find('.tooltip-close').click(function () {
        $dialog.hide();
        return false;
      });
      $tooltipBtn.click(function () {
        $dialog.toggle();
        return false;
      });
      var $pos = $tooltipBtn.offset();
      var $left = $pos.left + $tooltipBtn.width() + 20;
      var $top = $pos.top - 20;
      $dialog.css({ left: $left + 'px', top: $top + 'px', position: 'absolute' });
        });

    };

})(jQuery);


(function ($) {

  $.fn.bupaSiteTooltips = function () {

    return this.each(function () {
      var $this = $(this);
      var $tooltipText = $this.attr('title');
      $this.attr('title', '');

      var $dialog = $('<div class="tooltip-dialog site-tooltip"><span class="tooltip-arrow"></span><span class="tooltip-text">' + $tooltipText + '</span></div>').hide();
      
      $('body').append($dialog);

      $this.hover(
        function () {
          //if (!$dialog.hasClass('tooltip-processed')) {
            var $pos = $this.offset();
            var $left = $pos.left + $this.outerWidth() + 14;
            var $top = $pos.top + ($this.outerHeight() / 2) - 25;
            $dialog.css({ left: $left + 'px', top: $top + 'px', position: 'absolute' }).addClass('tooltip-processed');
          //}
          $dialog.show();
        }, 
        function () {
          $dialog.hide();
        });      
    });
  };
})(jQuery);


/*****************************************
Header Flyout Menu - Subnav hover items
*****************************************/

$('#access > ul > li > .flyout > ul > li').live('hover',
  function () {
      $(this).find('.subnavFlyout').clone().replaceAll($(this).parent().parent().find('.replacedContent'));
      $('.flyout_detail > .subnavFlyout').addClass('replacedContent');
  }
);

/*****************************************
Header Flyout Menu
*****************************************/

$('#access > ul > li').hover(
  function () {
    $(this).find('div.flyout').html($("div#flyout_" + $(this).attr('id')).html());
    $(this).find('div.flyout').stop(true, true).delay(300).fadeIn(100);
    $(this).addClass('selected');
  }, function () {
    $(this).find('div.flyout').stop(true, true).fadeOut(100);
    $(this).removeClass('selected');
  }
);

/*****************************************
Utility Nav Dropdowns
*****************************************/



function utilityNavDropDown() {
  var $utilityNavBtn = $('#utilitynav > ul > li.dropdown > a');

  $utilityNavBtn.click(
  function () {
    $parent = $(this).parent();
    $(this).siblings('div.ut_dropdown').toggle(100);

    $parent.toggleClass('selected');

    $parent.siblings('li').removeClass('selected').children('div.ut_dropdown').hide(100);

    return false;
  });
}


/***************************
Header Country Select Dropdown
**************************/
$(document).ready(function () {
    $('#ut_selectCountry, #sitechooser').accordion({
        header: 'li a.header',
        active: false,
        clearStyle: true,
        collapsible: true
    });
});

/*****************************************
Lightboxes
*****************************************/
var $timeline = $('.timeline ol li a[rel="timeline"]');
var $gallery = $('.gallery ul li a[rel="gallery"]');
var $profile = $('ol.profiles li a[rel="profile"]');

$timeline.colorbox({
    href: function () {
        return $(this).attr('href') + '?altTemplate=TimelineDetailLightBox';
    },
    iframe: true,
    innerWidth: '710px',
    innerHeight: '710px',
    scrolling: true
});


$gallery.colorbox({
    href: function () {
        return $(this).attr('href') + '?altTemplate=ImageGalleryLightboxDetail';
    },
    iframe: true,
    innerWidth: '710px',
    innerHeight: '710px',
    scrolling: true
});

$profile.colorbox({
    href: function () {
        return $(this).attr('href') + '?altTemplate=SportsInsuranceProfileLightboxDetail';
    },
    iframe: true,
    innerWidth: '580px',
    innerHeight: '610px',
    scrolling: true
});

$('.textclose').html('Close');
$('.textclose').click(function () {
    parent.$timeline.colorbox.close();
    parent.$gallery.colorbox.close();
    parent.$profile.colorbox.close();
    return false;
});




/*****************************************
FAQs
*****************************************/
$('.faqs dl.faqs dt:first, .faqs dl.faqs dd:first').addClass('active');
$('.faqs dl.faqs dt').click(function () {
    var $this = $(this);
    if ($this.hasClass('active')) {
        $this.next('dd').animate({ height: 'hide', opacity: 'hide' }, 'fast', function () { $this.removeClass('active'); $(this).removeClass('active'); });
    } else {
        $this.next('dd').animate({ height: 'show', opacity: 'show' }, 'fast', function () { $this.addClass('active'); $(this).addClass('active'); });
    }
});


/*****************************************
Hide/Show Content
*****************************************/
$('.hide-show').find('dt').prepend('<span title="Hide/Show services menu" class="hideShowToggle">Show <span class="icon">+</span></span>');
$('.hide-show').find('dd').hide();

$('.hide-show dt').click(function () {
    var $this = $(this);
    if ($this.hasClass('active')) {
        $this.next('dd').animate({ height: 'hide', opacity: 'hide', backgroundColor: '#fff' }, 'fast', function () { $this.removeClass('active'); $(this).removeClass('active'); });
        $this.find('.hideShowToggle').html('Show <span class="icon">+</span>');
    } else {
        $this.next('dd').animate({ height: 'show', opacity: 'show', backgroundColor: '#ebf6ff' }, 'fast', function () { $this.addClass('active'); $(this).addClass('active'); });
        $this.find('.hideShowToggle').html('Hide <span class="icon-less">-</span>');
    }
});


/***************************
Hide show footer
**************************/
$('.collapse').hide();
var $showhtml = '<a href="#" title="Hide/Show services menu"> Show quick links <span class="icon">+</span></a>';
var $hidehtml = '<a href="#" title="Hide/Show services menu"> Hide quick links <span class="icon">-</span></a>';
$('#hidefooter').html($showhtml);

$('#hidefooter').toggle(
  function () {
      var $this = $(this);
      $this.html($hidehtml);

      $(".collapse").animate({ /* Show footer contents **/
          height: 'show',
          opacity: 'show'
      }, 'slow');
      $('html, body').animate({
          scrollTop: $("footer").offset().top
      }, 'slow');
      return false;

  }, function () {
      var $this = $(this);
      $this.html($showhtml);

      $(".collapse").animate({ /* Hide footer contents **/
          height: 'hide',
          opacity: 'hide'
      }, 'slow');
      return false;
  }
  );

/***************************
Search Filter
**************************/
$('div.search-filter > ul > li > span').click(function () {
    $(this).parent().toggleClass('active');
});

$('#btn-search').click(function () {

    $.post("/callback/search/save-terms/default.ashx", {
        SearchTerm: $("#searchfield").val()
    },
        function (response) {
        });

});


/*****************************
Poll
*****************************/


$("section.poll_module").find("input[type='submit']").click(function (e) {
    e.preventDefault();
    var pollSection = $(this).parentsUntil('section').parent();

    if ($(pollSection).find("input[name='PollAnswerId']:checked").val() != undefined) {

        $(pollSection).children("form").addClass('hidden');
        $(pollSection).children('.ajax_loader').removeClass('hidden');

        $.ajax({
            async: false,
            type: 'GET',
            url: $(pollSection).children("form").attr('action') + "?PollAnswerId=" + $(pollSection).find("input[name='PollAnswerId']:checked").val() + "&PollId=" + $(pollSection).find("input[name='PollId']").val(),
            dataType: "json",
            success: function (response) {
                if (response != null) {
                    $.each(response, function (i, item) {

                        var currentChartWidth = $(pollSection).find(".poll_results > li:nth-child(" + parseInt(i + 1) + ")").find("div.bar_chart").width();
                        var newChartWidth = Math.floor(response[i].Percentage) + '%';

                        $(pollSection).find(".poll_results > li:nth-child(" + parseInt(i + 1) + ")").find("div.bar_chart").width(0)

                        $(pollSection).find('.ajax_loader').addClass('hidden');
                        $(pollSection).find('.poll_results').removeClass('hidden');

                        $(pollSection).find(".poll_results > li:nth-child(" + parseInt(i + 1) + ")").find("div.bar_chart").animate({
                            width: newChartWidth
                        }, 300, function () {
                            $(pollSection).find(".poll_results > li:nth-child(" + parseInt(i + 1) + ")").find("span.poll_percentage").html(response[i].Percentage + "%");
                            $(pollSection).find(".poll_results > li:nth-child(" + parseInt(i + 1) + ")").find("span.poll_percentage").removeClass('hidden');
                        });

                    })
                } else {
                    $(pollSection).find('.ajax_loader').addClass('hidden');
                    $(pollSection).children("form").removeClass('hidden');
                }
            },
            error: ajaxFailure
        });

    }

});


/***************************
AddThis - Share buttons
**************************/
var addthis_config =
{
  ui_delay: '100',
  ui_offset_top: '-50',
  ui_offset_left: '140'
}

/***************************
Briefcase
**************************/

/* Briefcase functions **************/
$('#ut_briefcase li.briefcase-item .delete').click(function (e) {
    deleteBriefcaseItem($(this));
    e.preventDefault();
});

/* Add to Briefcase message **************/
$('#add-briefcase > a').click(function (e) {
    callBriefcaseAction($(this));
    e.preventDefault();
});

/* Delete from Briefcase  **************/
$('#remove-briefcase > a').click(function (e) {
    callBriefcaseAction($(this));
    e.preventDefault();
});


/***************************
Text Resize
**************************/
$('.resizeSmaller').click(function () {
    setTextSize(13);
    SetCookie('bupatextsize', 14, 5);
    return false;
});

$('.resizeReset').click(function () {
    setTextSize(16);
    SetCookie('bupatextsize', 16, 5);
    return false;
});

$('.resizeLarger').click(function () {
    setTextSize(18);
    SetCookie('bupatextsize', 18, 5);
    return false;
});




/***************************
Briefcase AJAX functions
**************************/
function deleteBriefcaseItem(button) {
    $.ajax({
        async: false,
        type: 'GET',
        url: button.attr('href') + '&ajax=true',
        dataType: "json",
        success: function (response) {
            if (response.Success) {
                $('#briefcase-count').text(response.Count);
                if (response.Count == 0) {
                    button.parents('ul:first').children('li:last').removeClass('last');
                }
                button.parents('.briefcase-item:first').remove();
            }

            if (response.InBriefcase) {
                $('#add-briefcase').addClass('hidden');
                $('#remove-briefcase').removeClass('hidden');
            } else {
                $('#add-briefcase').removeClass('hidden');
                $('#remove-briefcase').addClass('hidden');
            }
        },
        error: ajaxFailure
    });
}

function callBriefcaseAction(button) {
  $.ajax({
    async: false,
    type: 'GET',
    url: button.attr('href') + '&ajax=true',
    dataType: "json",
    success: function (response) {
      var message;
      if (response.Success) {
        if (response.Added) {
          message = 'The file "<b>' + response.PageTitle + '</b>" has been added to the briefcase';
        }
      } else {
        message = 'There has been an error in the briefcase'
      }
      if (message) {
        $('body').prepend('<div class="briefcase_overlay" style="display:none"><span>' + message + '</span></div>');
        $(".briefcase_overlay").fadeIn(1500).fadeOut(2000);
      }

      if (response.InBriefcase) {
        $('#add-briefcase').addClass('hidden');
        $('#remove-briefcase').removeClass('hidden');
      } else {
        $('#add-briefcase').removeClass('hidden');
        $('#remove-briefcase').addClass('hidden');
      }
      $("#ut_briefcase").html(response.Briefcase);
      $('#ut_briefcase li.briefcase-item .delete').click(function (e) {
        deleteBriefcaseItem($(this));
        e.preventDefault();
      });
      utilityNavDropDown();
    },
    error: ajaxFailure
  });
}


function ajaxFailure(xhr, error) {
    alert('Error: ' + error + '\n' + xhr.responseText);
}




/***************************
Form styling
**************************/

//$(function() {
//    //find all form with class jqtransform and apply the plugin
//  $(".healthform").jqTransform();
//});


$('div.datepicker').find('span').prepend('<a href="#" class="datepicker-trigger" title="Show the datepicker">Datepicker</a>');


$('.datepicker-trigger').click(function () {
    $(this).parent().find('input').focus();

    return false;
});


  $('form small').bupaTooltips();
  
  $('.tooltip').bupaSiteTooltips();


// Form fieldset highlighting
var $formfields = $('#content form input, #content form textarea, #content form select');

$formfields.focusin(function () {
  $(this).closest('fieldset').css('background-color', '#F4F9FC');
});

$formfields.focusout(function () {
    $(this).closest('fieldset').css('background-color', '#fff');
});


// IE 6/7 form field :focus
var $IEinputFocus = $('.ie7 form input, .ie7 form textarea, .ie7 form select, .ie6 form input, .ie6 form textarea, .ie6 form select');

$IEinputFocus.focusin(function () {
  $(this).css('border-color', '#68A5D8');
});

$IEinputFocus.focusout(function () {
  $(this).css('border-color', '#D8D8D8');
});



/***************************
Form Placeholders
**************************/
// only add the script if placeholders aren't available
if (!Modernizr.input.placeholder) {
    jQuery('[placeholder]').focus(function () {
        var input = jQuery(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('').removeClass('placeholder');
        }
    }).blur(function () {
        var input = jQuery(this);
        if (input.val() == '') {
            input.val(input.attr('placeholder')).addClass('placeholder');
        }
    }).blur();
    jQuery('form').submit(function () {
        jQuery('[placeholder]', this).each(function () {
            var input = jQuery(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('').removeClass('placeholder');
            }
        });
    });
}

$(document).ready(function () {
  utilityNavDropDown();
});
