





/*-------------------------------------------------------------------- 
 * jQuery plugin: customInput()
 * by Maggie Wachs and Scott Jehl, http://www.filamentgroup.com
 * Copyright (c) 2009 Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 * Article: http://www.filamentgroup.com/lab/accessible_custom_designed_checkbox_radio_button_inputs_styled_css_jquery/  
 * Usage example below (see comment "Run the script...").
--------------------------------------------------------------------*/


jQuery.fn.customInput = function(){
	$(this).each(function(i){	
		if($(this).is('[type=checkbox],[type=radio]')){
			var input = $(this);
			
			// get the associated label using the input's id
			var label = $('label[for='+input.attr('id')+']');
			
			//get type, for classname suffix 
			var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';
			
			// wrap the input + label in a div 
			$('<div class="custom-'+ inputType +'"></div>').insertBefore(input).append(input, label);
			
			// find all inputs in this set using the shared name attribute
			var allInputs = $('input[name='+input.attr('name')+']');
			
			// necessary for browsers that don't support the :hover pseudo class on labels
			label.hover(
				function(){ 
					$(this).addClass('hover'); 
					if(inputType == 'checkbox' && input.is(':checked')){ 
						$(this).addClass('checkedHover'); 
					} 
				},
				function(){ $(this).removeClass('hover checkedHover'); }
			);
			
			//bind custom event, trigger it, bind click,focus,blur events					
			input.bind('updateState', function(){	
				if (input.is(':checked')) {
					if (input.is(':radio')) {				
						allInputs.each(function(){
							$('label[for='+$(this).attr('id')+']').removeClass('checked');
						});		
					};
					label.addClass('checked');
				}
				else { label.removeClass('checked checkedHover checkedFocus'); }
										
			})
			.trigger('updateState')
			.click(function(){ 
				$(this).trigger('updateState'); 
			})
			.focus(function(){ 
				label.addClass('focus'); 
				if(inputType == 'checkbox' && input.is(':checked')){ 
					$(this).addClass('checkedFocus'); 
				} 
			})
			.blur(function(){ label.removeClass('focus checkedFocus'); });
		}
	});
};













// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults


	var amountToLoad = 5;
	var listItems = [];
	var page = 1;
	
	var amountToLoad_text = 5;
	var page_text = 1;


	/*
		Renders the list of movie questions
		And shows the first one
		
		uses these elements as target for the data
		
			<ul id="movie_list"></ul>
			<div class="movie_target"></div>
			<div class="text_target"></div>
	*/
	
	
	
	function render_lists() {
		
		if(document.location.hash && document.location.hash != "") {
			$('[data-hide]').hide();
		}
		
		/*
			Render movie list
		*/
		{ 
      $("#movie_list").empty();
      
			var movie_list = [];

			$.each(listItems,function(index,value,bla) {
				if((value !== undefined && value.youtube_id !== undefined && value.youtube_id !== "") || (value !== undefined && value.image_url != "")) {
					//movie_list.push(value);
				}
			});
			
			var list_to_show = [];
			
			for(var i = (page-1)*amountToLoad; i < movie_list.length; i++) {
				list_to_show.push(movie_list[i]);
			}

      $.each(list_to_show,function(index,value,bla) {
        
        if(value == null) {
          return;
        }
        
        if(index < amountToLoad) {
          
					var youtube_id = value.youtube_id.replace('http://www.youtube.com/watch?v=','');

					var image_url = 'http://i3.ytimg.com/vi/'+youtube_id+'/default.jpg';
					
					if (value.youtube_id === undefined || value.youtube_id == "") {
						image_url = value.image_thumb_url;
					}
					

          var li = $("<li></li>")
            .append($('<div class="img_bg"><img alt="" src="'+image_url+'" alt="" /></div>'))
            .append($('<p>'+(value.text || "")+'</p>'))
            .append($('<div style="clear: both;"></div>'))
            .append($('<input type="hidden" name="id" value="'+value.id+'" />'));
          
          $("#movie_list").append(li);
            
            if(value.id == window.location.hash.substring(1)) {
              li.addClass('selected');
            }
          }
				});
				
				/*
					Fillout the list if we are on another page
				*/
				if(page != 1) {
					for(var i = $("#movie_list li").length; i < amountToLoad; i++) {
	          $("#movie_list").append('<li class="filler"></li>');
					}
				}
				
			if(movie_list.length == 0) {
				$('#movie_list_container').hide();
			} else {
				$('#movie_list_container').show();				
			}
      
      if(movie_list.length > amountToLoad) {
        
 
				var page_count = Math.floor(movie_list.length / amountToLoad);
				page_count += ((movie_list.length % amountToLoad) > 0) ? 1 : 0;

				var ul = $('<ul id="page_list"></ul>');
				
				for(var i = 0; i < page_count; i++) {
					var li = ul.append('<li class="'+((i+1) == page ? "selected" : "")+'">'+(i+1)+'</li>');
					li.click(function(e) {
						page = Math.floor($(e.target).html());
						render_lists();
					});
				}

				$("#movie_list")
          .append($('<li class="show_all"></li>')
						.append(ul));
        
        $("#movie_list li.show_all a").bind('click',function() {
          amountToLoad = 500;
          loadItems();
          return false;
        });
      }
      
      
      $("#movie_list li").bind('click',function(e) {
          var id = $(e.target).closest('li').find('input').val();
          $.each(listItems,function(index,value) {
              if(value !== undefined && value.id == id) {
								window.location.hash = value.id;
								$('[data-hide]').hide();
								$('html').scrollTo($(".movie_target"));
								render_lists();
                $('.movie_target,.text_target').show();
              }
            });
        });
    }








		/*
			Render text links
		*/
		{
      
      $("#text_questions").empty();

			var text_list = [];

			$.each(listItems,function(index,value,bla){
				//if((value !== undefined && value.youtube_id === undefined || ( value !== undefined && value.youtube_id === "")) && (value !== undefined && value.image_url == "")) {
					text_list.push(value);
				//}
			});
			
			if(text_list.length == 0) {
				$('#text_questions').hide();
			} else {
				$('#text_questions').show();				
			}
			
			var list_to_show = [];
			
			for(var i = (page_text-1)*amountToLoad_text; i < text_list.length; i++) {
				list_to_show.push(text_list[i]);
			}
      
      $.each(list_to_show,function(index,value,bla) {
        if(index < amountToLoad_text) {
          
          var li = $("<li></li>")
            .append($('<p>'+(value.text || "")+'</p>'))
            .append($('<p class="visningar"></p>'))
            .append($('<input type="hidden" name="id" value="'+value.id+'" />'));
          
          $("#text_questions").append(li);
            
            if(value.id == window.location.hash.substring(1)) {
              li.addClass('selected');
            }
          }});
      
        

					$("#text_questions li").click(function(e) {
	          var id = $(e.target).closest('li').find('input').val();
	          window.location.hash = id;
						
						$('html').scrollTo($(".text_target"));
						
						render_lists();
            $('.movie_target,.text_target').show();
	        });


					if(text_list.length > amountToLoad_text) {

						var page_count = Math.floor(text_list.length / amountToLoad_text);
						page_count += ((text_list.length % amountToLoad) > 0) ? 1 : 0;

						var ul = $('<ul id="page_list"></ul>');

						for(var i = 0; i < page_count; i++) {
							var li = ul.append('<li class="'+((i+1) == page_text ? "selected" : "")+'">'+(i+1)+'</li>');
							li.click(function(e) {
								page_text = Math.floor($(e.target).html());
								render_lists();
							});
						}

						$("#text_questions")
		          .append($('<li class="show_all"></li>')
								.append(ul));
		      }


        
	        
      
      
      	
    }



		
		/*
			Render movie and text
		*/
		if(listItems.length == 0) {
			$(".movie_target").empty();
			$('.text_target').empty();
		}
		
		/*
			Get selected item
		*/
		var selected;
		$.each(listItems,function(index,value,bla) {
			if(value !== undefined && value.id == window.location.hash.substring(1)) {
				selected = value;
			}
		});
		
		if(selected === undefined) {
			if(movie_list.length > 0) {
				selected = movie_list[0];
			} else if(text_list.length > 0) {
				selected = text_list[0];
			}
		}
		
		if(selected) {
			var value = selected;
			if(value.youtube_id !== undefined && value.youtube_id != "") {
			
				var youtube_id = value.youtube_id.replace('http://www.youtube.com/watch?v=','');
			
				/*
					We only update if the video changed
				*/
				if(render_lists.last_youtube_id != youtube_id) {
					$(".movie_target").empty();
					$(".movie_target").html(

		        '<object youtubeid="'+youtube_id+'" width="540" height="328"><param name="movie" value="http://www.youtube.com/v/'+youtube_id+'&hl=en&fs=1?rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><param name="wmode" value="opaque"></param>'+
		          '<param name="bgcolor" value="#000000"></param>'+
		          '<embed src="http://www.youtube.com/v/'+youtube_id+'&hl=en&fs=1?rel=0" wmode="opaque" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="540" height="328" bgcolor="#000000"></embed>'+
		        '</object>'
		        );	
		
					render_lists.last_youtube_id = youtube_id;
				}
			} else if(value.image_url !== undefined && value.image_url != "") {
				$(".movie_target").empty();
				$(".movie_target").html(

	        '<img alt="" src="'+value.image_url+'" />'
	        );
	
				$.get('/video_questions/'+value.id+'/increment_view');
	
			} else {
				$(".movie_target").empty();
				$.get('/video_questions/'+value.id+'/increment_view');
			}
		
			$('.text_target').html(value.long_text);
		}
			


		
		render_lists.last_hash = window.location.hash;
	}
	




	
	/*
		Renders the list of text questions
		
		uses these elements as target for the data
		
			<ul id="text_questions"></ul>
			<div class="text_target"></div>
			
		
	*/
  $(function() {
    
    
		render_lists();
      
  });







	/*
		New file upload manager
	*/



	var get_file = function(callBack) { 



	  var file_list = [];

	  var html = '<div id="file_manager_root">\
	    <div id="file_manager_blanker">\
	    </div>\
	    <div id="file_manager">\
	      <div class="container">\
	        <div class="preview_area"></div>\
	        <div class="list">\
	          <div style="clear: both;"></div>\
	        </div>\
	        <div class="buttons">\
	          <div id="button1" class="button">Upload</div>\
	          <div class="cancel_button">Cancel</div>\
	          <div style="clear: both;"></div>\
	        </div>\
	      </div>\
	    </div>\
	  </div>';

	  var test = $('      <div class="file">\
	          <div class="file_image">\
	            <img alt="" src="">\
	          </div>\
	          <div class="text">\
	              utneohauhsa eohutnsheoa  utnheoa uth eoa hutneoah\
	          </div>\
	        </div>');


	    var list = $('div.list');

	  $('body').append($(html));

	  $('div.cancel_button').click(function() {
	    $('#file_manager_root').remove();
	    callBack(undefined,true);
	  });

	  var handel_click = function(e) {
	    var value = $(e.target).parents('div.file')[0].value;
	    $('#file_manager_root').remove();
	    callBack(value.url,false);
	  };

	  var handel_hover_enter = function(e) {
	    var item = $(e.target).closest('div.file')[0].value;

	    var found = false;
	    $('.preview_area img').each(function(index,value) {
	      if($(value).attr('src') == item.url) {
	        found = true;
	      }
	    });

	    if (found == false) {
	      var result = $('.preview_area img');
	      result.fadeOut(300,function() {
	        result.remove();
	      });
	      $('<img style="display: none;" src="'+item.url+'">').appendTo('.preview_area').fadeIn(500);
	    }
	  };

	  var render = function() {

	    $('#file_manager div.list div.file').remove();

	    $.each(file_list,function(index,value) {
	      var b = test.clone();
	      b.find('div.text').text(value.name);
	      b.find('img').attr('src',value.url);

	      b[0].value = value;

	      $('#file_manager div.list').append(b);

	      b.click(handel_click);
	      b.mouseover(handel_hover_enter);
	    });
	  };

	  var load = function() {
	    $.ajax({
	      url: '/files/list?callback=?',
	      dataType: 'json',
	      success: function(data) {
	        file_list = data;
	        render();
	      }
	    });

	  };


	  load();

	  /* example 1 */
	  	var button = $('#button1'), interval;
	  var f =	new AjaxUpload(button,{
	  		//action: 'upload-test.php', // I disabled uploads in this example for security reasons
	  		action: '/files/upload', 
	  		name: 'new_file',
	  		onSubmit : function(file, ext){
	  			// change button text, when user selects file			
	  			button.text('Uploading');

	  			// If you want to allow uploading only 1 file at time,
	  			// you can disable upload button
	  			this.disable();

	  			// Uploding -> Uploading. -> Uploading...
	  			interval = window.setInterval(function(){
	  				var text = button.text();
	  				if (text.length < 13){
	  					button.text(text + '.');					
	  				} else {
	  					button.text('Uploading');				
	  				}
	  			}, 200);
	  		},
	  		onComplete: function(file, response){
	  			button.text('Upload');

	  			window.clearInterval(interval);

	  			// enable upload button
	  			this.enable();

	  			if(response == 'success') {
	  			  load();
	  			} else if(response == '_unknown_') {
	  			  /* Happens when we do crass domain uploads */
	  			  load();
	  			} else {
	  			  alert(response);
	  			}
	  		}
	  	});

	};











