/*
		IJSBOERKE IJssnoetactie 
		ijssnoetactie.js
*/


/* 
	font replacement 
*/
Cufon.replace('.menu a');


/* 
	Gallery thumbnail carousel - dynamic load
*/
function gallery_itemLoadCallback(carousel, state)
{
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }
	
	// Send the selected id only the first time
	var selected = $('#galery-preselect').attr('rel');
	var sort = $('#filter :selected').attr('id');

	$.ajax
		({
			type: "POST",
			url: "/gallery/thumbs",
			data: "{ 'first': '" + carousel.first + "', 'last': '" + carousel.last + "', 'selected': '" + selected + "', 'sort': '" + sort + "'}",      
			contentType: "application/json; charset=utf-8",
			dataType: "json",
			success: function(json) {
				gallery_itemAddCallback(carousel, carousel.first, carousel.last, json);
			}
		});
};

function gallery_itemAddCallback(carousel, first, last, json)
{
    // Set the size of the carousel
    carousel.size(json.d.Total);
	
	var i = 0;
	for (var key in json.d.Participants) {
		var p = json.d.Participants[key];
		carousel.add(first + i, gallery_getItemHTML( p.Id, p.ThumbSmall, p.Comments, p.ShareUrl, p.IsVertical ? 'v' : 'h' ));
		i++;
	}
	
	// Automatically scroll to the thumb of the selected item
	if (json.d.SelectedPos != 0) {
		carousel.scroll(json.d.SelectedPos, true);
	}	
	
	$.fn.InitThumbs();
};

function gallery_getItemHTML(id, url, alt, share, thumbPos)
{
	var html = '';
	//html += '<li class="' + thumbPos + '">';
	html += '<a href="#" rel="' + share + '" id="' + id +'">';
    html += '<img src="' + url + '" alt="' + alt + '" />';
	html += '<span class="like-icon"></span>';
	html += '</a>';
	//html += '</li>';
	
	return html;
};


$(document).ready(function(){

	$('.winners-galery a').attr('rel', 'winners').fancybox({
		'titleShow'	: false
	});

	$.fn.InitThumbs = function() {
		var $thumbs = $('#galery-scroll-thumbs ul li a');
		var selectedId = 'undefined';
		var preselect = $('#galery-preselect').attr('rel');		

		$thumbs.each( function(i) { 
			$(this).bind('click',$.fn.updatePhoto);
			if( $(this).hasClass('selected') ) selectedId = $(this).attr('id');
		});	
		if (selectedId == 'undefined') {
			if (preselect != '') {
				selectedId = preselect;
			} else {
				selectedId = $($thumbs[0]).attr('id');
			}
		}							
		$.fn.initPhoto(selectedId);
	}

	/*
	* Clear input text and textarea fields on focus
	*/
	$('input.txt, textarea.txa').clearFieldOnFocus();

  /*
	*	Photo galery page - jCarousel
	*/
	$('#galery-scroll-thumbs ul').jcarousel({	
		scroll: 5,
		buttonNextHTML: '<div id="galery-scroll-right"><a href="javascript:void(0);" title="Vorige" class="btn">&lt;</a></div>',
		buttonPrevHTML: '<div id="galery-scroll-left"><a href="javascript:void(0);" title="Volgende" class="btn">&gt;</a></div>',
		//itemVisibleOutCallback: {onAfterAnimation: function(carousel, item, i, state, evt) { carousel.remove(i); }},
		itemLoadCallback: gallery_itemLoadCallback
	});

	//$('#galery #galery-item').photoGallery();
	$('#galery-item').photoGallery();
	
  /*
	*	Contest rules page - Vertical jCarousel
	*/
	
	$('#rules-scroll ul').jcarousel({	
		vertical: 'true',															
		scroll: 1,
		buttonNextHTML: '<div id="rules-scroll-right"><a href="javascript:void(0);" title="Vorige pagina">&lt;</a></div>',
		buttonPrevHTML: '<div id="rules-scroll-left"><a href="javascript:void(0);" title="Volgende pagina">&gt;</a></div>'
	});	



  /*
	*	Galery page Filter dropdown
  * @source: http://www.jankoatwarpspeed.com/post/2009/07/28/reinventing-drop-down-with-css-jquery.aspx
	*/
	
	createDropDown();
            
  $(".dropdown dt a").click(function() {
  	$(".dropdown dd ul").toggle();
  });

  $(document).bind('click', function(e) {
  	var $clicked = $(e.target);
    if (! $clicked.parents().hasClass("dropdown"))
    	$(".dropdown dd ul").hide();
			
    });
                        
    $(".dropdown dd ul li a").click(function() {
    	var text = $(this).html();
      $(".dropdown dt a").html(text);
      $(".dropdown dd ul").hide();
      var source = $("#source");
			var selectedValue = $(this).find("span.value").html();
      
			// update hidden select
			source.val(selectedValue);
						
			location.href = selectedValue;			
						
			// filter galery
			// alert(selectedValue);
			//e.preventDefault();
			
  });

  function createDropDown(){
    var source = $(".galery-filter-select");
    var selected = source.find("option[selected]");
    var options = $("option", source);
            
    $("#galery-filter").append('<dl id="target" class="dropdown"></dl>')
    $("#target").append('<dt><a href="#">' + selected.text() + 
      '<span class="value">' + selected.val() + 
      '</span></a></dt>')
    $("#target").append('<dd><ul></ul></dd>')

    options.each(function(){
      $("#target dd ul").append('<li><a href="#">' + 
        $(this).text() + '<span class="value">' + 
        $(this).val() + '</span></a></li>');
      });
    }
});

/*
*/

(function($) {

	// vote
	$.fn.voteForPicture = function(id) {
		if (id != 'undefined' && id != '') {
			$.ajax
				({
					type: "POST",
					url: "/gallery/vote",
					data: "{ 'id': '" + id + "'}",               
					contentType: "application/json; charset=utf-8",
					dataType: "json"
				});			

		}
	}		
	
	$.fn.updateShareButton = function(shareLang, shareUrl, shareTitle, shareDesc) {
	
		var addthis_ui_config = {
			 ui_language: shareLang,
			 ui_cobrand: "IJsboerke",
			 services_compact: 'facebook, twitter, messenger, google, delicious, myspace, email, more',
			 services_exclude: 'print'
		}
		var addthis_share_config = {
			url: shareUrl,
			title: shareTitle,
			description: shareDesc								
		}
		addthis.button("#btnShare", addthis_ui_config, addthis_share_config);
	}	

	$.fn.photoGallery = function() {

	  return this.each(function() {
			
			// objects
				var $galery = $(this);
				var $likeButton = $('a.btn-like',$galery);
				var $contentToggler = $('.galery-photo-overlay-toggle',$galery);
				var $content = $('.galery-photo-overlay',$galery);
				
			  var $thumbs = $('#galery-scroll-thumbs ul li a');
				
				//alert($thumbs.size());
				
			// vars	
				var selectedId = 'undefined';
				var preselect = $('#galery-preselect').attr('rel');


			// thumbs juiste hoogte geven onload
				$thumbs.each( function() {
						var img = $('img',$(this));
						if (img.width()>76) { img.css({'width':'76px','height':'auto'})}
						if (img.height()>50) { img.css({'height':'50px','width':'auto'})}															 
				});



			// onclick like button photo detail
			$.fn.onClickLikeButton = function(e) {
				
				if ( !$(this).hasClass('btn-like-selected') ) {
						$.fn.voteForPicture($galery.attr('rel'));
						
						// select button
						$(this).addClass('btn-like-selected');
						if ($('#galery-scroll-thumbs ul li a').size()>0) {
								// select like icon in thumbnail
								$('.like-icon',$('#'+$galery.attr('rel'))).addClass('like-selected');
						}
				}
				e.preventDefault();
				
			};
			
			// toggle content
			$.fn.toggleContent = function(e) {
				var contentH =  $content.height();
				$(this);
				if ($content.hasClass('toggle-closed')) {
					  $content.animate({'bottom':'0'},300);	
						$content.removeClass('toggle-closed');			
				} else {
						$content.animate({'bottom':'-'+(contentH-10)+'px'},300);									
					  $content.addClass('toggle-closed');					
				}				
			};
 
			
			// update photo in galery
			$.fn.updatePhoto = function(e) {
				
				// vars
				var clickedEl, $thumb, $likeIcon;
					 
					clickedEl   = $(e.target);
					$thumb      = $(this);
					$likeIcon   = $('span.like-icon',$thumb);
					
					// if they clicked on the like-icon span, select like icon
						
					if (clickedEl.hasClass('like-icon')&&!clickedEl.hasClass('like-selected')) {
							$likeIcon.addClass('like-selected');	
							if ( $thumb.hasClass('selected')) $('a.btn-like',$galery).addClass('btn-like-selected');
							$.fn.voteForPicture($thumb.attr('id'));
					}						

				 
				// 
				if ( !$thumb.hasClass('selected') ) {
						
						// haal gegevens op
						var img      = $('img',$thumb);
						var imgW     = img.width();
						var imgH     = img.height();
						var descr    = img.attr('alt');
					
						var isHorizontal = ( imgW/imgH > 1 ) ? true : false;
						
					  var calcW = (38/26)*imgH;
						var calcH = (26/38)*imgW;
						//console.log('horizontaal ' + isHorizontal) 
					 
						
					  var largeImg = $('.galery-photo img',$galery);
						var shareUrl = $thumb.attr('rel');
						var thumbId  = $thumb.attr('id');
						var ie6 = ($.browser.msie && $.browser.version < 7 ) ? true : false;
						
						// verberg vorige
						$('#galery-scroll-thumbs ul li a').removeClass('selected');					 
						$thumb.addClass('selected');
						selectedId = thumbId;
						
						if (ie6) {
								$galery.css({'top':'1000px'});
						} else {
							  $galery.animate({'top':'1000px'},300);
						}
						
						// place photo id in rel attr
						$galery.attr('rel',thumbId);
						
						// voeg gegevens in
						if ( isHorizontal ) $galery.removeClass('galery-item-vertical').addClass('galery-item-horizontal');
						else $galery.removeClass('galery-item-horizontal').addClass('galery-item-vertical');
						$('.galery-photo-overlay-text',$galery).text(descr);
						
						
						//$('.galery-photo img',$galery).attr('src',img.attr('src').replace('small','big'));

						largeImg.attr('src',img.attr('src').replace('small','big'));
						
						//console.log( 'hor ? ' + isHorizontal + " " + largeImg.width() + " " + largeImg.height() );
						// zet afmetingen goed
						if ( isHorizontal ) { 
						    largeImg.width(358); 
								if(largeImg.height()>238) { largeImg.height(238); largeImg.width('auto'); };
						} else {
							  largeImg.height(358); 
								if (largeImg.width()>238) {
										largeImg.width(238); largeImg.height('auto'); 
								} 					
						}

						
						if ($likeIcon.hasClass('like-selected')) { 
							$('a.btn-like',$galery).addClass('btn-like-selected') 
						} else { 
							if( $('a.btn-like',$galery).hasClass('btn-like-selected') ) $('a.btn-like',$galery).removeClass('btn-like-selected') 
						}
						$content.removeClass('toggle-closed').css({'bottom':'0'});
						
						if (isHorizontal) {
								if (ie6) {
										$galery.css({'top':'57px','left':'58px'});
								} else {
										$galery.css('left','58px').animate({'top':'57px'},300);
								}	
						} else {
								if (ie6) {
										$galery.css({'top':'-7px','left':'120px'});
								} else {
								    $galery.css('left','120px').animate({'top':'-7px'},300);
								}	
						}
						
						$.fn.updateShareButton(shareLang, shareUrl, shareTitle, shareDesc);
						 
				};
				
				e.preventDefault();
				
			};		 

			// update photo in galery
			$.fn.initPhoto = function(id) {

        //  vars
					  var $thumb      = $('#'+id);
					  var $likeIcon   = $('span.like-icon',$thumb);

				// 
						// haal gegevens op
						var img      = $('img',$thumb);
						var imgW     = img.width();
						var imgH     = img.height();
						var descr    = img.attr('alt');
						var isHorizontal = ( imgW > imgH ) ? true : false;
						var shareUrl = $thumb.attr('rel');
						var thumbId  = $thumb.attr('id');
						var largeImg = $('.galery-photo img',$galery);
						
						// verberg vorige
						$thumbs.removeClass('selected');					 
						$thumb.addClass('selected');
						selectedId = thumbId;
						
						// place photo id in rel attr
						$galery.attr('rel',thumbId);
						
						// voeg gegevens in
						if ( isHorizontal ) $galery.removeClass('galery-item-vertical').addClass('galery-item-horizontal');
						else $galery.removeClass('galery-item-horizontal').addClass('galery-item-vertical');
						$('.galery-photo-overlay-text',$galery).text(descr);
						
						//$('.galery-photo img',$galery).attr('src',img.attr('src').replace('small','big'));
						
						largeImg.attr('src',img.attr('src').replace('small','big'));
						
						//console.log( 'hor ? ' + isHorizontal + " " + largeImg.width() + " " + largeImg.height() );
						// zet afmetingen goed
						if ( isHorizontal ) { 
						    largeImg.width(358); 
								if(largeImg.height()>238) { largeImg.height(238); largeImg.width('auto'); };
						} else {
							  largeImg.height(358); 
								if (largeImg.width()>238) {
										largeImg.width(238); largeImg.height('auto'); 
								} 					
						}	
						
						if ($likeIcon.hasClass('like-selected')) { 
							$('a.btn-like',$galery).addClass('btn-like-selected') 
						} else { 
							if( $('a.btn-like',$galery).hasClass('btn-like-selected') ) $('a.btn-like',$galery).removeClass('btn-like-selected') 
						}
						$content.removeClass('toggle-closed').css({'bottom':'0'});
						
						if (isHorizontal) {
								$galery.css({'left':'58px','top':'57px'});
						} else {
								$galery.css({'left':'120px','top':'-7px'});
						}

						$.fn.updateShareButton(shareLang, shareUrl, shareTitle, shareDesc);
			};
				
				
				
		  // 
			// events												
				$likeButton.bind('click',$.fn.onClickLikeButton);
				$contentToggler.bind('click',$.fn.toggleContent);				
				
				if ($thumbs.size()>0) {

						$thumbs.each( function(i) { 
							$(this).bind('click',$.fn.updatePhoto);
							if( $(this).hasClass('selected') ) selectedId = $(this).attr('id');
						});	
						if (selectedId == 'undefined') {
							if (preselect != '') {
								selectedId = preselect;
							} else {
								selectedId = $($thumbs[0]).attr('id');
							}
						}							
						$.fn.initPhoto(selectedId);
				} else {
				
					var largeImg = $('.galery-photo img',$galery);
					var isHorizontal = ( largeImg.width()>largeImg.height() ) ? true:false;
 					
					//console.log( 'hor ? ' + isHorizontal + " " + largeImg.width() + " " + largeImg.height() );
					// zet afmetingen goed
					if ( isHorizontal ) { 
						largeImg.width(358); 
							if(largeImg.height()>238) { largeImg.height(238); largeImg.width('auto'); };
					} else {
						  largeImg.height(358); 
							if (largeImg.width()>238) {
									largeImg.width(238); largeImg.height('auto'); 
							} 					
					}				
				
				}
	
				
		
	  });
		
	};		

})(jQuery);

/* 
    CLEAR FIELD ON FOCUS 
		For input text where the field label is displayed as initial value of the field 
		when the field is cleared, the initial value - stored in rel attribute - is displayed 
*/
 
(function($){
	jQuery.fn.clearFieldOnFocus = function() {
		return this.each(function() {
      var initVal = ''; if($(this).attr('value') != undefined) initVal = $(this).attr('value'); $(this).attr('rel',initVal); 
			$(this).focus(function() { if($(this).attr('value') == $(this).attr('rel')) $(this).attr('value', ''); });
			$(this).blur(function() { if($(this).attr('value') == '') $(this).attr('value', $(this).attr('rel')); });
		});
	};
})(jQuery);
