

var g_answer_saved = false;
var newColHeight = 0;


$(window).load(function(){

	$("nav.navigation li.NewCol>ul>li").each(function(){
		var h = parseInt($(this).height(), 10);
		
		if(h > newColHeight) {
			newColHeight = h;
		}
	});

	$("nav.navigation li.NewCol>ul>li").height(newColHeight);

});

$(document).ready(function(){

	$('a.add').live('click', function(event){
			event.preventDefault();
				var lngBookId         =  $(this).attr('rel');
				var strBookTitle      =  $(this).attr('Title');
				var intShoppingbasket =  parseInt ($("#ItemsInCart").text());
				
				$.ajax({
					url:'ajax.asp',
					data:'ajax_action=1&book_id='+lngBookId+'',
					type: 'post',
					error: function(){
						alert ("bøk er ikke lagt i handlekurv");
					},
					success: function(msg){
						
						$("#ItemsInCart").text(intShoppingbasket + 1);

						alert ( strBookTitle + ' er lagt i handlekurv' );
						
					}
				});
			
	});
	
	
	$('a.AutoSave').live('click', function(event){
		var myhref = $(this).attr("href");
		var interval = 1500; //ms
		var timeout = 5000; //ms
		var numAnswers = $('input.submitAnswer').length;
		var numSuccess = 0;
		var waitTimeBeforeReload = 1500;
		//console.log(new Date().getMilliseconds());
		//console.log(myhref);

		timeout = timeout + (numAnswers * 1000);
		
		$('input.submitAnswer').each(function() {
			timeout = 2000;
			g_answer_saved = false;
			
			$(this).trigger("click2.autosave");
			//$(this).trigger("click");
			
			var loop = setInterval(function(){
				if(g_answer_saved) {
					numSuccess++;
					clearInterval(loop);

					if(numAnswers == numSuccess) {
						//console.log(myhref);
						setTimeout(
							  function() 
							  {
								document.location = myhref;
								
							  }, waitTimeBeforeReload);

						//document.location = myhref;
					}
				} else if(timeout <= 0) {
					alert("Kunne ikke lagre, vennligst prøv igjen.");
					clearInterval(loop);
					return false;
				}
				
				timeout -= interval;
			}, interval);
			
			
		});
		
		//alert(1);
		
		return false;
	});
		
		
	//Auto Save	on page navigate
	// $(window).unload(function() {
	// //alert('Handler for .unload() called.');
	// //$('input.submitAnswer').trigger("click");
	// });	


	$('input.submitAnswer').live('click click2.autosave', function(event){
			event.preventDefault();
			
			//console.log(event);
			
			/* ************************************ **/
			var blnRefresh, clsRefresh;
			clsRefresh = $('a.genNewRow');
			/* need to refresh if the class has refresh attribute, which means the a.genNewRow exists on the page */
			/*And Only refresh if the user clicks the butten*/
			
			var strNamespace;
				strNamespace = event.namespace; /*This has to be empty, if it contains autosave then the autosave code has triggered it */
			//console.log(strNamespace);
			
			blnRefresh = clsRefresh.length && clsRefresh.length > 0 &&  strNamespace != 'autosave';
			// &&  strNamespace != 'autosave' ;
			
			if (blnRefresh) {
				console.log(blnRefresh);
			}
			
			/* ************************************ **/
			
			if(true) {
				alert("Du har blitt logget ut automatisk pga. inaktivitet. Vennligst logg inn på nytt");
				document.location.reload()
				return false;
			}
			
			$.blockUI({ 
				message: 'Lagrer, vennligst vent.',
				overlayCSS:  { 
        	backgroundColor: 'transparent', 
        	opacity: 1 
    		},
    		css: {
    			padding: '15px'
    		}
			});
			
			/* depending on which question-del, different id for question-title and textarea needed */
			/* Can not be allowed to save if any relevent id's are mising ie. userId oppgaveId oppgavedel*/
			
			var lngOppgaveDel  = $(this).attr('rel');
			var lngOppgaveId   = $('#Oppgave-Title').attr('value');
			var strId          = $(this).attr('id');
			var lngId          = strId.slice (strId.indexOf('_') + 1,  strId.length );  
			
			//var blnSuccess     = true;
			
			//alert ( lngId + ' '  + strId.length + ' ' + strId.indexOf('_')) ;
			
			var txtQuestionDivName       = '#title'  + lngId;
			//var txtAnswerTextAreaName    = 'textarea#textarea'  + lngId;
			var txtAnswerTextAreaName    = 'textarea.textarea'  + lngId;
			var strQuestion = $(txtQuestionDivName).text();
			var numAnswers = $(txtAnswerTextAreaName).length;
			var numDone    = 0;
			var numSuccess = 0;
						
			//loop this for each item in collection 
			$(txtAnswerTextAreaName).each (function(index){
			
				var strAnswer   = $(this).val();          //$(txtAnswerTextAreaName).val();
				var intPos      = $(this).attr('pos');    //$(txtAnswerTextAreaName).attr('pos');
			
				//alert ( strQuestion + ' ' + strAnswer + ' ' + lngOppgaveDel + ' ' + lngOppgaveId);
				
					$.ajax({
							url:'ajax.asp',
							data:'ajax_action=2&answer_title=' + encodeURIComponent(strQuestion) + 
							'&answer_text=' + encodeURIComponent(strAnswer) + 
							'&answer_part=' + lngOppgaveDel +
							'&oppgaveId=' + lngOppgaveId +
							'&text_pos=' + intPos  +  '',
							
							type: 'post',
							error: function(){
								//alert ("somthing went wrong");
								//blnSuccess = false;
								//console.log(arguments);
								//console.log(intPos + ' ' + lngOppgaveDel); 
								
								
								$.unblockUI();
								alert("Kunne ikke lagre, vennligst prøv igjen");
							},
							success: function(msg){
								//alert ( 'success' );
								numSuccess++;
							},
							complete: function(){
								numDone++;
								
								if(numSuccess == numAnswers) {
									g_answer_saved = true;
								}
								
								if(numDone == numAnswers) {
									$.unblockUI();
									
									if (blnRefresh) {
										document.location.reload();
									}
								}
								
								
							}
						});
			});
			

			// if (blnRefresh) {
			
				// //When all boxes are saved then reoad the page.
				
					// if(numSuccess == numAnswers) {
						// document.location.reload();
					// }
					
			// }
			//if (blnSuccess) {
				//alert ( 'Svar lagret' );
				//location.reload();
			//}else{
				//alert ( 'Noe gikk galt, og svaret var ikke lagret' );
			//}
			
			
	
	});
	
	$('a.genNewRow').live('click', function(event){
		event.preventDefault();
		
		var colCount =  parseInt( $(this).attr('rel') ); 
		var rowCount = parseInt ( $('input.#rowCount').attr('value') );
		rowCount = rowCount + 1;
		
		var strHtml = '<textarea cols=\"30\" rows=\"10\" title=\"textarea\" pos=\"'  + rowCount + '\" class=\"textarea1\"></textarea>'
		var strHtml2 = '<textarea cols=\"30\" rows=\"10\" title=\"textarea\" pos=\"'  + rowCount + '\" class=\"textarea2\"></textarea>'
		
		//alert (colCount);
		if  (colCount === 1){ 
			//$('tr.footer').before('<tr><td></td><td>' + strHtml + '</td><td></td></tr>');
			$('tr.footer').before('<tr><td class=\"col1\"></td><td class=\"col2\">' + strHtml + '</td></tr>');
		}else {
			
			//$('tr.footer').before('<tr><td></td><td>' + strHtml + '</td><td>' + strHtml2 + '</td></tr>');
			$('tr.footer').before('<tr><td class=\"col1\"></td><td class=\"col2\">' + strHtml + '</td><td class=\"col3\">' + strHtml2 + '</td></tr>');
		}
		
		
		//increase row count
		$('input.#rowCount').attr('value', rowCount); 
		
	});
	
	
	$('a.svarveiledning').live('click', function(event){
		event.preventDefault();
		var lngOppgaveDel  = $(this).attr('rel');
		var strSpanName    = 'span#' + lngOppgaveDel;
		
		var strDelText     = $(strSpanName).html();
		var divSvarBoxNode = $('#Svarveiledning');
		
		//console.log(strDelText);
		
		//var position       = $(this).offset(); //.position();
		// alert(position.left + ' '+ position.top)
		// var objCoords =  new Object; 
			// objCoords.left     = position.left;
			// objCoords.top      = position.top;
			
		//console.log(position);	
	
		
		var box = $(this).closest("div.box");
		//var offset = box.offset();
		var offset;
		
		// "div.box" not always present
		if(box.offset() == null) {
			//box = $(this);
			box = $(this).closest("fieldset");
			offset = { 
				//left: box.offset().left - 386, 
				left: $(this).offset().left + 250, 
				top: box.offset().top - 2 
			};
		} else {
			offset = { 
				left: box.offset().left - 386, 
				top: box.offset().top - 2 
			};
		}
		
		
		//offset.left -= 386;
		//offset.top -= 2;
			
		
			
		var strLiPopup     =  'li.popup-holder[ref=\"' + 10000 + '\"]';
		var liNode         = $(strLiPopup);
		
		var strDivArea     =  'div.area[ref=\"' + 10000 + '\"]';
		var divNode        = $(strDivArea);
		
		//divNode.text(strDelText);
		divNode.html(strDelText);
		
		liNode.addClass("active");
		
		//divSvarBoxNode.offset($(this).offset());
		divSvarBoxNode.find("*").css("width", "auto");
		
		divSvarBoxNode.find("a.close").css("width", "13px");
		
		divSvarBoxNode.offset(offset);
		
		//alert (strDelText);
		

	});
	
	function Answer(id, answer){
		this.id = id;
		this.answer = answer;
	
	};
	
	function Quiz(id, answer){
		this.id = id;
		this.Answers = answer;
	};
	
	function Quizes(quiz){
		this.Quiz = quiz;
	};
	
	
	$('.deleteline').live('click', function(event){
		event.preventDefault();
		
		var lngOppgaveId   = $('#Oppgave-Title').attr('value');
		var pos =  parseInt( $(this).attr('ref') ); 
		
		//alert(lngOppgaveId + " " + pos);
		
		
		$.ajax({
			url:'ajax.asp',
			data:'ajax_action=4&text_pos='+pos+
			'&oppgaveId=' + lngOppgaveId + '',
			
			type: 'post',
			error: function(){
				
			},
			success: function(msg){
				location.reload();

			}
		});
		
		
		
	});
	
	
	
	
	
	$('input.Quiz').live('click', function(event){
		event.preventDefault();
	
		var jsonObj = {} ;
		var lngOppgaveId   = $('#Oppgave-Title').attr('value');
		var lngQuizId        = $(this).attr('ref');
		var strAnsersString  = 'div.area[rel=\"' + lngQuizId + '\"] input:radio:checked';

		var strLiPopup  =  'li.popup-holder[ref=\"' + lngQuizId + '\"]';
		var liNode = $(strLiPopup);
		
		var AnswerArray = [];
		
		var answersById = $(strAnsersString);
		
		$(answersById).each(function(index){
			var lngAnswerId = $(this).attr('rel');
			var strAnswer   = $(this).attr('value');

			AnswerArray.push( new  Answer( lngAnswerId, strAnswer ) );
			
			//alert(strAnswer + " " + lngAnswerId);

		});
		
		jsonObj = new Quiz(lngQuizId, AnswerArray);
		
        var jsonStr = JSON.stringify(jsonObj);
        //alert(jsonStr);
		
		
		$.ajax({
			url:'ajax.asp',
			data:'ajax_action=3&answer_text=' + encodeURIComponent(jsonStr) + 
			'&oppgaveId=' + lngOppgaveId + '',
			
			type: 'post',
			error: function(){
				//alert ("somthing went wrong");
			},
			success: function(msg){

				alert ( 'Oppgave lagret' );
				liNode.removeClass("active");
			}
		});
		
	});
	
	
	
	$('a.open').live('click', function(event){
		event.preventDefault();
		var lngQuizId   = $(this).attr('ref');
		var strLiPopup  =  'li.popup-holder[ref=\"' + lngQuizId + '\"]';
		var liNode = $(strLiPopup);
		
		liNode.addClass("active");
		
	});
	
	
	$('a.close').live('click', function(event){
		event.preventDefault();
		var lngQuizId   = $(this).attr('ref');
		var strLiPopup  =  'li.popup-holder[ref=\"' + lngQuizId + '\"]';
		var liNode = $(strLiPopup);
		
		liNode.removeClass("active");
		
	});
	
	
	
	$('a.nesteCol').live('click', function(event){
		event.preventDefault();
		var lngTextBoxId   = $(this).attr('ref');
		var strNextTextBox  =  'textarea.textarea' + lngTextBoxId + '[pos=\"' + 1 + '\"]';
		
		$(strNextTextBox).focus();
		
	});
	
	
	
	// $('h2').simpletip(
	// {
		
		// var strText = $(this).text();
		// content: strText + ' is a <h1>tool</h1> tip right here', 
		// fixed: false
	
	// }
	// );
	
	$('info').each(function(i){
		var strText = $(this).html();
		//$(this).simpletip({ content: strText }); 
	});
	
	
	
	// $('a.info').live('click', function(event){
		// event.preventDefault();
	// });
	
	// $('a.info').removeAttr('href');
	
	
	$('a.banner-login').live('click', function(event){
		event.preventDefault();
		
		$('#login-info').text("*Vennligst Logg inn først");
		$('#txtUsername').removeAttr('value');
		$('#txtUsername').focus();
	});
	
	
	// $('#txtUsername').live('click', function(event){
		// $('#txtUsername').removeAttr('value');
	// });
	
});
