var hash =  window.location.hash+'';

var IS_BONUS = false;

$(document).ready(function () {
	
	initIE6();
	initH3Accordeon(0);
	initMarginalForms();
	initH2Accordion();
	initGallery();
	initShareLinks();
	initSocialLinks();
	initMultimedia();
	initForms();
	initQuiz();
	initTooltip();
	openAutoOverlay();
	initRelpaceVideo();
	scrollToHash();
	lteForm();
	
	$("#fancybox-close",window.parent.document).fadeIn('slow');
	
	$('.vf_shop_options_close').click(function() {
		parent.$.fancybox.close();
		return false;
	});
	
	$('#vf_print').click(function(){
		window.print();
		return false;
	});
	
	var h = window.location.host.toLowerCase();
	
	$('body:not(#vf_overlay_page)')
		.find("#stores,a[href$='.13.0.html'],"+
			  "[href$='.14.0.html'],"+
			  "a[href^='http']:not(a[href^='http://"+h+"']):not(a[href^='http://www."+h+"']),"+
			  "a[href$='.pdf']").attr("target", "_blank");

	$('body#vf_overlay_page a').attr("target", "_top");

	$('body:not(#vf_layout_22) #vf_order_button a.button[href*="'+h+'"], #vf_main_297 a')
		.click(function(){
			$.fancybox({    	
	    		'href'				: $(this).attr('href'),
				'width'				: 677,
				'height'			: 528,
				'padding'			: 0,
		        'autoScale'     	: false,
				'titlePosition'		: 'over',
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe', 
				onComplete		    : function() { $('#fancybox-close').addClass('custom'); },
				onClosed			: function() { $('#fancybox-close').removeAttr('class'); }
			});
			return false;
	});
	
	$(window).unload(function() {
	    $('#vf_content .cjo_video_iframe').each(function(){
        	var iframe = $(this);
	        var video = iframe.contents().find('.video-js')[0];
	        if (typeof video != 'undefined') {
	        	video.player.pause();
	        }
	        iframe.remove();
	    });
	});
	
	setTimeout(function(){$('#vf_marginal').addClass('init');},1000);

	/* VF-DSL-SHOP */
	if (typeof s != 'undefined') {
		if (s.getQueryParam('b_id') && s.getQueryParam('shopid')) {
			$('body').append('<ifr' + 'ame src="//shop.vodafone.de/micropages/cookie-setting-page.htm?B_ID='
									+ s.getQueryParam('b_id')
									+ '&S_ID='
									+ s.getQueryParam('shopid')
									+ '&override=1" width="1" height="1" style="display:none"></ifr'
									+ 'ame>');
		}
		if (s.getQueryParam('vo')) {
			$('body').append( '<ifr'+ 'ame src="http://dslshop.vodafone.de/eshop/consumer/'
									+ s.getQueryParam('vo')
									+ '/0/1/asb.html" width="1" height="1" style="display:none"></ifr'
									+ 'ame>');
		}
	}
	/* VF-DSL-SHOP */	
});

function initTooltip() {
	
	var elm;
	var title = '';
	
	var moveTooltip = function($this, e) {

		var tip = createTooltip($this);

		if (!tip) {
			return false;
		}
		elm = $this;
		var offset = elm.offset();
		var height = elm.height()*1;
		var left   = e.pageX-30;
		var top    = e.pageY*1+25;
		elm.css({'cursor': 'pointer'});
		tip.css({'display': 'block', 'margin-left': left, 'margin-top': top, 'z-index': '999', 'top': '0', 'left':'0'});
		if(tip.is(':hidden')) tip.show();		
	}

	var createTooltip = function($this) {

		var cont = $('body > #vf_tooltip');
		if (cont.length > 0 && $this.is('.vf_tooltip_active')) return cont;		
		
		var new_title = $this.attr('title');
		
		if ($this.is('.vf_tooltip')) {
			if (new_title == undefined || new_title.length < 2) {
				removeTooltip();
				return false;
			}
			var temp = new_title.split(':::');
			var html = '<h4>'+temp[0]+'</h4><div class="textblock">'+temp[1]+'</div>';
		} else {
			var html = $this.next().html();
			if ($this.next().text().replace(/\s/g,'') == ':') {
				removeTooltip();
				return false;
			}
		}

		$this.removeAttr('title');
		removeTooltip();
		
		elm = $this;
		title = new_title;
		
		var css = '';
		var hits = 0;
		var i = 0;
		var parent = elm.parent();
		while (hits<=3 && i<=50){
			i++;
			var temp = parent.attr('class');	
			
			if (temp != undefined && temp.length > 0) {
				css += ' '+temp;
				hits++;
			}

			var temp = parent.attr('id');	
			if (temp != undefined && temp.length > 0) {
				css += ' '+temp;
				hits++;
			}

			parent = parent.parent();	
		}
		elm.addClass('vf_tooltip_active');
		return $('<div id="vf_tooltip" class="'+css+'">'+			 
				 '	<div class="vf_tooltip_outer">'+
				 '		<div class="vf_tooltip_inner">'+html+'</div>'+
				 '		<div class="vf_tooltip_shadow_middle" />'+
				 '  </div>'+			 
				 '	<div class="vf_tooltip_shadow_top" />'+
				 '	<div class="vf_tooltip_shadow_bottom" />'+
				 '</div>').appendTo($('body'));
	}	

	var removeTooltip = function () {
		if (elm != undefined) {
			elm.removeClass('vf_tooltip_active');
			if (title != undefined) elm.attr('title',title);
		}
		$('body > #vf_tooltip').remove();
	}
	
	$("div.vf_tooltip").prev().mousemove(function(e){
		moveTooltip($(this), e);
	}).mouseleave(function(){
		removeTooltip();
	});
	
	$(".vf_tooltip:not(div)").mousemove(function(e){
		moveTooltip($(this), e);
	}).mouseleave(function(){
		removeTooltip();
	});
}




function lteForm() {
	var form = $('#vf_layout_34 div[id^="form_"]');	
	if (form.length < 1) return false;
	var items = form.find('[name*="sup_"]').parent().parent();
	var check = form.find('input[name*="supplyadress"]');
	
	if (!check.is(':checked')) { items.hide(); }
	
	check.mousedown(function(){
		var $this = $(this);
		items.toggle();
	});
}

function initIE6() {
	
	if (!$.browser.msie || $.browser.version.substr(0,1)>6 || $('#vf_layout_20').length || $('#vf_layout_22').length ) return false;
	
	var container = $('#vf_main .container:first');
	var border 	  = container.find('.vf_border_right:first');
	var h = container.height()*1;

	border.css({'height': (h+2)+'px','padding-bottom':'0','margin-bottom':'0'});
	
	container = $('#vf_teaser_inner');
	var border 	  = container.find('.vf_border_right');
	var h = container.height()*1;

	border.css({'height': (h+2)+'px','padding-bottom':'0','margin-bottom':'0'});

	pngfix.fix('#vf_multimedia .vf_mm_ext_links a,'+
			   '#vf_multimedia .pagination .page_link,'+
			   '#vf_multimedia .vf_nav_after,'+
			   '#vf_main #vf_main_footer a#vf_print span,'+
			   '.vf_package_stoerer img');   
}

function scrollToHash() {
	if (hash.length <= 1) return false;
	var anchor = $('a[name="'+hash.replace(/#/,'')+'"]');
	if (typeof anchor == 'undefined' || !anchor) return false;
	$.scrollTo(anchor, 1200);
}

function initMarginalForms() {
	
	var vf_marginal = $('#vf_marginal');

	vf_marginal.find('#availability_el_5').attr('maxlength', '5');
	vf_marginal.find('#stores_el_1').attr('maxlength', '3');
	
	vf_marginal
		.find('form:not(#stores)')
		.submit(function(){
			var $this = $(this);

			var type   = $this.attr('id');
			var url    = $this.find('input[name*="url"]').val();
			var width  = $this.find('input[name*="width"]').val()*1;			
			var height = $this.find('input[name*="height"]').val()*1;

			if (!width)  width = 806;
			if (!height) height = 440;
			if (!url) {			
				url = $this.attr('action');
				if (!url.match(/http:\/\//i)) url = '.'+url;
			}

			$this.find('input').each(function(){
				var $this = $(this);
				
				var title = $this.attr('title');
				var value = $this.val();

				if (typeof title != 'undefined' && value.toLowerCase() == title.toLowerCase()) {
					value = $this.val('');
				}
			});
			
			url = (url.match(/\?/)) ? url+'&'+$this.serialize() : url+'?'+$this.serialize()

			$.fancybox({    	
	    		'href'				: url,
				'width'				: width,
				'height'			: height,
				'padding'			: 0,
		        'autoScale'     	: false,
				'titlePosition'		: 'over',
				'transitionIn'		: 'none',
				'transitionOut'		: 'none',
				'type'				: 'iframe', 
				onComplete		    : function() { $('#fancybox-close').addClass('custom').addClass(type); },
				onClosed			: function() { $('#fancybox-close').removeAttr('class'); }
			});
			return false;
		});	

		$('a[href$=".27.0.html"]')
			.mousedown(function(){
				$.fancybox({    	
		    		'href'				: $(this).attr('href'),
					'width'				: 606,
					'height'			: 310,
					'padding'			: 0,
			        'autoScale'     	: false,
					'titlePosition'		: 'over',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'type'				: 'iframe', 
					onComplete		    : function() { $('#fancybox-close').addClass('custom').addClass('newsletter'); },
					onClosed			: function() { $('#fancybox-close').removeAttr('class'); }
				});
				return false;
			});
}

function openAutoOverlay() {

	if (hash.replace(/#/,'') != 'overlay' || $('#fancy_content:empty').length > 0) return false;
	hash = '';
	var params = parseUri(window.location.href);
	var url = unescape(params.queryKey.url);

	var query = url.match(/\?/) ? '&' : '?';
	$.each(params.queryKey, function(key, value) { 
		if (key == 'url' || key == 'width' || key == 'height') return true;
		query += key+'='+value+'&';
	});
	query += 'overlay=1';

	$.fancybox({    	
		'href'				: url+query,
		'width'				: params.queryKey.width*1,
		'height'			: params.queryKey.height*1,
		'padding'			: 0,
        'autoScale'     	: false,
		'titlePosition'		: 'over',
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'type'				: 'iframe', 
		onComplete		    : function() { $('#fancybox-close').addClass('custom').addClass('newsletter'); },
		onClosed			: function() { $('#fancybox-close').removeAttr('class'); }
	});
}

function initH3Accordeon(default_open) {
	
	if ($('#vf_layout_22').length == 1) return true;
	
    var vf_h3 = $('#vf_content h3');
    var duration = (jQuery.browser.msie) ? 0 : 'fast';

    vf_h3.each(function(i){
        var $this = $(this);
        $this.css('cursor','pointer');
        if (default_open != i) {
        	$this.nextUntil('h3, h2, h1, .vf_border_right')
        		 .not('.textblock.open, .form.open')
        		 .hide();
        } else {
        	$this.addClass('open');
        }
    });

    vf_h3.click(function(){
        var $this = $(this);
        var open = $this.parent().parent().find('div.textblock:not(:hidden), div.form:not(:hidden)');
        var next = $this.nextUntil('h3, h2, h1, .vf_border_right');
        
        $('h3.open')
        	.removeClass('open');
        	
        if ($this.next('div').is(':hidden')) {
            next.slideDown(duration);
            $this.addClass('open');
        }
        open.slideUp(duration);
        return false;
    });  
}

function appendHtml5Iframe(box, url, width, height) {
	
	var overlay = box;	
	var inner 	= overlay.find('.vf_overlay_inner');
	var bg 	  	= overlay.find('.vf_overlay_bg');	
	var bonus   = box.parent().find('.vf_mm_bonus');		
	var nav     = box.parent().find('.nav');

	var left = width/2;
	var top  = height/2;

	if (nav.length) left -= (nav.width()*1)/2+1;

	if (!bonus.is(':hidden')) bonus.hide();

	inner
	.empty()
    .css({'margin-left': '-'+left+'px',
    	  'margin-top': '-'+top+'px',
    	  'width' : width+'px',
    	  'height' : height+'px'});
	
	$(inner).append('<iframe class="cjo_video_iframe" '+
				   'src="'+url+'" width="'+width+'" '+
				   'height="'+height+'" frameborder="0" '+
				   'scrolling="no" allowtransparency="true"></iframe>');
	
	overlay
	.show()
	.find('.vf_overlay_close')
	.click(function(){
		closeVideo();
		return false;
	});	
}

function showVideoIframe() {
	
	$('.cjo_video_iframe')
		.css({'position':'relative',
			'top':'0',
			'left': '0',
		    'z-index':'0'});
	$('#vf_multimedia .vf_overlay .vf_overlay_bg').fadeTo(200,1);
}

function initMultimedia(){
	
	var conf = {};
	
	conf.mm	  	 = $('#vf_multimedia');
	conf.bonus   = conf.mm.find('.vf_mm_bonus');		
	conf.overlay = conf.mm.find('.vf_overlay_bg');
	var links  	 = conf.mm.find('a[rel^="mm_overlay"]').add('#vf_main a[rel^="mm_overlay"]');
	
	autoAppendHtml5Iframe(conf);
	
	links.each(function(){
		var $this = $(this);
		var url = parseUri($this.attr('href'));
		$this.attr('href','#');
		var box = $this.parent().siblings().filter('.vf_overlay');
		$this.click(function(){
			conf.overlay.fadeTo(1,0.8);				
			appendHtml5Iframe(box, url.source, url.queryKey.width, url.queryKey.height);
			return false;
		});
	});	

	initMultimediaBonus(conf);
	initMultimediaDemo();
	initMultimediaStartpage(conf);
}

function autoAppendHtml5Iframe(conf) {
	
	var selector = '#'+hash.replace(/#/,'');

	if (selector == '#') return false;
	
	var link = $(selector);

	if (link.length == 0 || 
		link.attr('href') == undefined ||
	    link.attr('href') == '') return false;

	var url = parseUri(link.attr('href'));	

	if (url.source == undefined) return false;
	
	conf.overlay.fadeTo(1,0.8);		

	var box = link.parent().siblings().filter('.vf_overlay');
	appendHtml5Iframe(box, url.source, url.queryKey.width, url.queryKey.height);
}

function initMultimediaStartpage(conf) {

	var items = conf.mm.find('.inner > .item');
	
	if ($('#vf_layout_2').length != 1 || items.length < 2) return;
	
	items.not(':first').addClass('inactive');
	var curr = 0;
	var total = items.length;
	var mouseover = false;
	
	conf.mm.hover(function(){
		mouseover = true;
	}, function(){
		mouseover = false;
	});
	
	
	setInterval(function() {

		items = conf.mm.find('.inner > .item');
		
		if (!mouseover && items.eq(curr).find('.vf_overlay').is(':hidden')) {
			
			items.eq(curr).css('z-index','1');
			curr++;
			if (curr >= total) curr = 0;
			items.eq(curr).css('z-index','2').fadeIn(1000,function() {
				$(this).siblings().addClass('inactive').hide();
				items.eq(curr).removeClass('inactive');
			});
		}
	}, 5000);
	
}

function initMultimediaBonus(conf){
	
	var links    = conf.mm.find('a[rel="mm_bonus"]');
	var steps    = 1;
	var per_view = 3;	

	if (!links.length) return false;	
	
	var showBonus = function () {
		conf.bonus.show();
		IS_BONUS = true;
	};
	
	var hideBonus = function () {
		conf.bonus.hide();
		IS_BONUS = false;
	};
	
	var updateBonus = function(step) {

		var total = items.length;
		items.filter(':not(:hidden)').hide();
		if (step > 0) {
			items.slice(0, step).clone().appendTo(inner);
			items.slice(0, step).remove();
			items = inner.find('a');
			items.slice(0, per_view).show();
			
		}
		else {
			items.slice(total+step, total).clone().prependTo(inner);
			items.slice(total+step, total).remove();
			items = inner.find('a');				
			items.slice(0, per_view).show();
		}
		
		items.each(function(){
			$(this)
				.unbind('click')
				.click(function(){
					var $this = $(this);
					var url = parseUri($this.attr('href'));
					conf.mm.find('.vf_overlay_bg').css('opacity','0.8');
					var box = conf.mm.find('.vf_overlay');
					appendHtml5Iframe(box, url.source, url.queryKey.width, url.queryKey.height);
					return false;
				});
		});	
	};	
	
	var inner 	= conf.bonus.find('.vf_overlay_inner');
	var items   = inner.find('a[rel="mm_bonus_overlay"]');
	
	conf.bonus.find('.vf_overlay_bg').fadeTo(1,0.8);	
	
	links.click(function(){
		if(items.length == 1) {
			var $this = items.eq(0);
			var url = parseUri($this.attr('href'));
			var box = conf.mm.find('.vf_overlay');
			appendHtml5Iframe(box, url.source, url.queryKey.width, url.queryKey.height);
		}
		else { showBonus(); }
		return false;
	});
	
	if (items.length > 1) {
		conf.bonus
			.find('.vf_overlay_close')
			.unbind('click')
			.bind('click', function(){
				hideBonus();
				return false;
		});	
	}
	
	updateBonus();
	
	if (items.length <= per_view) return;
	
	items.hide().slice(0, per_view).show();
	
	var bonus_left = $('<a href="#" class="vf_bonus_left">&lt;</a>').appendTo(conf.bonus);
	var bonus_right = $('<a href="#" class="vf_bonus_right">&gt;</a>').appendTo(conf.bonus);
	
	bonus_left.click(function() {
		updateBonus(steps*-1);
		return false;			
	});
	
	bonus_right.click(function() {
		updateBonus(steps);
		return false;
	});
}

function initRelpaceVideo(){
	
	var links = $('a[rel="replace_video"]');
	
	if (links.length == 0) return false;
	
	closeReplaceVideo();
	
	links.each(function(){
		
		var $this = $(this);
		var url = parseUri($this.attr('href'));
		var container = $this.parent().find('.cjo_iframe_container');
		
		var showIframe = function(url, width, height) {
			
			$this.hide();
			
			container
			.show()			
			.empty()
			.append('<iframe class="cjo_video_iframe" '+
				   'src="'+url+'" width="'+width+'" '+
				   'height="'+height+'" frameborder="0" '+
				   'scrolling="no" allowtransparency="true"></iframe>');
		};
		
		var autoShowIframe = function() {
			
			var selector = '#'+hash.replace(/#/,'');

			if (selector == '#' || !$this.is(selector) ) return false;
			showIframe(url.source, url.queryKey.width, url.queryKey.height);
		}
		
		container.hide()
			.css({'margin': 0,
			      'width': url.queryKey.width+'px',
			      'height': url.queryKey.height+'px',
			      'overflow' : 'hidden'});
		
		$this.attr('href','#');
		
		$this.click(function(){
			showIframe(url.source, url.queryKey.width, url.queryKey.height);
			return false;
		});
		
		autoShowIframe();
	});	
}
function closeReplaceVideo() {
	
	var links = $('a[rel="replace_video"]:hidden');

	if (links.length == 0) return false;

	links.each(function(){
		$(this).show()
		var iframe	= $(this).parent().find('.cjo_video_iframe')
		var video = iframe.contents().find('.video-js')[0];
        if (typeof video != 'undefined') {
        	video.player.pause();
        }
        iframe.removeAttr('src').parent().hide();	
	});
}

function buildTopicStartView (ID) {
	$('#vf_idemo').empty().hide();
}

function init3CoverGallery(data, id, title) {
	
	var items = $('#'+id+' .item');

	items.each(function(i) { 

		var value = data[i];
		if (value.length < 1) return true;
		var item = $(this);
		var imageblock = item.find('.imageblock');
		
		imageblock.find('img').wrap('<a href="#" class="image_link" title="'+title+'"></a>')
		imageblock.append('<a href="#" class="text_link" title="'+title+'">'+title+'</a>');
		
		imageblock
			.find('a')
			.click(function(){

				var $this = $(this);
				var headline = item.find('h1, h2, h3, h4, h5');
				$.fancybox(value.clone(), {
						   'orig'		   : $this,
						   'padding'       : 0,
            			   'transitionIn'  : 'elastic',
            			   'transitionOut' : 'elastic',
            			   'easingIn'      : 'easeOutBack',
            			   'easingOut'     : 'easeInBack',
            			   'titlePosition' : 'over',
           				   'type'		   : 'image',             			   
            			   'titleFormat'   : function(title, currentArray, currentIndex) {
								
   								if (title == '') {
   									title = headline.eq(0).text();
   								}
   								
                                return '<span id="fancybox-title-over" style="display:none"><b>'+ title +'</b>'+
                                         ' <span id="fancybox-title-number-of"> ' +
                                             (currentIndex + 1) + ' / ' + currentArray.length +
                                         '</span></span>'; 
                            },                 
				            'onComplete'   :  function() {
                            	 $('#fancybox-title-over').show();
								 var timeout;
				                 window.clearTimeout(timeout);
				                 timeout = window.setTimeout("$('#fancybox-title').slideUp('normal')", 1000);
				         		$("#fancybox-wrap").hover(function() {
				         			window.clearTimeout(timeout);
				                     $('#fancybox-title').slideDown('fast');
				         		}, function() {
				                     window.clearTimeout(timeout);
				                     timeout = window.setTimeout("$('#fancybox-title').slideUp('normal')", 1000);
				         		});
							}
				});
				return false;
		});
	});
}

function initMultimediaDemo(){
	
	var mm	  	= $('#vf_multimedia');
	var links   = mm.find('a[rel^="mm_idemo"]');

	if (!links.length) return false;
	if (isNoFlash()) links.remove();

	links.click(function(){
		
		$('#vf_idemo').empty().show();

		var videoFile, linearVideoFile, srcFile;
		var id 				= ARTICLE_ID*1;
		var videoPath   	= MEDIAFOLDER+'/';
		var resPath         = FRONTPAGE_PATH+'/swf/demo/';
		var linearVideoPath = resPath+'resources_website/linear_video/';	
		var appWidth    	= 494;

		switch (id) {
			case 8:  srcFile = "idemo_hd.swf";		break;
			case 12: srcFile = "idemo_hardware.swf";	break;
			default: srcFile = "idemo.swf";		
		}

		switch (id) {
			case 6:	 
				videoFile = 'iptv_tv_web_noicon.f4v'; 
				linearVideoFile = '';
				break;
			case 7:	 
				videoFile = 'iptv_vod_web_noicon.f4v'; 
				linearVideoFile = '';
				break;
			case 8:	 
				videoFile = 'idemo_hd.f4v'; 
				linearVideoFile = 'hd_sample.f4v';
				break;
			case 9:
				videoFile = 'iptv_timeflex_web.f4v'; 
				linearVideoFile = '';
				break;
			case 10: 
				videoFile = 'iptv_epg_web_noicon.f4v'; 
				linearVideoFile = '';
				break;
			case 11: 
				videoFile = 'iptv_rec_web_noicon.f4v'; 
				linearVideoFile = '';
				break;
			case 12: 
				videoFile = '';	 
				linearVideoFile = '';
				break;
		}

		$('#vf_idemo').flash({
			src: videoPath+srcFile,
			width: 876,
			height: 422,
			menu:false,
			allowScriptAccess:'always',
			windowMode:'opaque', 
			flashvars: { 'topicID':id, 'resPath':resPath, 'videoPath':'', 'videoFile':videoFile, 'linearVideoPath':linearVideoPath, 'linearVideoFile': linearVideoFile, 'appWidth':appWidth }
		}, { expressInstall: true, version: '9' });

		return false;
	});
}


function initGallery(){
	
	$('#vf_main .gallery').each(function(){
		var $this     = $(this);

		var col1	  = $this.parentsUntil('.col1').length ;
		var display	  = col1 > 0 ? 4 : 3;

		var visible   = $this.find('div:first > p');
		var hidden    = $this.find('div:gt(0) > p');
		var link_show = $this.next().find('.vf_show_all');
		var link_hide = $this.next().find('.vf_hide_all');
		
		visible.show();
		if (hidden.length < 1) return false;
		
		link_show
			.show()
			.click(function(){
				hidden.slideDown('slow');
				link_hide.show();
				link_show.hide();
				return false;
			});
		
		link_hide
		.click(function(){
			hidden.slideUp('slow');
			link_hide.hide();
			link_show.show();
			return false;
		});
	});
}

function initSocialLinks(){
	
	function open() {
	    var valueWidth = $(this).children().innerWidth();
	    $(this).animate({"width":valueWidth},75);
	}
	
	function close() {
	    $(this).animate({"width":20},75);
	}
	
    $("#vf_social li:not(.infoLink)").hover(open, close);
    $("#vf_social li b a").attr({title: ""});
}

function initShareLinks() {

    var action  = false;	
    var timeout  = null;
    var msie     = $.browser.msie
    var duration = (!msie) ? 'fast' : 1;
	var footer = $('#vf_main_footer');
	var link   = footer.find('#vf_share');
	var nav    = footer.find('.vf_social');
    var page   = $('#page_margin');

    var perform = function(open) {

       if (timeout) {
            clearTimeout(timeout);
            timeout = null;
       }
       if (open) {
           if (msie) {
        	   nav.show();
           } else {
        	   nav.slideDown(duration);
           }
           link.addClass('open');
       }
       else {
           timeout = setTimeout(function(){
               timeout = null;
               if (msie) {
            	   nav.hide();
               } else {
            	   nav.slideUp(duration);
               }
               link.removeClass('open');
           }, 800);
       }
       return false;
    }

    link.focusin(function() {
    	perform(true);
    });

    link.mouseenter(function() {
    	perform(true);
    });

    nav.mouseenter(function() {
    	perform(true);
    });

    link.mouseleave(function() {
    	perform(false);
    });
        
    nav.mouseleave(function() {
    	perform(false);
    });	
}


function initFormLabelToDefault() {
	
	var forms = $('form:not(.show_labels)');
	
	forms.find('label').hide();
	
	forms.submit(function(){
		$(this)
			.find('input[type="text"], textarea')
			.each(function(){
				toggleLabel($(this), 'remove')
			});
	})	
	.find('input, textarea')
	.each(function() {
		
		var $this = $(this);
		if ($this.is('input[type="hidden"]')) {
			return true;
		}
		if (!$this.is('input[type="text"]') && !$this.is('textarea')) {
			$this.parent().find('label').show();
			return true;
		}
		var title = clearLabelStr($this.attr('title'));
		var label = clearLabelStr($this.parent().parent().find('label').text());
		
		if (label != title) {
			title = label;
			$this.attr('title',title);
		}			

		toggleLabel($this, 'add');
		
		$this.blur(function() {
			toggleLabel($this, 'add');
		});
		
		$this.focus(function() {
			toggleLabel($this, 'remove');
		});			
	});
	
	forms
		.find('select')
		.each(function() {
			var $this = $(this);
			var first = $this.children().eq(0);
			var title = clearLabelStr($this.attr('title'));
			var label = clearLabelStr($this.parent().parent().find('label').text());
			
			if (label != title) {
				title = label;
				$this.attr('title',title);
			}
			
			if (first.text() == '') {
				first.html(title);
			}
			else if(first.val() != '') {
				$this.prepend('<option>'+$this.attr('title')+'</option>');
			}
			
			if ($this.children().eq(0).is(':selected')) {
				$this.addClass('default');
			}
			$this.change(function(){
				if ($this.children().eq(0).is(':selected')) {
					$this.addClass('default');
				}
			});
			
			$this.focus(function(){
				$this.removeClass('default');
			});	
		});
}

function clearLabelStr(str){
	str = jQuery.trim(str);
	return 	str.replace(/\n/g, ' ');
}

function toggleLabel(obj, type){
	var input = $(obj);
	var value = clearLabelStr(input.val());
	var label = clearLabelStr(input.attr('title'));

	if (type == 'remove' && value == label) {
		input.val('');
	}	
	if (type == 'add' && value == '') {
		input.val(label);
	}	
	
	if (input.val() == label) {
		input.addClass('default');
	}
	else {
		input.removeClass('default');
	}
}

function initForms() {
	
	initFormLabelToDefault();
	
    $('#error').each(function(){
    	
    	var $this = $(this);
    	var msg = '';

    	$('form span.form_error, .statusmessage p').each(function(){
    		var html = $(this).html();
    		if (html.replace(/&nbsp;| /g,'') == '') return true;
    		msg += '<p><b>!</b>'+html+'</p>';
    	});
    	$('.statusmessage').remove();
    	
    	if (msg != '') {
    		msg = msg.replace(/<br ?\/?>/gi, '</p><p>! ');
    		$this.append(msg);
    		$this.slideDown('slow');
    	}
    });
}

function initQuiz() {

	var vf_quiz = $('#vf_quiz');

	if (!vf_quiz.length) return false;
	
	window.setTimeout("$('#vf_content').scrollTop(0)",10);
	
	var form   = vf_quiz.find('.form');
	var head   = vf_quiz.find('#vf_quiz_head');
	var check  = head.find(':checkbox');
	var hidden = vf_quiz.find('.form input:first');	

	if (form.length > 0){
		check.mousedown(function(){
			var $this = $(this);
			hidden.val($this.val());
			head.find('input').removeAttr('checked');
			return true;
		});
	} else {
		check
			.attr('disabled','disabled')
			.filter(':not(:checked)')
			.parent()
			.addClass('disabled');
	}
}

function initH2Accordion (){

    var duration = (jQuery.browser.msie) ? 0 : 'fast';

    var tb = parseUri(window.location).queryKey.tb;
    
	$('.page_5 #'+tb).addClass('open').prev('h2').addClass('open');

    $('.page_5 #vf_main h2')
    	.each(function(){
	        var $this = $(this);
	        var next  = $this.nextUntil('h2, h1, div:not(.textblock)');
	        var close = next.not('.textblock.open');
	        var iframes = next.find('.cjo_video_iframe');
	        
	        next.css('padding-left','11px');
	        close.hide();
	        $this.css('cursor','pointer');
	        
	        iframes.each(function(){
	    		var $this = $(this);
	    		$this.parent().css({'width': $this.css('width'),
	    							'height': $this.css('height')});
	    		
	    		var textblock = $this.nextUntil('.textblock').parent();
	    		if (textblock.is(':not(:hidden)')) {
	    			$this
			        	.removeAttr('style')
			        	.attr('src', $this.attr('longdesc'));
	    		}
	        });
	        
	        next.find('.cjo_video_iframe').removeAttr('src');
	    })
	    .click(function(){
	        var $this = $(this);
	        var next = $this.nextUntil('h2, h1');
	        	
	        if (!$this.is('.open')) {
	        	
	        	closeH2Accordion();
	        	
	            next.slideDown(duration).addClass('open');
	            $this.addClass('open');
	            
	            next.find('.cjo_video_iframe').each(function(){
	            	var iframe = $(this);
			        iframe
			        	.removeAttr('style')
			        	.attr('src', iframe.attr('longdesc'));
	            });
	        }
	        return false;
	    });  
}

function closeH2Accordion(){

    var duration = (jQuery.browser.msie) ? 0 : 'fast';
	var main = $('.page_5 #vf_main');
	var open = main.find('.textblock.open');
	var h2 = main.find('h2.open');
	
	if (open.length == 0) return;
	
	h2.removeClass('open');
	
    open
    	.slideUp(duration)
    	.removeClass('open')
    	.find('.cjo_video_iframe')
    	.each(function(){
    		
	    	var iframe = $(this);
	        var video = iframe.contents().find('.video-js')[0];
	        if (typeof video != 'undefined') {
	        	video.player.pause();
	        }
	        iframe.removeAttr('src');
	    });
}

function closeVideo() {


	conf         = {}
	conf.mm	  	 = $('#vf_multimedia');
	conf.bonus   = conf.mm.find('.vf_mm_bonus');	
	conf.overlay = conf.mm.find('.vf_overlay');	
	conf.inner   = conf.overlay.find('.vf_overlay_inner');

	var iframe = conf.inner.find('iframe');
	var video = iframe.contents().find('.video-js')[0];
    if (typeof video != 'undefined' && video != null) {
    	video.player.pause();
    }
	iframe.removeAttr('src');
	
	if (IS_BONUS) {
		conf.bonus.show();
		conf.overlay.hide();
		IS_BONUS = true;
		return false;
	} else {
		conf.overlay.hide();
		if (IS_BONUS) conf.bonus.show();
	}
		
	closeH2Accordion();
	closeReplaceVideo();

	$('.vf_video_container').siblings(':hidden').show();
	$('.vf_video_container').remove();	
	
	return false;
}

function trackPiwikParams(url) {
	
	if (typeof(piwik_page_title) == 'undefined') return url;
	
	var now = new Date();
	
	$.get("http://vtv.prod.appseleration.net/tv/piwik/piwik.php", { 
		idsite: 1,
		url:  MEDIAFOLDER+'/'+url, 
		rec: "1",
		revenue: "1",
		rand: Math.random(),
		h: now.getHours(),
		m: now.getMinutes(),
		s: now.getSeconds()
	});
	
	return url;
}

function isNoFlash(){
	return navigator.userAgent.match(/(iphone|ipod|ipad)/i) != null;
}

//parseUri 1.2.2
//(c) Steven Levithan <stevenlevithan.com>
//MIT License

function parseUri (str) {
	var	o   = {
			strictMode: false,
			key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
			q:   {
				name:   "queryKey",
				parser: /(?:^|&)([^&=]*)=?([^&]*)/g
			},
			parser: {
				strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
				loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
			}};
	var	m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};


Array.prototype.clone = function () {var a = new Array(); for (var property in this) {a[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return a}

