//init local bk settings
var BK = BK || {};
var parts = CulturePrefix.split('/');
var CORPORATE = BK[parts[1]][parts[2]].CORPORATE;

(function() {

	$.fn.podSlideshow = function(options) {
		var opts = $.extend({}, $.fn.podSlideshow.defaults, options);
		var slideshowTimer;

		return this.each(function() {
			$this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

			$this.find('ul.slideshow').css('height', $this.find('ul.slideshow li:first').outerHeight());
			$this.find('ul.slideshow li:first').addClass('active');
			$('ul.pagination li a[href=#' + $('ul.slideshow li.active').attr('id') + ']').addClass('active');

			$this.find('ul.pagination li a').click(function() {
				swap(this, 'user');
				return false;
			});

			function swap(obj, caller) {
				if (caller == 'user') { stopTimer(); }
				$link = $(obj);
				if (!$this.find($link.attr('href')).hasClass('active')) {
					$link.addClass('active').parent().siblings().find('a').removeClass('active');
					var $onDeck = $this.find($link.attr('href'));

					$this.find('ul.slideshow li.active').fadeOut(500, function() {
						$(this).removeClass('active');
						$onDeck.addClass('active');
						$onDeck.fadeIn('slow');
					});
				}
			}

			setTimer();

			$this.click(function() {
				stopTimer();
			}, function() {
				setTimer();
			});

			function stopTimer() {
				//console.log('timer stopped');
				clearInterval(slideshowTimer);
			}

			function setTimer() {
				//console.log('timer start');
				slideshowTimer = setInterval(function() {
					if ($this.find('ul.pagination li a.active').parent().next().size() == 1) {
						var $nextPage = $this.find('ul.pagination li a.active').parent().next().find('a');
					} else {
						var $nextPage = $this.find('ul.pagination li a:first');
					}
					swap($nextPage, 'timer');
				}, 10000);
			}

		});
	};

	$.fn.newsSlideshow = function(options) {
		var opts = $.extend({}, $.fn.newsSlideshow.defaults, options);
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

			function setActive($obj, transition) {
				if (!$obj.hasClass('active')) {
					if (transition) {
						$obj.find('p.hero_image').css('opacity', 0);
						$obj.addClass('active').siblings().removeClass('active');
						$obj.find('p.hero_image').animate({
							opacity: 1
						}, 'fast', function() {
							$obj.siblings().removeClass('previous');
							$obj.addClass('previous');
						});

					} else {
						$obj.addClass('active').siblings().removeClass('active');
					}
				}
			}

			function setTimer() {
				slideshowTimer = setInterval(function() {
					if ($this.find('li.active').next().size() == 1) {
						var $next = $this.find('li.active').next();
					} else {
						var $next = $this.find('li:first');
					}
					setActive($next, true);
				}, o.timer);
			}

			setTimer();

			$this.hover(function() {
				clearInterval(slideshowTimer);
			}, function() {
				setTimer();
			});

			$this.find('li').bind('mouseenter', function() {
				setActive($(this));
			});

		});
	};

	$.fn.newsSlideshow.defaults = {
		timer: 3000
	};


	$.fn.selectReplace = function(options) {
		if (!($.browser.msie && $.browser.version < 7)) {
			var opts = $.extend({}, $.fn.selectReplace.defaults, options);
			return this.each(function() {
				var $this = $(this);
				var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

				$this.wrap('<span id="' + $this.attr('id') + '_wrapper" class="select_wrapper"></span>').before('<span>' + $this.find('option[value=' + $this.val() + ']').html() + '</span>');
				$this.css("opacity", 0);

				$this.change(function() {
					$this.parent().find('span').html($this.find('option[value=' + $this.val() + ']').html());
				}).hover(function() {
					$this.css('cursor', 'pointer');
				}, function() {
					$this.css('cursor', 'default');
				});

			});
		}
	};

	$.fn.submitReplace = function(options) {
		var opts = $.extend({}, $.fn.submitReplace.defaults, options);
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

			$this.wrap('<span class="submit_wrapper"></span>');
			$this.css('opacity', 0);
			$this.hover(function() {
				$this.css('cursor', 'pointer');
			}, function() {
				$this.css('cursor', 'default');
			});

		});
	};
	$.fn.radioReplace = function(options) {
		var opts = $.extend({}, $.fn.radioReplace.defaults, options);
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

			$this.wrap('<span class="radio"></span>');
			$this.css('opacity', 1);
			$this.css('position', 'relative');
			$this.css('left', '-3px');
			$this.hover(function() {
				$this.css('cursor', 'pointer');
			}, function() {
				$this.css('cursor', 'default');
			});
		});
	};

	$.fn.addHoverClass = function(options) {
		var opts = $.extend({}, $.fn.addHoverClass.defaults, options);
		return this.each(function() {
			var $this = $(this);
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

			$this.hover(function() {
				$(this).addClass('hover');
			}, function() {
				$(this).removeClass('hover');
			});

		});
	};
})(jQuery);


(function() {

	$.fn.modalVideo = function(options) {
		var opts = $.extend({}, $.fn.modalVideo.defaults, options);
		return this.each(function() {
			var $this = $(this);
			var o = $.metadata ? $.extend({}, opts, $this.metadata()) : opts;
			var videoURL = $this.attr('rel');
			var mediaType;

			for (var media in $.fn.modalVideo.media) {
				if (videoURL.search($.fn.modalVideo.media[media].pattern) != -1) {
					mediaType = media;
				} else { }
			}

			$this.click(function(e) {
				if (mediaType) {

					e.preventDefault();
					var $modalOverlay = o.container;
					$modalOverlay.find(o.dismissButton).click(function() {
						garbageCleanup($modalOverlay, o);
						$.fn.modalVideo.dismiss($modalOverlay, o);
						return false;
					});
					$(o.scope).bind('keypress.dismissModalVideoOverlay', function(e) {
						if (e.keyCode == 27) {
							garbageCleanup($modalOverlay, o);
							$.fn.modalVideo.dismiss($modalOverlay, o);
						}
					});
					$modalOverlay.find(o.caption).html($this.attr('title'));
					if (o.link_text) {
						$modalOverlay.find(o.utility).html(o.link_text.replace("~", "'"));
					}
					else {
						$modalOverlay.find(o.utility).html(CORPORATE.SEE_MORE_VIDEOS);
					}
					if (o.link_url) {
						$modalOverlay.find(o.utility).attr('href', o.link_url);
					}
					else {
						$modalOverlay.find(o.utility).attr('href', CulturePrefix + 'company-info/press/public-archive.html');
					}
          if (o.link_target) {
						$modalOverlay.find(o.utility).attr('target', o.link_target);
					}
					else {
						$modalOverlay.find(o.utility).attr('target', '_self');
					}

					if (o.uiBlock) {
						o.uiBlock.appendTo(o.scope).css({
							display: 'block',
							opacity: 0
						}).animate({
							opacity: 0.8
						}, 'fast');
					}

					initOverlay($modalOverlay, o, function() {
						$.fn.modalVideo.media[mediaType].execution($modalOverlay, videoURL, o);
					});

					if ($.browser.msie && $.browser.version < 7) {
						var intContentHeight = parseInt(($('#Content').height() + 35), 10);
						$('.UIBlock').css({ 'height': intContentHeight });
					}

				}
			});
			
			if (BK.NewsItemID && $this.attr('id') == BK.NewsItemID) {
				$this.trigger('click');
			}
		});
	};

	function initOverlay(overlay, options, callback) {
		if (callback && typeof (callback) == 'function') {
			if ($.browser.msie && $.browser.version < 7) {
				$('#year').hide();
				$('#sort').hide();
				$('#narrow').hide();
			}
			overlay.css({
				width: parseInt(options.width, 10) + 20
			}).find(options.flashContent).css({
				width: parseInt(options.width, 10),
				height: parseInt(options.height, 10) + parseInt(options.controlHeight, 10)
			});
			overlay.appendTo(options.scope).css({
				display: 'block',
				opacity: 1,
				marginTop: (parseInt(options.height, 10) + parseInt(options.controlHeight, 10)) / -2,
				marginLeft: parseInt(options.width, 10) / -2
			});
			overlay.animate({
				opacity: 1
			}, 'fast', function() {
				callback();
			});
		}
	}

	function garbageCleanup(overlay, options) {
    $(overlay).find(options.flashContent).attr('style', '');
	}

	$.fn.modalVideo.dismiss = function(overlay, options) {
		if ($.browser.msie && $.browser.version < 7) {
			$('#year').show();
			$('#sort').show();
			$('#narrow').show();
		}
		if (options.uiBlock) {
			options.uiBlock.fadeOut('fast', function() {
				$(this).remove();
			});
		}
		overlay.fadeOut('fast', function() {
			$(this).find(options.flashContent).html('');
			$(this).remove();
			
			// IE6 is touchy about this; detect the object and function 
			// sequentially before firing the pause function.			
			if ( typeof videoElement === 'object' ) { 
				if ( typeof videoElement.pause === 'function' ) {
					videoElement.pause(); 
				}
			}
		});
		$(options.scope).unbind('keypress.dismissModalVideoOverlay');
	};

	$.fn.modalVideo.media = {
		youtube: {
			pattern: new RegExp(/^http:\/\/www.youtube.com\/watch\?v=\w/),
			execution: function(overlay, videoURL, options) {
				var embedToken = videoURL.replace(/^http:\/\/www.youtube.com\/watch\?v=/, '');
				overlay.find(options.flashContent).html('<object width="' + options.width + '" height="' + options.height + '"><param name="movie" value="http://www.youtube.com/v/' + embedToken + '&hl=en&fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + embedToken + '&h1=en&fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="' + options.width + '" height="' + options.height + '"></embed></object>');
			}
		},
		hosted: {
			pattern: new RegExp(/\/.{0,1000}[.]{1}(flv)\b/gi),
			execution: function(overlay, videoURL, options) {

				var vidhtml = '';
				var mp4Link = videoURL.replace('/cms/','/cms_prep/').replace('flv','mp4');
				var oggLink = videoURL.replace('/cms/','/cms_prep/').replace('flv','ogg');
				var webmLink = videoURL.replace('/cms/','/cms_prep/').replace('flv','webm');

				vidhtml += '<div class="video-js-box">';
				vidhtml += '<video class="video-js" width="'+options.width+'" height="'+options.height+'" preload >';
				vidhtml += '<source src="' + oggLink + '" type=\'video/ogg; codecs="theora, vorbis"\'>';
				vidhtml += '<source src="' + mp4Link + '" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\'>';
				//vidhtml += '<source src="' + webmLink + '" type=\'video/webm; codecs="vp8, vorbis"\'>';
				vidhtml += '<embed width="'+options.width+'" height="'+(options.height + options.controlHeight)+'" bgcolor="#000000" ';
				vidhtml += 'allowfullscreen="true" allowscriptaccess="always" type="application/x-shockwave-flash" ';
				vidhtml += 'src="/page_templates/cultures' + CulturePrefix + 'flash/BKVideoPlayer.swf" pluginspage="http://www.adobe.com/go/getflashplayer" ';
				vidhtml += 'flashvars="videoType=progressive&amp;videoURL='+videoURL+'&amp;width='+options.width+'&amp;height='+(options.height + options.controlHeight)+'">';
				vidhtml += '</embed>';
				vidhtml += '</video>';
				vidhtml += '<div class="replay"><span class="replayArrow"></span></div>';
				vidhtml += '</div>';
        		
				overlay.find(options.flashContent).html('').html(vidhtml);
				VideoJS.setup();
				$('.replay').mouseover(function(){$('.vjs-controls').stop().css('bottom','0px')});
				$('.replay').click(function(){videoElement.play();});
				
				if ( testFor.htmlvideo() ) {
					videoElement.play()
				};
			}
		},
		
		hostedImage: {
			
			pattern: new RegExp(/\/.{0,1000}[.]{1}(jpg|gif|png|jpeg)\b/gi),
			execution: function(overlay, imgURL, options) {

				var imghtml = '';

				imghtml += '<div class="video-js-box">';
				imghtml += '<img src="'+imgURL+'" alt="" width="'+options.width+'" height="'+options.height+'" />';
				imghtml += '</div>';

				overlay.find(options.flashContent).html('').html(imghtml);

			}
		}
		
	};

	$.fn.modalVideo.defaults = {
	container: $('<div class="modal_overlay video_player"><div class="flash_content"></div><div class="modal_overlay_content"><h4 class="caption"></h4><p class="call_to_action"><a href="' + CulturePrefix + 'company-info/press/public-archive.html" class="utility" onclick="$(\'div.flash_content\').html(\'\');" target="_self">' + CORPORATE.SEE_MORE_VIDEOS + '</a></p></div><p class="dismiss"><a href="#">' + CORPORATE.CLOSE + '</a></p></div>'),
		uiBlock: $('<div class="UIBlock"></div>'),
		caption: '.caption',
		utility: '.utility',
		dismissButton: '.dismiss a',
		flashContent: 'div.flash_content',
		scope: 'body',
		width: 'auto',
		height: 'auto',
		controlHeight: 0,
		type: 'progressive'
	};

})(jQuery);

$(document).ready(function () {

  $('div.slideshow').podSlideshow();

  $('#featured_news_slideshow').newsSlideshow();

  $('#did_you_know').newsSlideshow({ timer: 7000 });

  $('p.video_thumbnail a').append('<span class="overlay">Play</span>');
  $('p.video_thumbnail a.embed').modalVideo();

  $('#stock_ticker select, .Press .tabbed .pod_content form select, #state_field select, #franchising_intro select, #birthday_field select, #visits_field select').selectReplace();
  $('#stock_ticker input[type=submit], #press_releases input[type=submit], .tabbed .pod_tools input[type=submit], .Promotions input[type=submit], .Franchise input[type=submit], .SiteFeedback input[type=submit]').submitReplace();
  $('#stock_ticker input[type=radio], .Promotions input[type=radio]').radioReplace();
  $('.tabbed .pod_header ul li').addHoverClass();

  $('.Franchise #login p a.login').click(function () {
    $(this).parent().parent().find('form').show();
    $(this).parent().remove();
    return false;
  });

  $('#sort, #narrow').change(function () {
    $('.Media .pod_content form').submit();
  });

  $('#print_article').click(function () {
    window.print();

    return false;
  });

  $('#franchise_disclosure').click(function (e) {
    var $this = $(this);
    e.preventDefault();

    $('body').append('<div class="UIBlock"></div>');

    $('body').append('<div class="modal_overlay overlay_prompt"><p>' + CORPORATE.FDD + '</p><ul><li class="cancel"><a href="#">' + CORPORATE.CANCEL + '</a></li><li class="download"><a href="#">' + CORPORATE.DOWNLOAD + '</a></li></ul></div>');
    //$('body').append('<div class="modal_overlay overlay_prompt"><p id="fd_logo"><img src="/images/corporate/franchise-bk.jpg" alt="Burger King" title="Burger King" /></p><p id="fd_update">Burger King Corporation\'s Franchise Disclosure Document ("FDD") is being updated and is temporarily unavailable. If you need to receive a paper copy, please contact us at (305) 378-3588.</p><ul><li class="close"><a href="#">close</a></li></ul></div>');
    $('.UIBlock').css({
      display: 'block',
      opacity: 0
    }).animate({
      opacity: 0.8
    }, 'fast');

    if ($.browser.msie && $.browser.version < 7) {
      var intContentHeight = parseInt(($('#Content').height() + 35), 10);
      $('.UIBlock').css({ 'height': intContentHeight });
    }

    $('div.overlay_prompt ul li.cancel a, div.overlay_prompt ul li.close a').click(function () {
      $('.UIBlock').remove();
      $('.modal_overlay').remove();
    });

    $('div.overlay_prompt ul li.download a').click(function () {
      $('.UIBlock').remove();
      $('.modal_overlay').remove();

      window.open($this.attr('href'));
    });
  });

  $('#real_estate').click(function (e) {
    var $this = $(this);
    e.preventDefault();
    $('body').append('<div class="UIBlock"></div>');
    $('body').append('<div class="modal_overlay overlay_prompt extra_large"><p>' + CORPORATE.REAL_ESTATE + '</p><ul><li class="close"><a href="#">' + CORPORATE.CLOSE + '</a></li></ul></div>');
    getTerritoryDropdown();

    $('.UIBlock').css({
      display: 'block',
      opacity: 0
    }).animate({
      opacity: 0.8
    }, 'fast');
    if ($.browser.msie && $.browser.version < 7) {
      var intContentHeight = parseInt(($('#Content').height() + 35), 10);
      $('.UIBlock').css({ 'height': intContentHeight });
    }
    $('div.overlay_prompt ul li.close a, div.overlay_prompt ul li.close a').click(function () {
      $('.UIBlock').remove();
      $('.modal_overlay').remove();
    });
  });

}); //end document.ready


function TimelineLoaded() {
    try {
        pageTracker._trackEvent(CulturePrefix + CORPORATE.TRACK_LOAD_COMPLETE[0], CORPORATE.TRACK_LOAD_COMPLETE[1], CORPORATE.TRACK_LOAD_COMPLETE[2]);
    }
    catch (e) { }
}

function TimelineLeftArrow() {
    try {
        pageTracker._trackEvent(CulturePrefix + CORPORATE.TRACK_LEFT_ARROW[0], CORPORATE.TRACK_LEFT_ARROW[1], CORPORATE.TRACK_LEFT_ARROW[2]);
    }
    catch (e) { }
}

function TimelineRightArrow() {
    try {
        pageTracker._trackEvent(CulturePrefix + CORPORATE.TRACK_RIGHT_ARROW[0], CORPORATE.TRACK_RIGHT_ARROW[1], CORPORATE.TRACK_RIGHT_ARROW[2]);
    }
    catch (e) { }
}

function TimelineDragToYear(strYear) {
    try {
        pageTracker._trackEvent(CulturePrefix + CORPORATE.TRACK_DRAG_TO[0], CORPORATE.TRACK_DRAG_TO[1], CORPORATE.TRACK_DRAG_TO[2] + strYear);
    }
    catch (e) { }
}

function TimelineYearViewed(strYear) {
    try{
        pageTracker._trackPageview(CulturePrefix + 'company-info/index.html/timeline-' + strYear);
    }
    catch (e) { }
}
