/************************************************************************/// /* SORTING *//************************************************************************/

(function($) {
	$.fn.sorted = function(customOptions) {
		var options = {
			reversed: false,
			by: function(a) {
				return a.text();
			}
		};
		$.extend(options, customOptions);
	
		$data = $(this);
		arr = $data.get();
		arr.sort(function(a, b) {
			
		   	var valA = options.by($(a));
		   	var valB = options.by($(b));
			if (options.reversed) {
				return (valA < valB) ? 1 : (valA > valB) ? -1 : 0;				
			} else {		
				return (valA < valB) ? -1 : (valA > valB) ? 1 : 0;	
			}
		});
		return $(arr);
	};

})(jQuery);

$(function() {
  
  var read_button = function(class_names) {
    var r = {
      selected: false,
      type: 0
    };
    for (var i=0; i < class_names.length; i++) {
      if (class_names[i].indexOf('selected-') == 0) {
        r.selected = true;
      }
      if (class_names[i].indexOf('segment-') == 0) {
        r.segment = class_names[i].split('-')[1];
      }
    };
    return r;
  };
  
  var determine_sort = function($buttons) {
    var $selected = $buttons.parent().filter('[class*="selected-"]');
    return $selected.find('a').attr('data-value');
  };
  
  var determine_kind = function($buttons) {
    var $selected = $buttons.parent().filter('[class*="selected-"]');
    return $selected.find('a').attr('data-value');
  };
  
  var $preferences = {
    duration: 800,
    easing: 'easeInOutQuad',
    adjustHeight: false
  };
  
  var $list = $('#gallery');
  var $data = $list.clone();
  
  var $controls = $('ul.gallerynav');
  
  $controls.each(function(i) {
    
    var $control = $(this);
    var $buttons = $control.find('a');
    
    $buttons.bind('click', function(e) {
      
      var $button = $(this);
      var $button_container = $button.parent();
      var button_properties = read_button($button_container.attr('class').split(' '));      
      var selected = button_properties.selected;
      var button_segment = button_properties.segment;

      if (!selected) {

        $buttons.parent().removeClass('selected-0').removeClass('selected-1').removeClass('selected-2').removeClass('selected-3').removeClass('selected-4').removeClass('selected-5');
        $button_container.addClass('selected-' + button_segment);
        
        var sorting_type = determine_sort($controls.eq(1).find('a'));
        var sorting_kind = determine_kind($controls.eq(0).find('a'));
        
        if (sorting_kind == 'all') {
          var $filtered_data = $data.find('li');
        } else {
          var $filtered_data = $data.find('li.' + sorting_kind);
        }
        
        if (sorting_type == 'size') {
          var $sorted_data = $filtered_data.sorted({
            by: function(v) {
              return parseFloat($(v).find('span').text());
            }
          });
        } else {
          var $sorted_data = $filtered_data.sorted({
            by: function(v) {
              return $(v).find('strong').text().toLowerCase();
            }
          });
        }
        
        $list.quicksand($sorted_data, {
      duration: 800,
      easing: 'easeInOutQuad'
    }, function() {

                                $("a.colorbox").colorbox();
                                $(".videoframe").colorbox({iframe:true, innerWidth:500, innerHeight:290, title:false});
                                $('.boxgrid.caption').hover(function(){
					$(".cover", this).stop().animate({top:'110px'},{queue:false,duration:160});
				}, function() {
					$(".cover", this).stop().animate({top:'140px'},{queue:false,duration:160});
				});
                        });
        
      } 
      
      
           e.preventDefault();
      
      
    });
    
  }); 

  
});

			
/************************************************************************/// // NIVO SLIDER ///************************************************************************/
			



$(window).load(function() {
	$('#sliderholder').nivoSlider({
		effect:'random',
		slices:20,
		animSpeed:800,
		pauseTime:3000,
		startSlide:0, //Set starting Slide (0 index)
		directionNav:true, //Next & Prev
		directionNavHide:true, //Only show on hover
		controlNav:true, //1,2,3...
		keyboardNav:true, //Use left & right arrows
		pauseOnHover:true, //Stop animation while hovering
		manualAdvance:false, //Force manual transitions
		captionOpacity:0.8 //Universal caption opacity
	});
});

/************************************************************************/// // VALIDATION  ///************************************************************************/

$(document).ready(function() {
			// SUCCESS AJAX CALL, replace "success: false," by:     success : function() { callSuccessFunction() },
			$("#formID").validationEngine({scroll:false})
			//$.validationEngine.loadValidation("#date")
			//alert($("#formID").validationEngine({returnIsValid:true}))
			//$.validationEngine.buildPrompt("#date","This is an example","error")	 		 // Exterior prompt build example								 // input prompt close example
			//$.validationEngine.closePrompt(".formError",true) 							// CLOSE ALL OPEN PROMPTS
		});
		
/************************************************************************/// // FORM SUBMISSION/************************************************************************/

$(document).ready(function() {
			// SUCCESS AJAX CALL, replace "success: false," by:     success : function() { callSuccessFunction() }, 
			$("#formID").validationEngine({
				ajaxSubmit: true,
					ajaxSubmitFile: "contact.php",
					ajaxSubmitMessage: "Thank you for your message!",
				success :  false,
				failure : function() {}
			})	
		});

/************************************************************************/// // TWITTER ///************************************************************************/
	
getTwitters('twitter', {
        id: 'jacquelinecharl', 
        count: 1, 
        enableLinks: true, 
        ignoreReplies: false,
        template: '<span class="twitterPrefix"><span class="twitterStatus">%text%</span> <em class="twitterTime"><a href="http://twitter.com/%user_screen_name%/statuses/%id%">- %time%</a></em>',
        newwindow: true
    });

/************************************************************************/// // COLORBOX ///************************************************************************/

$(document).ready(function(){
				$(".colorbox").colorbox();
				$(".videoframe").colorbox({iframe:true, innerWidth:500, innerHeight:293, title:false});

			});
			
/************************************************************************/// // CAPTION ///************************************************************************/
			
$(document).ready(function(){
				//Caption Sliding (Partially Hidden to Visible)
				$('.boxgrid.caption').hover(function(){
					$(".cover", this).stop().animate({top:'110px'},{queue:false,duration:160});
				}, function() {
					$(".cover", this).stop().animate({top:'140px'},{queue:false,duration:160});
				});
			});
			

			
/************************************************************************/// // NEWS ///************************************************************************/

/**
 * We use the initCallback callback
 * to assign functionality to the controls
 */
function mycarousel_initCallback(carousel) {

    jQuery('#newslist-next').bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('#newslist-prev').bind('click', function() {
        carousel.prev();
        return false;
    });
};

// Ride the carousel...
jQuery(document).ready(function() {
    jQuery("#newslist").jcarousel({
        scroll: 1,
        initCallback: mycarousel_initCallback,
        // This tells jCarousel NOT to autobuild prev/next buttons
        buttonNextHTML: null,
        buttonPrevHTML: null,
        vertical: true
    });
});


      $(document).ready(function(){

        $('a.menuitem[href*=#]').click(function() {

          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')

          && location.hostname == this.hostname) {

            var $target = $(this.hash);

            $target = $target.length && $target

            || $('[name=' + this.hash.slice(1) +']');

            if ($target.length) {

              var targetOffset = $target.offset().top;

              $('html,body')

              .animate({scrollTop: targetOffset}, 1000);

             return false;

            }

          }

        });

      });

/************************************************************************/// HOVER EFFECT /************************************************************************/
			
// If the HTML document is ready to be manipulated
$(document).ready(function(){
	// Add the hover handler to the link
	$("ul.social li a").hover(
		function(){
			$(this).find("img").animate({top : '-4px'}, 200);
		},
		function(){ 
			$(this).find("img").animate({top : '0px'}, 200);
		}
	);
});

/************************************************************************/// SCROLL /************************************************************************/

$(function()
			{
				// this initialises the demo scollpanes and makes it reinitialise itself once it's images have loaded...
				var settings = {
					scrollbarWidth: 4,
					dragMaxHeight: 100
				};
				$('.scroll-pane')
					.jScrollPane(settings)
					$.featureList(
				$("#newslist ul li a"),
				$(".entry"), {
					start_item	:	0,
					transition_interval : 0
				}
			);
			});

/************************************************************************/// MENU /************************************************************************/

$(document).ready(function(){
            
            $("ul#menu li a").blend({speed:700});
            
        });
        
/************************************************************************/// /* NEWS LIST *//************************************************************************/

$(document).ready(function() {

			$.featureList(
				$(".altnews li a"),
				$(".entry"), {
					start_item	:	0,
					transition_interval : 0
				}
			);

		});


/************************************************************************/// SCROLLABLE /************************************************************************/


function makeScrollable(wrapper, scrollable){
	// Get jQuery elements
	var wrapper = $(wrapper), scrollable = $(scrollable);
	
	// Hide images until they are not loaded
	scrollable.hide();
	var loading = $('<div class="loading">Loading...</div>').appendTo(wrapper);
	
	// Set function that will check if all images are loaded
	var interval = setInterval(function(){
		var images = scrollable.find('img');
		var completed = 0;
		
		// Counts number of images that are succesfully loaded
		images.each(function(){
			if (this.complete) completed++;	
		});
		
		if (completed == images.length){
			clearInterval(interval);
			// Timeout added to fix problem with Chrome
			setTimeout(function(){
				
				loading.hide();
				// Remove scrollbars	
				wrapper.css({overflow: 'hidden'});						
				
				scrollable.slideDown('slow', function(){
					enable();	
				});					
			}, 100);	
		}
	}, 10);
	
	function enable(){
		// height of area at the top at bottom, that don't respond to mousemove
		var inactiveMargin = 99;					
		// Cache for performance
		var wrapperWidth = wrapper.width();
		var wrapperHeight = wrapper.height();
		// Using outer height to include padding too
		var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin;
		// Do not cache wrapperOffset, because it can change when user resizes window
		// We could use onresize event, but it's just not worth doing that 
		// var wrapperOffset = wrapper.offset();
		
		// Create a invisible tooltip
		var tooltip = $('<div class="altnews_tooltip"></div>')
			.css('opacity', 0)
			.appendTo(wrapper);
	
		// Save menu titles
		scrollable.find('li a').each(function(){				
			$(this).data('tooltipText', this.title);				
		});
		
		// Remove default tooltip
		scrollable.find('a').removeAttr('title');		
		// Remove default tooltip in IE
		scrollable.find('img').removeAttr('alt');	
		
		var lastTarget;
		//When user move mouse over menu			
		wrapper.mousemove(function(e){
			// Save target
			lastTarget = e.target;

			var wrapperOffset = wrapper.offset();
		
			var tooltipLeft = e.pageX - wrapperOffset.left;
			// Do not let tooltip to move out of menu.
			// Because overflow is set to hidden, we will not be able too see it 
			tooltipLeft = Math.min(tooltipLeft, wrapperWidth - 75); //tooltip.outerWidth());
			
			var tooltipTop = e.pageY - wrapperOffset.top + wrapper.scrollTop() - 40;
			// Move tooltip under the mouse when we are in the higher part of the menu
			if (e.pageY - wrapperOffset.top < wrapperHeight/2){
				tooltipTop += 80;
			}				
			tooltip.css({top: tooltipTop, left: tooltipLeft});				
			
			// Scroll menu
			var top = (e.pageY -  wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin;
			if (top < 0){
				top = 0;
			}			
			wrapper.scrollTop(top);
		});
		
		// Setting interval helps solving perfomance problems in IE
		var interval = setInterval(function(){
			if (!lastTarget) return;	
										
			var currentText = tooltip.text();
			
			if (lastTarget.nodeName == 'IMG'){					
				// We've attached data to a link, not image
				var newText = $(lastTarget).parent().data('tooltipText');

				// Show tooltip with the new text
				if (currentText != newText) {
					tooltip
						.stop(true)
						.css('opacity', 0)	
						.text(newText)
						.animate({opacity: 1}, 1000);
				}					
			}
		}, 200);
		
		// Hide tooltip when leaving menu
		wrapper.mouseleave(function(){
			lastTarget = false;
			tooltip.stop(true).css('opacity', 0).text('');
		});			
		
		/*
		//Usage of hover event resulted in performance problems
		scrollable.find('a').hover(function(){
			tooltip
				.stop()
				.css('opacity', 0)
				.text($(this).data('tooltipText'))
				.animate({opacity: 1}, 1000);
	
		}, function(){
			tooltip
				.stop()
				.animate({opacity: 0}, 300);
		});
		*/			
	}
}
	
$(function(){	
	makeScrollable("div.altnews_wrapper", "ul.altnews");
});

