var channel_carousel = false;
var videoplayers = {};

var uploader = false;
var upload_status = false;

var uploader2 = false;
var upload2_status = false;

var show_h264_video = false;

var fancybox_options = {
	'type'				: 'html',
	'content'			: '',
	'autoDimensions'	: false,
	'width'         	: 334,
	'height'        	: 'auto',
	'overlayOpacity'	: 0.8
}

var agent = new String(navigator.userAgent);
if ((agent.indexOf('iPad') > 0) || (agent.indexOf('iPhone') > 0)) {
    show_h264_video = true;
}


function hide_other_videos(show_video)
{
    for(i=0; i < 3; i++) {
        var vvalue = (i == show_video) ? 'visible' : 'hidden';
        var dvalue = (i == show_video) ? 'block' : 'none';

        //$('#video'+i).css('visibility',vvalue);
        $('#video'+i+' object').css('display',dvalue);
        $('#video'+i+' embed').css('display',dvalue);
    }
}

jQuery(function($){
    $('#bigvideo_intros.hover li').click( function() {
		$('#bigvideo_intros li').removeClass('active');
		$(this).addClass('active');

		var video = $('#bigvideo_intros li').index(this) + 1;

		if (videoplayers.video1) {
			videoplayers.video1.sendEvent("STOP");
		}
		if (videoplayers.video2) {
			videoplayers.video2.sendEvent("STOP");
		}
		if (videoplayers.video3) {
			videoplayers.video3.sendEvent("STOP");
		}

        /*
        $('#video0').css('visibility','visible');
        $('#video1').css('visibility','visible');
        $('#video2').css('visibility','visible');
        //*/
        //*
        if (show_h264_video) {
            $('#video0 object, #video0 embed').css('display','block');
            $('#video1 object, #video1 embed').css('display','block');
            $('#video2 object, #video2 embed').css('display','block');
        }
        //*/

		var offset = "0px";
		switch (video) {
			case 1:
				offset = "0px";
				$('#bigvideo_intros').addClass('first').removeClass('second').removeClass('third');
				break;

			case 2:
				offset = "-277px";
				//$('#bigvideo_intros').addClass('second');
				$('#bigvideo_intros').removeClass('first').addClass('second').removeClass('third');
				break;

			case 3:
				offset = "-554px";
				//$('#bigvideo_intros').addClass('third');
				$('#bigvideo_intros').removeClass('first').removeClass('second').addClass('third');
				break;
		}

		$('div#videowrapper').animate(
			{ top: offset },
			{ duration: 300, queue: false }
		);

        if (show_h264_video) {
            setTimeout('hide_other_videos('+(video-1)+')',350);
        }
    });
    
	$('#subscribe_newsletter input').focus( function() {
	    if($(this).val()=="Naam" || $(this).val()=="E-Mail") {
		$(this).val('');
	    }
	});
	
	$('#subscribe_newsletter input').blur( function() {
	    if($(this).val() == "") {
		if($(this).attr('class') == "name") {
		    $(this).val("Naam") ;
		} else {
		    $(this).val("E-Mail") ;
		}
	    }
	});

	fancybox_options.content = $('#loginfancybox').html();

	$('a.openprofile').bind('click',function(e){
		if (!$(this).hasClass('loggedin')) {
			e.preventDefault();

			$.fancybox('Login',fancybox_options);

			$('.loginpanel p.message').hide();
		}
	});
	
	$('.uploadbutton').click( function(event){
		event.preventDefault();
		if ($(this).hasClass('notloggedin')) {
			$.fancybox('Login',fancybox_options);

			$('.loginpanel p.message').show();
			$('.loginpanel p.message span').hide();
			$('.loginpanel p.message span.for_upload').show();
		}
		else {
			if ($('#uploadpanel:visible').is('*')) {
				$('#uploadpanel').hide();
			} else {
				$('#loginpanel').hide();
				$('#uploadpanel').show();

				if (uploader != false) {
					uploader.refresh();
				}
				else {
					// error?
				}
			}
		}
	});

	$('a.numvotes').click(function(event){
		if ($('#profilecontrols a.openprofile').hasClass('loggedin')) {
		}
		else {
			$.fancybox('Login',fancybox_options);

			$('.loginpanel p.message').show();
			$('.loginpanel p.message span').hide();
			$('.loginpanel p.message span.for_vote').show();
		}
		return false;
	});
	
	$('#headerwrapper .closebutton').click( function() {
	    $(this).closest('.headerpanel').hide();
	});

    /*___________________________________________________
     *                  Channelswitcher
     *___________________________________________________
     */
    
    $('div#channelpicker').jcarousel({
		dispItems: 3,
		wrap: 'both',
		initCallback: function(carousel,state){
			channel_carousel = carousel;
			setTimeout('channel_carousel.options.animation = 3000; channel_carousel.next(); channel_carousel.options.animation = "normal"; ',1500);
		}
    });

    
    $('#switchchannels').click( function() {
		if ($('#channelpicker').hasClass('closed')) {
			$('#channelpicker').removeClass('closed');
			$('#channelmessage').css('display','none');
			$(this).removeClass('closed');
		}
		else {
			$('#channelpicker').addClass('closed');
			$('#channelmessage').css('display','block');
			$(this).addClass('closed');
		}
		return false;
    });

	$('#channelmessage').click(function(){
		$('#channelpicker').removeClass('closed');
		$('#channelmessage').css('display','none');
		$('#switchchannels').removeClass('closed');
	});
    
    /*___________________________________________________
     *                  Spotlight
     *___________________________________________________
     */
    
    $('#spotlight #spotlightswitcher a').click(function(){
		$('#recent, #mostviewed, #mostcomments').hide();
		$('#spotlight #spotlightswitcher a').removeClass('active')
		$('#spotlight #spotlightswitcher').removeClass('recent').removeClass('mostviewed').removeClass('mostcomments').addClass($(this).attr('rel'))
		$('#'+$(this).attr('rel')).show();
		return false;
    });
	
	$('#spotlight .datefilter a').click(function(e){
		var column_el = $(this).closest('.column');
		$('.subcolumn', column_el).hide();
		$('.datefilter a', column_el).removeClass('active');
		$(this).addClass('active');
		$('#'+$(this).attr('rel')).show();

		e.preventDefault();
		return false;
	});
    
    
    $('#sidebarspotlight #spotlightswitcher a').click( function() {
	$('#relatedweblogs, #relatedvideos').hide();
	$('#sidebarspotlight #spotlightswitcher a').removeClass('active')
	$('#sidebarspotlight #spotlightswitcher').removeClass('relatedweblogs').removeClass('relatedvideos').addClass($(this).attr('rel'))
	$('#'+$(this).attr('rel')).show();
	return false;
    });
    
    /*___________________________________________________
     *                  Embedcode
     *___________________________________________________
     */
    
    $('#embedcode').focus( function() {
		$(this).select();
    });

	/*
	$.clipboardReady(function(){
		$("#copyembed").click(function(){
			$.clipboard( "You clicked on a link and copied this text!" );
			return false;
		});
	},
	{
		swfpath: "/pivotx/templates/froeks/scripts/jquery.clipboard.swf", debug: false
	});
	*/
    
    
    /*___________________________________________________
     *                  Tip de redactie
     *___________________________________________________
     */
    
    $('#tipredactie img').click( function() {
		if($('#tipredactie').hasClass('closed')) {
			$('#tipredactie').removeClass('closed');
		}
		else {
			$('#tipredactie').addClass('closed');
		}
    });
    
    
    
    
    /*___________________________________________________
     *                  Newsletter subscribe
     *___________________________________________________
     */

		var c = new String(' ' + document.cookie);
		if (c.indexOf('newsletter=subscribed') > 0) {
			$('#subscribe_newsletter').hide();
		}

		$("#subForm input:submit").click(function() {	
			
			// First, disable the form from submitting
			$('form#subForm').submit(function() { return false; });
			
			// Grab form action
			formAction = $("form#subForm").attr("action");
			
			// Hacking together id for email field
			// Replace the xxxxx below:
			// If your form action were http://mysiteaddress.createsend.com/t/r/s/abcde/, then you'd enter "abcde" below
			emailId = "hltytk";
			emailId = emailId.replace("/", "");
			emailId = emailId + "-" + emailId;
			
			// Validate email address with regex
			if (!checkEmail(emailId)) 
			{
				alert("Dit is geen geldig e-mailadres");
				return;
			}
			
			// Serialize form values to be submitted with POST
			var str = $("form#subForm").serialize();
			
			// Add form action to end of serialized data
			var post = str + "&action=" + formAction;

			// Submit the form via ajax
			$.ajax({
				url: "proxy.php",
				type: "POST",
				data: post,
				success: function(html){
					var date = new Date();
					date.setTime(date.getTime()+(365*24*60*60*1000));
					var expires = "; expires="+date.toGMTString();
					document.cookie = "newsletter=subscribed"+expires+"; path=/";

					document.location.href = '/nieuwsbrief-aangemeld';
				}
			});
		});

    /*___________________________________________________
     *                  Filter weblog
     *___________________________________________________
     */
    
    $('a#filterweblog').click(function(){
		order = $('#weblogcontrols input[name="order"]').val();
		vm = $('#weblogfromdatefilter select[name="vm"] option:selected').attr('value');
		vy = $('#weblogfromdatefilter select[name="vy"] option:selected').attr('value');
		tm = $('#weblogtodatefilter select[name="tm"] option:selected').attr('value');
		ty = $('#weblogtodatefilter select[name="ty"] option:selected').attr('value');
		if (vy != "") {
			if (vm!="" && vm < 10) {
				fromdate = vy+"-0"+vm+"-00";
			}
			else if (vm!="" && vm < 13) {
				fromdate = vy+"-"+vm+"-00";
			}
			else {
				fromdate = vy+"-00-00";
			}
		}
		if (ty != "") {
			if (tm!="" && tm < 10) {
				todate = ty+"-0"+tm+"-00";
			}
			else if (tm!="" && tm < 13) {
				todate = ty+"-"+tm+"-00";
			}
			else {
				todate = ty+"-00-00";
			}
		}
		window.location = $(this).attr('rel')+"?order="+order+"&from="+fromdate+"&to="+todate;
    });


	// upload panel for the pop-up

	uploader = new plupload.Uploader({
		//runtimes : 'gears,html5,flash,silverlight,browserplus',
		runtimes : 'silverlight,flash',
		browse_button : 'pickfiles',
		container : 'filecontainer',
		max_file_size : '960mb',
		chunk_size: '10mb',
		url : '/upload-progress.php',
		flash_swf_url : '/pivotx/templates/froeks/scripts/plupload/plupload.flash.swf',
		silverlight_xap_url : '/pivotx/templates/froeks/scripts/plupload/plupload.silverlight.xap',
		filters : [
			{title : "Movie files", extensions : "mov,mp4,wmv,flv,avi,m4v" }
		],
		multi_selection: false,
		unique_names: true
	});

	uploader.bind('UploadFile', function(up, file) {
		if (file.percent < 1) {
			$('#upload-status')
				.html(file.name + ' - starting..')
				;
		}
	});

	uploader.bind('FileUploaded', function(up, file){
		$('#upload-status')
			.html(file.name + ' - done')
			;

		upload_status = true;
	});

	uploader.bind('QueueChanged', function(up){
		while (uploader.files.length > 1) {
			ret = uploader.removeFile(uploader.files[0]);
		}

		if (uploader.files.length > 0) {
			$("#filelist").val(uploader.files[0].name + ' (' + plupload.formatSize(uploader.files[0].size) + ')');

			$('#upload_id').val(uploader.files[0].id);
			$('#upload_filename').val(uploader.files[0].name);

			if (uploader.files[0].status == plupload.DONE) {
				upload_status = true;
			}
			else {
				upload_status = false;
				uploader.start();
			}
		}
	});

	uploader.bind('UploadProgress', function(up, file) {
		//$('#filelist').html(file.percent + '%');

		var percent = file.percent;
		if (upload_status) {
			percent = 100;
		}

		var width = Math.ceil((percent * ($('.upload-progress').width()+6)) / 100);

		if (!upload_status) {
			$('#upload-status')
				.html(file.name + ' - ' + file.percent + '%')
				;
		}

		$('#upload-bar')
			.width(width)
			;

		if (uploader.files[0].status == plupload.DONE) {
			upload_status = true;
		}
	});

	$('#upload-form').bind('submit',function(e){
		if (!upload_status) {
			e.preventDefault();
		}
	});

	uploader.init();



	// upload panel for editting the video

	if ($('#pickfiles2').is('*')) {
		uploader2 = new plupload.Uploader({
			//runtimes : 'gears,html5,flash,silverlight,browserplus',
			runtimes : 'silverlight,flash',
			browse_button : 'pickfiles2',
			container : 'filecontainer2',
			max_file_size : '960mb',
			chunk_size: '10mb',
			url : '/upload-progress.php',
			flash_swf_url : '/pivotx/templates/froeks/scripts/plupload/plupload.flash.swf',
			silverlight_xap_url : '/pivotx/templates/froeks/scripts/plupload/plupload.silverlight.xap',
			filters : [
				{title : "Movie files", extensions : "mov,mp4,wmv,flv,avi,m4v" }
			],
			multi_selection: false,
			unique_names: true
		});

		uploader2.bind('UploadFile', function(up, file) {
			if (file.percent < 1) {
				$('#upload2-status')
					.html(file.name + ' - starting..')
					;
			}
		});

		uploader2.bind('FileUploaded', function(up, file){
			$('#upload2-status')
				.html(file.name + ' - done')
				;

			upload_status = true;
		});

		uploader2.bind('QueueChanged', function(up){
			while (uploader2.files.length > 1) {
				ret = uploader2.removeFile(uploader2.files[0]);
			}

			if (uploader2.files.length > 0) {
				$("#filelist").val(uploader2.files[0].name + ' (' + plupload.formatSize(uploader2.files[0].size) + ')');

				$('#upload2_id').val(uploader2.files[0].id);
				$('#upload2_filename').val(uploader2.files[0].name);

				if (uploader2.files[0].status == plupload.DONE) {
					upload2_status = true;
				}
				else {
					upload2_status = false;
					uploader2.start();
				}
			}
		});

		uploader2.bind('UploadProgress', function(up, file) {
			$('#filelist').html(file.percent + '%');

			var percent = file.percent;
			if (upload2_status) {
				percent = 100;
			}

			var width = Math.ceil((percent * ($('.upload2-progress').width()+6)) / 100);

			if (!upload2_status) {
				$('#upload2-bar')
					.html(file.name + ' - ' + file.percent + '%')
					;
			}

			$('#upload2-bar')
				.width(width)
				;

			if (uploader2.files[0].status == plupload.DONE) {
				upload2_status = true;
			}
		});

		uploader2.init();
	}

	$('.fancythumb').bind('click',function(e){
		var src = new String($(this).attr('src'));

		var pos = src.indexOf('src=',src);

		var href = src.substring(pos);

		$.fancybox(
			$(this).attr('alt'), {
				'type':		'image',
				'href':		href,
				'overlayOpacity': 0.8
			}
		);
	});
});

function update_vote(el)
{
	$.ajax({
		url: el.href,
		type: 'GET',
		dataType: 'json',
		success: function(result){
			div_vote = $(el).parent();
			var votes_up   = parseInt(result.votes_up);
			var votes_down = parseInt(result.votes_down);
			var votecount  = votes_up - votes_down;
			$('.votecount',div_vote).text(votecount);
			$('.voteupcount',div_vote).text(votes_up);
			$('.votedowncount',div_vote).text(votes_down);
		}
	});
	return false;
}

function checkEmail(email) {	
	var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	var emailVal = $("#" + email).val();
	return pattern.test(emailVal);
}

function playerReadyCallback(obj)
{
	if (obj['id']) {
		videoplayers[obj['id']] = document.getElementById(obj['id']);
	}
}

