$('document').ready( function() {
	mainInit();
});

function mainInit() {
	// initHoverHelpers();
				
	$('.toggler h3').siblings().hide();
	$('.toggler h3').click( function() {
		$(this).siblings().toggle();
	});
	
	$('a.moment').media(
		{
			attrs:     { allowFullscreen:  'true' }
		}
	);
	
	$(".introMovie").flash(
		{
			id: 'introMovieFlash',
		    src: '/flash/introVideo.swf',
		    width: '100%',
		    height: '100%',
		    wmode: 'transparent',
		    flashvars: { videoSource: "http://educations.nu/flash/jimmy1.flv" }
		},
		{ version: 9 }
	);
	
	$('.introMovie div').hide();	
	$('.btn_diagonalStripes').append( "<img class='pngFix' style='position: absolute; bottom: -1px; right: -6px' src='/images/bg_diagonalStripes.png' alt='' />" );
	
	$('.togglerContainer').hide();
	$('.hoverToggler').hover( function() {
		$(this).children('.togglerContainer').fadeIn(500);
	}, function() {
		$(this).children('.togglerContainer').fadeOut(500);
	});
	
	$('a.btn_newAnswer').click(function() {
		
		var answer = $(this).parent().prev().children('div:last'),
        index = answer.children('div').children('textarea').attr('id').split('_')[2],
        newIndex = parseInt( index ) + 1,
        newAnswer = answer.clone().insertAfter( answer );
		
		newAnswer.children('label').attr("for", "answerId_new_"+newIndex );
		newAnswer.children('div').children('textarea').attr("id", "answerId_new_"+newIndex );
		newAnswer.children('div').children('textarea').attr("name", "answerId_new_"+newIndex );
		
		newAnswer.children('div').children('div').children('label').attr("for", "answerScore_new_"+newIndex );
		newAnswer.children('div').children('div').children('input').attr("id", "answerScore_new_"+newIndex );
		newAnswer.children('div').children('div').children('input').attr("name", "answerScore_new_"+newIndex );
		
		
	});
  
 
 	/*
	var inputform = '<div class="inputContainer clearer"><label for="categories" class="btn_diagonalStripes bg_sexyGrey optional">"Frågekategori"</label></div>';
 
        $( '.spinaForm' ).append(inputform);
        console.log(inputform);
        
*/

  var button = $('#showbutton');
    button.append( "Lägg till ny kategori" );
    button.click(function() {

	 
	 $i = 1;
 	 while( $i){
 	 	if(!$('#categories' + $i).parent('div').is(":visible")){
			$( '#categories' + $i ).parent('div').show();
        	$('#numOfQ' + $i).parent('div').show();
			break;
	  	}
	  	$i++;
 	 }
    });
  

  
	$('#expandparticipants').delegate( ".showall", "click", function(){ 
    
    var $this = $( this );

    if( $this.is( ".open" ) ){
      $this.siblings( "ul" ).hide()
      .end()
      .removeClass( "open" );
    }
    else{
      $this.siblings( "ul" ).show()
      .end()
      .addClass( "open" );
    }
  });
  
	$('input.departmentCheckbox').click(function() {
		var checked = $(this).attr('checked');
		$(this).parent().children('div').children('input').attr('checked',checked ? 'checked' : '');
	});
	
	$('.departmentsList').hide();
	$('a.departmentExpander').click(function() {
		$(this).parent().parent().children('div').toggle();
	});
	
	$().mousemove(
		function(e){
			xmouse = e.pageX; ymouse = e.pageY;
			$('#hoverhelper').css('left', xmouse - 40 ).css('top', ( ymouse + 20  ) );
		}
	); 
	
	var st = "";
	for( var i in theVars ) {
		st += i + " : " + theVars[i] + "\n";
	}
	
	$("#pageHeader").flash({
	    src: '/flash/spinaHeader.swf',
	    width: '100%',
	    height: '100%',
	    wmode: 'transparent',
	    flashvars: theVars
		},
		{ version: 9 }
	);
	
	$(".stageEntry a").click(
		function( ) {
		
			var obj = $(this).parent();
			
			if( obj.hasClass("openStageEntry") ) obj.removeClass("openStageEntry");
			else obj.addClass("openStageEntry");
		
		}
	);

	$('.dropDown').hover( 
		function() {
			$(this).children('.dropDownContainer').toggle();
		},
		function() {
			$(this).children('.dropDownContainer').toggle();
		}
	);

	$("#participantsForm .departments").each(
		function() {
			var allChecked = true;
			var users = jQuery.makeArray( $(this).siblings("ul").children("li").children(":checkbox") );
			for( var i=0; i<users.length; i++ ) {
				allChecked = jQuery( users[i] ).attr('checked');
				if( !allChecked ) break;
			}
			
			if( allChecked ) $(this).attr("checked", "checked");
		}
	);

	$("#participantsForm .departments").change(
		function() {
			var checked = $(this).attr('checked');
			var users = $(this).siblings("ul").children("li").children(":checkbox");
			if( checked ) users.attr('checked', 'checked');
			else users.removeAttr('checked');
			
			users.each( changeParticipantsCheck );
		}
	);
	
	$("#participantsForm .users").change( changeParticipantsCheck );
	
	
	if( chat )  initChat();
	
	if( $("form").length > 0 ) {
		formPlacement();
	}

		$('#circlearrow').toggle(
		   function()
		   {
				moveUserArea( true );    
				$('#circlearrow').css({'background-position':' 0px -53px'})
		   },
		   function()
		   {
				moveUserArea( false );
				$('#circlearrow').css({'background-position':' 0px 0px'})
	   });


	moveUserArea( false );

	setInterval( "updateTestTime()", 200 );
	
	testTime = parseInt( theVars.endTime ) - parseInt( theVars.time );
	$('.showTime, .hideTime').click(
		function() {
			
			showTime = $( this ).hasClass( 'showTime' );
			$('.showTime, .hideTime').toggle();
			$('#testTime').html( showTime ? timeString : "&ndash;&ndash;:&ndash;&ndash;" );
		}
	);
	

	$('#questionCommentFormToggler').click( function() {
			$('#questionCommentForm').toggle();
    }
	);
	
	
	initQuestionBox();

	initNewWindowLink();
	
	
	if( IE6 ) fixPNG();
	
	$('#questionBox').hide();
	$('#questionBox').css('top', '0px');
}
//Admin education and department ajax search

function searchEducation(inputString) {

    console.log(inputString.length);    
    if(inputString.length <= 1) {
      $.post('/admin/searcheducation/format/html', {'searchline': inputString}, function(data){ 
        $('#educationList').html( data); 
      });
    } else {
      if(inputString.length >=1) {
        $.post("/admin/searcheducation/format/html", {'searchline': inputString}, function(data){   
           $('#educationList').html(data);      
        });
        }
    }
    return false;
  }
  
  function searchDepartment(inputString) {

    console.log(inputString.length);    
    if(inputString.length <= 1) {
      $.post('/admin/searchdepartment/format/html', {'searchline': inputString}, function(data){ 
        $('#departmentList').html( data); 
      });
    } else {
      if(inputString.length >=1) {
        $.post("/admin/searchdepartment/format/html", {'searchline': inputString}, function(data){   
           $('#departmentList').html(data);      
        });
        }
    }
    return false;
  }
  
  //Editdepartment ajax usersearch 
  
  function lookup(inputString) {
    var depId = window.location.pathname.split("/")[4];
    // var ajaxLoader = $( "<img>" ).attr( {"src" : "/images/spinaIcons/ajax-load.gif", "style" : "margin-left:50%;"} ).fadeIn( "fast" );
		// $("#users").after(ajaxLoader);
    if(inputString.length <= 1) {
      $.post('/department/usersforeditdep/format/html', {'searchline': inputString, 'depId':depId}, function(data){
        // ajaxLoader.remove();   
        $('#users').html( data); 
      });
    } else {
      if(inputString.length >=1) {
        $.post("/department/usersforeditdep/format/html", {'searchline': inputString, 'depId':depId}, function(data){
           // ajaxLoader.remove();
console.log(data);           
            $('#users').html(data);      
        });
        }
    }
    return false;
  }

function fixPNG() {
	
	$('img:not(.pngFix)').each( 
		function() {
			if( $(this).attr('src').indexOf( 'png' ) != -1 ) {
				$(this).addClass( 'pngFix' );
			}
		}
	);
	
	$('a:not(.pngFix), div:not(.pngFix)').each( 
		function() {
			if( $(this).css('backgroundImage').indexOf( 'png' ) != -1 ) {
				$(this).addClass( 'pngFix' );
			}
		}
	);

}

function initNewWindowLink() {
	
	
	$('.newWindow').click(
		function() {
			
			window.open( $(this).attr('href'), 'mywindow' );
			return false;
		}
	
	);
	
	
}

var scrollTopBeforeQuestion = 0;

function initQuestionBox() {
	
	
	$('.questionBoxed').click(
		function() {
			
			var data = $(this).metadata();
			
			$('#questionBoxTitle').html( data.title );
			$('#questionBoxText').html( data.text );
			$('#questionBoxYes').html( data.yesText );
			$('#questionBoxNo').html( data.noText );
			$('#questionBoxYes').attr('href', $(this).attr('href') ); 
			$('#questionBox').fadeIn( 300 );
			$('.moment').hide();

			scrollTopBeforeQuestion = $( ( IE6 ? '#scrollContainer' : 'html' ) ).scrollTop();
			$('#scrollContainer').hide();

			return false;
		}
	);
	
	
	$('#questionBoxNo').click( 
		function() {
			$('#questionBox').fadeOut( 300 );
			$('.moment').show();
			
			$('#scrollContainer').show();
			$( ( IE6 ? '#scrollContainer' : 'html' ) ).scrollTop( scrollTopBeforeQuestion );
			
		}
	);
	
}

function moveUserArea( show ) {
	
	var ua = $("#userArea");
	var pos;

	if( show ) pos = 0;
	else pos = ( controller == 'test' && action == 'show' ? 10 : 40 ) - ua.height();
	
	ua.stop();
	ua.animate({ 
		bottom: pos + "px"
	}, 200 );
	
}

var d = new Date(),
    tick = 0,
    stTime = d.getTime(),
    endTime = stTime,
    testTime,
    showTime = true,
    timeString = "";

function updateTestTime() {
	
	
	if( showTime ) {
		d = new Date();
		endTime = stTime;
		stTime = d.getTime();
		tick = ( stTime - endTime );
		testTime -= tick * 0.001;
		
		//document.title = testTime;

		timeString = "00:00";
		
		if( testTime > 0 ) {
			var h = Math.floor( testTime / ( 60 * 60 ) );
			var m = Math.floor( testTime / 60 ) % 60;
			var s = Math.floor( testTime ) % 60;
			
			timeString = ( h > 0 ? h+ ":" : "" ) + ( m >= 10 ? m : "0"+m ) + ":" + ( s >= 10 ? s : "0" + s );  
			
		}
		
		
		//document.title = "längd: " + $('#testTime').length;
		
		$('#testTime').html( timeString );
		
		//document.title = tick;
	
	}
	
}

function changeParticipantsCheck( some, obj ) {
	if( obj == undefined ) obj = $(this);
	
	var checked = $(obj).attr('checked');
	var ar = $(obj).attr('class').split("_");
	var uId = ar[ar.length - 1];
	var users = $(".user_"+uId);
	if( checked ) users.attr('checked', 'checked');
	else users.removeAttr('checked');
}


function introVideoDone( ) {
	$('.introMovie').empty();
	$('.introMovie').hide( 1000 );
}


function saveAnswers( nextIndex ) {
	$("#nextQuestionIndex").attr('value', nextIndex); 
	setTimeout('delayedSubmit();', 200);
}

function delayedSubmit() {
	$("form#instanceForm").submit();
}

var gettingChat = false;
var sendingChat = false;
var oldHtml = "";
function getChats() {
	
	
	if( !gettingChat ) {
		$.ajax({
			url: '/chat/ajax/',
			cache: false,
			success: function(html){
				//alert( html );
				if( oldHtml != html ) {
					oldHtml = html;
					
					var code = "var theHtml = " + html;
					eval( code );
					
					$("#chatContainer").html( theHtml.chatList );
					$('#chatContainer').scrollTop( $('#chatContainer').attr("scrollHeight") );
					
					$("#userListContainer").html( theHtml.userList );
					
				}
				
				setTimeout( "getChats();", 5000 );
				gettingChat = false;
			}
		});

		gettingChat = true;
	}
}


function initChat() {
	getChats();
	
	/*
	$('#chatForm').ajaxForm(
		function() {
			$('input[name=text]').val('');
			getChats();
		}
	);
	*/
	
	$('#chatForm').submit(
		function() {
			
			if( !sendingChat && $('input[name=text]').val().length > 0 ) {
				
				$('input[name=text]').attr('readonly', 'readonly');
				$('input[name=text]').css('backgroundColor', '#ccc');
				
				$('input[type=submit]').attr('disabled', 'disabled');
				
				$(this).ajaxSubmit(
					function() {
						sendingChat = false;
						
						
						$('input[name=text]').removeAttr( 'readonly' );
						$('input[name=text]').css('backgroundColor', '#fff');
						$('input[name=text]').val('');
						
						$('input[type=submit]').removeAttr( 'disabled' );
						
						
						getChats();
					}
				);
				sendingChat = true;
			}
			
			return false;	
		}
	);
}

function removeChat( chatId ) {
	//alert( chatId );
	$.post( 
		"/chat/ajaxremove/chatId/"+ chatId,
		null,
		function() {
			alert( "deleted!" );
		}
	);
}



function formPlacement() {
	
	//alert( $('.inputContainer').length );
	
	$('.inputContainer').each(
		function() {
			
			var cw = Math.min( 500, $(this).width() );
			//alert( cw );
			
			var lw = $(this).children('label').width();
			//alert( lw );
			
			var restw = cw - lw;
			
			if( restw > 100 ) {
				$(this).children('input, select').each( 
					function() {
						$(this).css('clear', 'none').css('margin-left', '5px');
						
						if( $(this).is( 'input[type=text], input[type=file], input[type=password], select' ) ) {
							
							$(this).css('width', ( restw - ( $(this).is('input[type=text], input[type=password]') ? 35 : 30 ) )+"px" )
						}
					}		
				);	
			}
			
			
			$(this).children('textarea').css("width", (cw-10)+"px").css('overflow', 'auto');
		}
	);

	 
	
 	 for($i=0; $i<20; $i++){
 	 	if($('#categories' + $i).attr( 'selected', 'selected' ).val() == 0){
			$( '#categories' + $i ).parent('div').hide();
        	$('#numOfQ' + $i).parent('div').hide();
			
	  	}
	  
 	 }
}




