





 $(document).ready(function() {


    $('#courseSelector').change(function() {
	if( isEdit() ){	    
	    var selectedCourseId = ($(this).val());	    
	    var currentCourseId = getCourseId();
	    
	    
	    if( currentCourseId != selectedCourseId ){	    
		    if( selectedCourseId == 0 ){	    
			 if(confirm( "Laste standard baneoppsett?\n\n") ){
				updateCourseData( getDefaultCourseData() );

				//removeRoundData();				                  
				var roundId = generateRoundId();
				setRoundId( roundId );

				update();
				resetLockTimeLeft();
			  }
		    }else{
			//load from server
			// alert('server perver ' + selectedCourseId );
			if(confirm( "Laste inn standard baneoppsett fra server?\n\n" ) ){
							loadDefaultCourseFromServer();
			
							// removeRoundData();				                  
							var roundId = generateRoundId();
							setRoundId( roundId );
			
							update();
							resetLockTimeLeft();
			}

		    }
             }
	}
    });



    $(".loadServerCourseList").click(function() {
   	if( isEdit() ){
   		if( confirm( "Laste liste over baner fra serveren ?\n\n" ) ){
   		    // save json object
			setServerCourseList( "<option value='5'>Standard bane fra server</option> " );

			updateCourseList();
   		}
	}
   });


	$("#LiveViewScoreViewUpdateWithLatest").click(function() {
		getNewLiveScoreRows();
   	});
 
   $(".hider").click(function() {
   	if( isEdit() ){
   		resetLockTimeLeft();
   		
	        if( isShowDetails() ){
			setShowDetails( false );        
		}else{
			setShowDetails( true  );        
		}       
	}
   });
   $(".edit").click(function() {
        unlock();
   });
   
   $(".resetRound").click(function() {
           if( isEdit() ){
              resetLockTimeLeft();
               
              if(confirm( "Starte ny runde (og avslutte gjeldende) ?\n\n" ) ){
                  removeRoundData();
                  
                  var roundId = generateRoundId();
		  setRoundId( roundId );
	      }
           }
   });




   $(".UseAutoForward").click(function() {
	if( isEdit() ){		
		setUseAutoForward( ! getUseAutoForward() );
                                           
                update();
                resetLockTimeLeft();                                                          
	}
   });    

   $(".liveScoring").click(function() {
	if( isEdit() ){
		if( getUseLiveScoringWarningShowed( ) == false ){
			alert( "Bruk av direkteoppdateringer medforer en viss nettverkstrafikk\n\nSa no veit du da, og du far aldri hore mer om det\n\n" );
			setUseLiveScoringWarningShowed( true );
		}

		setUseLiveScoring( ! getUseLiveScoring() );
                                           
                update();
                resetLockTimeLeft();                                                          
	}
   });    
   $(".liveScoringAnonymous").click(function() {
   	if( isEdit() ){
   		setAnonymousLiveScoring( ! getAnonymousLiveScoring() );
                                              
                update();
                resetLockTimeLeft();                                                          
   	}
   });

   
   $(".lockTimeUp").click(function() {
                 if( isEdit() ){
                    var lockTime = getLockTimeValue();
                                        
                    setLockTimeValue( lockTime +1 );
                    resetLockTimeLeft();                                   
                 }
   });
   $(".lockTimeDown").click(function() {
              if( isEdit() ){
                 var lockTime = getLockTimeValue();
                 
                 if( lockTime > 2 ){
                 	setLockTimeValue( lockTime -1 );
                 }
                 resetLockTimeLeft();                                   
              }
   });
   
   
   $(".lock").click(function() {
   	lock();
   });


   $(".value").click(function() {
       if( isEdit() ){
           resetLockTimeLeft();
       
           var holeNum   = parseInt( $(this).attr("data-holeNum") );
           var holeValue = parseInt( $(this).attr("data-holeValue") );
           
           setHoleValue( holeNum, holeValue );
                     
           
           $( ".value_" + holeNum ).removeClass("selectedValue");
           $( "#value_" + holeNum + "_" + holeValue ).addClass("selectedValue");
           
           sendLiveScoreToServer( holeNum );
           
           
           
           if( getUseAutoForward()  ){
           	setCurrentHole( (holeNum +1) );           

		hideAllHoleDivs();
		setHoleDivVisible( getCurrentHole() );           
           }
           
           
           update();
        }
   });

   $(".valueReset").click(function() {
          if( isEdit() ){
              resetLockTimeLeft();
          
              var holeNum   = parseInt( $(this).attr("data-holeNum") );
              var holeValue = parseInt( $(this).attr("data-holeValue") );
              
              removeHoleValue( holeNum );
                        
              
              $( ".value_" + holeNum ).removeClass("selectedValue");
              //$( "#value_" + holeNum + "_" + holeValue ).addClass("selectedValue");
              
              
              update();
           }
   });



    $(".exportScore   ").click(function() {
	       if( isEdit() ){
	       	    resetLockTimeLeft();	       		
	           sendRoundToServer();
	           resetLockTimeLeft();	           
	        }
   });
   
   $(".holeNavi").click(function() {
       if( isEdit() ){
       	    resetLockTimeLeft();
       		
           var holeNum   = parseInt( $(this).attr("data-holeNum") );
           
           
              setCurrentHole( (holeNum ) );           
              update();
              
              hideAllHoleDivs();
		setHoleDivVisible( getCurrentHole() );
           
        }
   });

	$(".next").click(function() {
		if( isEdit() ){
			resetLockTimeLeft();
			var holeNum   = parseInt( $(this).attr("data-holeNum") );

			if( holeNum < 19 ){
				setCurrentHole( (holeNum +1) );           
				update();

				hideAllHoleDivs();
				setHoleDivVisible( getCurrentHole() );
			}
		}
	});

   $(".last").click(function() {
	  if( isEdit() ){
	      resetLockTimeLeft();
	      
	      var holeNum   = parseInt( $(this).attr("data-holeNum") );

	      
	      if( holeNum > -1 ){
		 setCurrentHole( (holeNum -1) );           
		 update();
		 
		 hideAllHoleDivs();
		 setHoleDivVisible( getCurrentHole() );
	      }
	   }
   });


    $(".testClass").click(function() {
    	loadDefaultCourseFromServer();
    });

   $(".testClass2").click(function() {
       	test2();
    });
 

	$(".changeUser").click(function() {
		if( isEdit() ){
			if( isPersonLoggedIn() ){
			  	logOutUser();
			}else{
			       	changeUser();
			
			}
       			resetLockTimeLeft();			
		}
	});
	
	
	$(".loadDefaultCourse").click(function() {
		if( isEdit() ){
			if(confirm( "Laste standard baneoppsett?\n\n") ){
				updateCourseData( getDefaultCourseData() );

				//removeRoundData();				                  
				var roundId = generateRoundId();
				setRoundId( roundId );
				
				update();
				resetLockTimeLeft();
			}
		}
	});


	$(".loadDefaultCourseServer").click(function() {
		if( isEdit() ){
			if(confirm( "Laste inn standard baneoppsett fra server?\n\n" ) ){
				loadDefaultCourseFromServer();

				// removeRoundData();				                  
				var roundId = generateRoundId();
				setRoundId( roundId );

				update();
				resetLockTimeLeft();
			}
		}
	});


 });
 
 
 

 



function createScoreCardView(){
	createDefaultData();

	createViews();
	doInitialViewUpdates();
	update();
}


 function test2(){
 
 // Assign handlers immediately after making the request,
     // and remember the jqxhr object for this request
     
     
     
     
     var jqxhr = $.post("OnlineScoreCardServer.php", { action: "getNewLiveScoreRows", topLiveScoreId : "7" }, function(data) {
          
          alert("Data Loaded: " + data);
     
     try {
     
              var loginInfo = jQuery.parseJSON( data );
              
              if( loginInfo["status"] === "ok" ){
              
     		//alert("Nytt baneoppsett lastet ned: " + loginInfo['courseName'] );
     		alert( "ok : " + loginInfo["statusMessage"] );
     	}else{
     		alert( "Noe gjekk galt: " + loginInfo["statusMessage"] );
     	}
     	
     	
     } catch(e) {
	alert( "Noe er feil med resultatet fra serveren: \n\nError:\n" + e + "\n\n" );
	 }
     	
     	
     });
     
     
     
/*     
     var jqxhr = $.post("OnlineScoreCardServer.php", { action: "GetUserInfo" }, function(data) {
     
     alert("Data Loaded: " + data);

         var courseInfo = jQuery.parseJSON( data );
         
         if( courseInfo["status"] === "ok" ){
         
		//alert("Nytt baneoppsett lastet ned: " + courseInfo['courseName'] );
		alert( "ok : " + courseInfo["statusMessage"] );
	}else{
		alert( "Noe gjekk galt: " + courseInfo["statusMessage"] );
	}
     });
     
     */
     
   //  .success(function() { alert("second success"); })
   //  .error(function() { alert("error"); })
   //  .complete(function() { alert("complete"); });
 
     // perform other work here ...
 
     // Set another completion function for the request above
   // jqxhr.complete(function(){ alert("second complete"); });
 
 }
 



function sendLiveScoreToServer(holeNum){

	if( getUseLiveScoring() ){
		if( isSetHoleValue( holeNum ) ){
			var comment =  "";

			var roundId = getRoundId();


			var courseId   = getCourseId(); ;
			var courseName = getCourseName();

			var personId = -1;
			var personName = "Anonym"
			if( getAnonymousLiveScoring() === false ){
				personId   = getPersonId();
				personName = getPersonName();
			}



			var holeValue = getHoleValue( holeNum );
			var holePar   = getHolePar(  holeNum );
			var holeName  = getHoleName( holeNum );



			var postData = { 
				action     : "registrerLiveScore", 

				_personId   : personId,        // 
				_personName : personName,        // 
				_roundId    : roundId,        // 
				_courseId   : courseId,        // 
				_courseName : courseName,        // 
				_holeNum    : holeNum,        // 
				_holeName   : holeName,        // 
				_holeValue  : holeValue,        // 
				_holePar    : holePar,        // 
				_comment    : comment        // 

			};

			// alert( "round : " + roundId + " - dato " + dato + "   -- " + JSON.stringify(postData)  );


			var jqxhr = $.post("OnlineScoreCardServer.php", postData, function(data) {


				 //alert("data: " + data );
				 
				var loginInfo = jQuery.parseJSON( data );

				

				if( loginInfo["status"] === "ok" ){
					// do nothing
					//alert( "Noe gjekk bra: " + loginInfo["statusMessage"]  + "\n\n");
				}else{
					alert( "Noe gjekk galt: " + loginInfo["statusMessage"]  + "\n\nDirekteoppdatering vil bli slått av\n\n");
					setUseLiveScoring( false );					
				}
			})

			.error(function() { 
				  alert("Noe gjekk galt under tilkobling til server \n\nDirekteoppdatering vil bli slått av\n\n");
				  setUseLiveScoring( false );					
				  }
			 );
		} 
	}else{
		//alert( 'Runden er ikke ferdig\n\n' );
	}  
}




function sendRoundToServer(){
	if( isRoundComplete() ){
		if( getPersonId() > 0 ){    
			if( getCourseId() > 0 ){    
				if( isCurrentRoundExported() === false ){
					if(confirm( "Sende resultatet til www.stormkast.no?\n\nDet er etterpa ikke mulig a endre pa\nscore for a sa sende det pa nytt.\n\n\n" ) ){
						var comment =  prompt("Skriv en kommentar til runden (frivillig)","");
						if( comment != null && comment != ""){ 	
							var d = new Date();
							var curr_date = d.getDate();
							var curr_month = d.getMonth();
							curr_month++;
							var curr_year = d.getFullYear();

							if( curr_date < 10 ){
								curr_date = "0" + curr_date;
							}
							if( curr_month < 10 ){
								curr_month = "0" + curr_month;
							}

							var dato = curr_year + "-" + curr_month + "-" + curr_date ;
							var roundId = getRoundId();
							var courseId = getCourseId();    // 5 = 18-hulls bane 
							var personId = getPersonId();
							var whatId = 1;   //trening


							var extraThrows = 0;

							var resultatSum = getTotalScore();
							var resultatPar = getPlayedPar();
							var resultatAvstand = resultatSum - resultatPar;


							var postData = { 
								action     : "registrerRunde", 

								baneSelect     : courseId,        // bane id
								datoFelt       : dato,            // 
								personSelect   : personId,        // personId
								hvaSelect      : whatId,          //  hva id
								kommentar      : comment,         //
								hull_exstra    : extraThrows,     // ekstra kast og straffekast
								hull_1         : getHoleValue( 1), //
								hull_2         : getHoleValue( 2), //
								hull_3         : getHoleValue( 3), //
								hull_4         : getHoleValue( 4), //
								hull_5         : getHoleValue( 5), //
								hull_6         : getHoleValue( 6), //
								hull_7         : getHoleValue( 7), //
								hull_8         : getHoleValue( 8), //
								hull_9         : getHoleValue( 9), //
								hull_10        : getHoleValue(10), //
								hull_11        : getHoleValue(11), //
								hull_12        : getHoleValue(12), //
								hull_13        : getHoleValue(13), //
								hull_14        : getHoleValue(14), //
								hull_15        : getHoleValue(15), //
								hull_16        : getHoleValue(16), //
								hull_17        : getHoleValue(17), //
								hull_18        : getHoleValue(18), //
								resultSum      : resultatSum,       //
								resultAvstand  : resultatAvstand,       //
								resultHash     : roundId        //
							};

							// alert( "round : " + roundId + " - dato " + dato + "   -- " + JSON.stringify(postData)  );


							var jqxhr = $.post("OnlineScoreCardServer.php", postData, function(data) {

								var loginInfo = jQuery.parseJSON( data );

								// alert("data: " + data );

								if( loginInfo["status"] === "ok" ){
									markCurrentRoundAsExported();

									alert( "Runde sendt til www.stormkast.no \n\n" );

									update();
								}else{
									alert( "Noe gjekk galt: " + loginInfo["statusMessage"]  + "\n\n");
								}
							})
							
							.error(function() { 
							          alert("Noe gjekk galt under tilkobling til server \n\n"); 
							          }
							          );
						}  //comment
					}  // check if will export
				}else{
					alert( 'Runden er alt exportert: \n' + getCurrentRoundExportedTime() + "\n\n");
				}     
			}else{
				alert( 'Et baneoppsett fra serveren ma vere valgt\n\n' );
			}     
		}else{
			alert( 'En ma vere innlogget for a sende inn runde\n\n' );
		}     
	}else{
		//alert( 'Runden er ikke ferdig\n\n' );
	}  
}



 function logOutUser(){      
	if(confirm( "Logge ut innlogget bruker?\n\n") ){
		setPersonName( "Ikke innlogget" );
		setPersonId( -1 );

		update();
	}
}



 function changeUser(){
 
 // Assign handlers immediately after making the request,
     // and remember the jqxhr object for this request
     
     var email =  prompt("Skriv inn epost (=brukernavn)","");
     if( email != null && email != ""){
 	
 	var pass =  prompt("Skriv inn passord (vil vises i klartekst)","");
     	if( pass != null && pass != ""){
 	
 		var jqxhr = $.post("OnlineScoreCardServer.php", { action: "loginUser", epost : email, passord : pass }, function(data) {

			var loginInfo = jQuery.parseJSON( data );

			if( loginInfo["status"] === "ok" ){
				setPersonName( loginInfo["userName"] );
				setPersonId( loginInfo["userId"] );
				
				alert( "Ny bruker logget inn : " + loginInfo["userName"] + "\n\n");
				
				update();
			}else{
				alert( "Noe gjekk galt: " + loginInfo["statusMessage"]  + "\n\n");
			}
	     	})
	     	.error(function() { 
		       alert("Noe gjekk galt under tilkobling til server \n\n"); 
		  }
                );
	}
     }

     
   //  .success(function() { alert("second success"); })
   //  .error(function() { alert("error"); })
   //  .complete(function() { alert("complete"); });
 
     // perform other work here ...
 
     // Set another completion function for the request above
   // jqxhr.complete(function(){ alert("second complete"); });
 
 }
 


function doInitialViewUpdates(){
	updateHoleParValueVisuals();
	updateHoleValueVisuals();
	updateHoleNameVisuals()
	
	hideAllHoleDivs();
	setHoleDivVisible( getCurrentHole() );
	setEdit( isEdit() );
	setShowDetails( isShowDetails() );
	
	
	updateCourseList();
	
	lock();
	update();
	
	
}   


function updateCourseList(){

        //  last json object
        // ta hensyn til sist valgte bane
        // resett om ikke på lista

	var courseSelect = "";
	courseSelect = courseSelect + "   <option value='0'>Standard bane</option> ";
	courseSelect = courseSelect + getServerCourseList();
//	courseSelect = courseSelect + "   <option value='5'>Standard bane fra server</option> ";
       $("#courseSelector").html( courseSelect );
}


 function loadDefaultCourseFromServer(){
 
 // Assign handlers immediately after making the request,
     // and remember the jqxhr object for this request
     var jqxhr = $.post("OnlineScoreCardServer.php", { action: "GetDefaultCourse" }, function(data) {

         var courseInfo = jQuery.parseJSON( data );
         
         if( courseInfo["status"] === "ok" ){
         
     
		removeAllStoredCourseData();
		updateCourseData( courseInfo );         

		updateHoleParValueVisuals();
		updateHoleValueVisuals();
		updateHoleNameVisuals()

		update();

		alert("Nytt baneoppsett lastet inn: " + courseInfo['courseName'] + "\n\n" );
	}else{
		alert( "Noe gjekk galt: " + courseInfo["statusMessage"] + "\n\n" );
	}
     })
     .error(function() { 
	  alert("Noe gjekk galt under tilkobling til server \n\n"); 
	  }
      );
   //  .success(function() { alert("second success"); })
   //  .error(function() { alert("error"); })
   //  .complete(function() { alert("complete"); });
 ;
     // perform other work here ...
 
     // Set another completion function for the request above
   // jqxhr.complete(function(){ alert("second complete"); });
 
 }
 



function startLiveView(){
	getLast50LiveScoreRows();
	restartLiveViewTimer();
}

function restartLiveViewTimer(){
   var liveViewUpdateRate = 5000;
	liveViewTimer = setTimeout("restartLiveViewTimer();",liveViewUpdateRate);
	
	getNewLiveScoreRows();
}


var liveViewTimer;




var lockTimer;
var lockTimeLeft = -1;




function lockTimerAction(){
	lockTimeLeft--;
	
	if( lockTimeLeft > 0 ){
		lockTimer = setTimeout("lockTimerAction();",1000);
		update();
	}else{
		lock();
	}
}


function resetLockTimeLeft(){
	if( isEdit() ){
		clearTimeout( lockTimer );
		lockTimeLeft = getLockTimeValue();;
		lockTimer = setTimeout("lockTimerAction();",1000);
	}
}

function lock(){
	clearTimeout( lockTimer );
	setEdit( false ); 
	
	lockTimeLeft = -1;
		
	update();
}

function unlock(){
	setEdit( true );        
		
	resetLockTimeLeft();
	lockTimer = setTimeout("lockTimerAction();",1000);
	
	update();
}

   
   function update(){
       //updateDetails();
       
       
       
       $( ".coursName" ).html( getCourseName() );    
       $( ".userName" ).html( getPersonName() );    
       
       
	//var par = getTotalPar();
	var parPlayed = getPlayedPar();
	var score = getTotalScore();

	$( ".totalScore" ).html( "" + score + " (" + ( score -parPlayed ) + ")" );    
	$( ".totalScoreHeading" ).html( "" + score );    
       
           if( isRoundComplete() ){       		
    		$( ".stormkastScoreString" ).html( getStormkastScoreString() );    
    		
    		
    		if( isCurrentRoundExported() ){
    			$( ".exportScore" ).html( "Score er eksportert til www.stormkast.no" );        		
    		}else{
			$( ".exportScore" ).html( "Eksporter score til www.stormkast.no" ); 
    		}
    		
           }else{        
           	$( ".stormkastScoreString" ).html( "Runden er ikke ferdig" );               	
           	$( ".exportScore" ).html( "Kan ikke eksportere runde som ikke er ferdig" );        		
           }


	if( isEdit() ){	    	        	
		$( ".lock" ).html( "L&aring;s (" + lockTimeLeft + ")" );    
		$( ".edit" ).html( "&Aring;pen" );    	
	   }else{
	
		$( ".lock" ).html( "L&aring;st - Trykk '&Aring;pne'" );    
		$( ".edit" ).html( "&Aring;pne" );    
		
           }	
           
           
           
           if( isEdit() ){	    	        	
               $( "#courseSelector" ).attr( "disabled", "" )
               $( "#courseSelector" ).attr( "enabled", "" )
           }else{
               $( "#courseSelector" ).attr( "disabled", "disabled" )
               $( "#courseSelector" ).attr( "enabled", "enabled" )
               
           }
           
           
           
           if( getUseAutoForward() ){	    	        	
		$( ".UseAutoForward" ).html( "<input type=checkbox checked=checked disabled=disabled readonly=readonly /> Automatisk g&aring til neste hull" );    		
	   }else{
		$( ".UseAutoForward" ).html( "<input type=checkbox                 disabled=disabled readonly=readonly /> Automatisk g&aring til neste hull" );    

           }	
          
          
          var lockTime = getLockTimeValue();
          
          $( ".lockTimeUp" ).html( "&Oslash;k tid for autol&aring;s til: " + ( lockTime +1 ) );    
          
          if( lockTime > 2 ){
             $( ".lockTimeDown" ).html( "Senk tid for autol&aring;s til: " + ( lockTime -1 ) );    
          }else{
             $( ".lockTimeDown" ).html( "Tid for autol&aring;s er satt til minimum: 2 " );    
          }

           
       if( isPersonLoggedIn() ){
       		$( ".changeUser" ).html( "Logg ut bruker" );    
       }else{
       		$( ".changeUser" ).html( "Logg inn" );    
       }
       
              
       
       if( getUseLiveScoring() ){
            //$( ".liveScoring" ).html( "Sl&aring; av direkteoppdateringer til www.stormkast.no" );    
            $( ".liveScoring" ).html( "<input type=checkbox checked=checked disabled=disabled readonly=readonly /> Direkteoppdateringer til www.stormkast.no" );    
            
            if( getAnonymousLiveScoring() ){
	    	  $( ".liveScoringAnonymous" ).html( "<input type=checkbox                 disabled=disabled readonly=readonly /> Send navn ved direkteoppdateringer" );    
	    }else{
	    	  $( ".liveScoringAnonymous" ).html( "<input type=checkbox checked=checked disabled=disabled readonly=readonly /> Send navn ved direkteoppdateringer" );    
            }
       }else{
          ///  $( ".liveScoring" ).html( "Sl&aring; p&aring; direkteoppdateringer til www.stormkast.no" );    
          
            $( ".liveScoring" ).html( "<input type=checkbox disabled=disabled readonly=readonly /> Direkteoppdateringer til www.stormkast.no" );    
            $( ".liveScoringAnonymous" ).html( "" );    
       }
       
    
       
       
       var currentHole = getCurrentHole();
       
       
       $(".holeNavi").removeClass( "selectedDiv");
       $("#holeNavi_" + currentHole ).addClass( "selectedDiv");
       
       
       
       
       

       
       
       
       updateHoleValueVisuals();           
   }


function createViews(){  
   createSettingsDiv();
   createStartDiv();
  createEndDiv()
  for( ix = 1; ix <= 18; ix++ ){
      createHoleDiv( ix );
   }
   writeMainControls()
}
   
   

function getRoundDetailsRowTds( liveDataForHole ){
	var tds = 
		"<td>" + liveDataForHole.personName  + "</td>" +
		"<td>" + liveDataForHole.holeNum     + "</td>" +
		"<td>" + liveDataForHole.holeName    + "</td>" +
		"<td>" + liveDataForHole.holeValue   + "</td>" +
		"<td>" + (liveDataForHole.holeValue  - liveDataForHole.holePar )     + "</td>" +
		"<td>" + liveDataForHole.courseName  + "</td>" +
		"<td>" + liveDataForHole.lastUpdate  + "</td>" +
		"<td>" + liveDataForHole.comment     + "</td>" 
		;
		
		
   return tds;
}   



function getNewLiveScoreRows(){
 	var topRowId = getLastLiveScoreId();;


 	var postData = {
		action         : "getNewLiveScoreRows",
		topLiveScoreId : topRowId
	};


	var jqxhr = $.post("OnlineScoreCardServer.php", postData, function(data) {

//		alert("Data Loaded: " + data);

		try {
			var loginInfo = jQuery.parseJSON( data );

			if( loginInfo["status"] === "ok" ){

				//alert("Nytt baneoppsett lastet ned: " + loginInfo['courseName'] );
				//alert( "ok : " + loginInfo["statusMessage"] );


				if( loginInfo['numNewRows']  > 0 ){
					var html = "";
					
//					$( ".LiveTableRow" ).removeClass( "newLiveTableRow" );
					
					for( classId = 10; classId >= 1; classId-- ){
						$( ".newLiveTableRow_" + classId ).addClass( "tmpLiveTableRow" );
						$( ".newLiveTableRow_" + classId ).removeClass( "newLiveTableRow_" + classId );
						
						$( ".tmpLiveTableRow" ).addClass( "newLiveTableRow_" + (classId +1) );
						$( ".tmpLiveTableRow" ).removeClass( "tmpLiveTableRow" );
					}
					
					

					for( key in loginInfo['rows'] ){
					   var value = loginInfo['rows'][ key ];

					   html += "<tr class='LiveTableRow newLiveTableRow_1'>" +

									getRoundDetailsRowTds( loginInfo['rows'][ key ] ) + 
					           
					           "<td><a href='?liveScoring=a&action=roundDetails&roundId=" + loginInfo['rows'][ key ].roundId     + "'>Detaljer</a></td>" +
					           "</tr>";

						if( topRowId < loginInfo['rows'][ key ].id ){
							topRowId = loginInfo['rows'][ key ].id;
						}
						
						
						
						if( loginInfo['rows'][ key ].holeValue == 1 ){
							alert( "ACE !\n\n" + loginInfo['rows'][ key ].personName + " har rapportert en ACE pa hull " + loginInfo['rows'][ key ].holeNum + " (" + loginInfo['rows'][ key ].holeName  + ") pa " + loginInfo['rows'][ key ].courseName + "\n\n" );
						}				           
					}

					//html += "</table>";

					$( "#liveScorTableBody tr:first" ).before( html );

					setLastLiveScoreId( topRowId );
				}
			}else{
				alert( "Noe gjekk galt: " + loginInfo["statusMessage"] );
			}
		} catch(e) {
			alert( "Noe er feil med resultatet fra serveren: \n\nError:\n" + e + "\n\n" );
		}
	})
	.error(function() {
		alert("Feil ved tilkobling til serveren");
	});

 }



function showRoundDetails( roundIde ){
var postData = {
		action  : "getRoundDetails",
		roundId : roundIde
	};


	var jqxhr = $.post("OnlineScoreCardServer.php", postData, function(data) {

//		alert("Data Loaded: " + data);

		try {
			var loginInfo = jQuery.parseJSON( data );

			if( loginInfo["status"] === "ok" ){

				//alert("Nytt baneoppsett lastet ned: " + loginInfo['courseName'] );
				//alert( "ok : " + loginInfo["statusMessage"] );


				if( loginInfo['numNewRows']  > 0 ){
					var html = "";
					
//					$( ".LiveTableRow" ).removeClass( "newLiveTableRow" );
					
					for( classId = 10; classId >= 1; classId-- ){
						$( ".newLiveTableRow_" + classId ).addClass( "tmpLiveTableRow" );
						$( ".newLiveTableRow_" + classId ).removeClass( "newLiveTableRow_" + classId );
						
						$( ".tmpLiveTableRow" ).addClass( "newLiveTableRow_" + (classId +1) );
						$( ".tmpLiveTableRow" ).removeClass( "tmpLiveTableRow" );
					}
					
					

					for( key in loginInfo['rows'] ){
					   var value = loginInfo['rows'][ key ];


					   html += "<tr class='LiveTableRow '>" +
					           
					           getRoundDetailsRowTds( loginInfo['rows'][ key ] ) + 
					           
				           
//					           "<td><a href='?liveScoring=a&action=roundDetails&roundId=" + loginInfo['rows'][ key ].roundId     + "'>Detaljer</a></td>" +
					           "</tr>";


						
						
						if( loginInfo['rows'][ key ].holeValue == 1 ){
							alert( "ACE !\n\n" + loginInfo['rows'][ key ].personName + " har rapportert en ACE pa hull " + loginInfo['rows'][ key ].holeNum + " (" + loginInfo['rows'][ key ].holeName  + ") pa " + loginInfo['rows'][ key ].courseName + "\n\n" );
						}				           
					}

					//html += "</table>";

					$( "#liveScorTableBody tr:first" ).before( html );

				//	setLastLiveScoreId( topRowId );
				}
			}else{
				alert( "Noe gjekk galt: " + loginInfo["statusMessage"] );
			}
		} catch(e) {
			alert( "Noe er feil med resultatet fra serveren: \n\nError:\n" + e + "\n\n" );
		}
	})
	.error(function() {
		alert("Feil ved tilkobling til serveren");
	});

}


function getLast50LiveScoreRows(){
 	var topRowId = getLastLiveScoreId();;


 	var postData = {
		action         : "getLast50LiveScoreRows",
		topLiveScoreId : topRowId
	};


	var jqxhr = $.post("OnlineScoreCardServer.php", postData, function(data) {

//		alert("Data Loaded: " + data);

		try {
			var loginInfo = jQuery.parseJSON( data );

			if( loginInfo["status"] === "ok" ){

				//alert("Nytt baneoppsett lastet ned: " + loginInfo['courseName'] );
				//alert( "ok : " + loginInfo["statusMessage"] );


				if( loginInfo['numNewRows']  > 0 ){
					var html = "";
					
//					$( ".LiveTableRow" ).removeClass( "newLiveTableRow" );
					
					for( classId = 10; classId >= 1; classId-- ){
						$( ".newLiveTableRow_" + classId ).addClass( "tmpLiveTableRow" );
						$( ".newLiveTableRow_" + classId ).removeClass( "newLiveTableRow_" + classId );
						
						$( ".tmpLiveTableRow" ).addClass( "newLiveTableRow_" + (classId +1) );
						$( ".tmpLiveTableRow" ).removeClass( "tmpLiveTableRow" );
					}
					
					

					for( key in loginInfo['rows'] ){
					   var value = loginInfo['rows'][ key ];
					   
					   var tds = getRoundDetailsRowTds( value );

					   html += "<tr class='LiveTableRow '>" +				           
					           
					           tds + 

					           "<td><a href='?liveScoring=a&action=roundDetails&roundId=" + loginInfo['rows'][ key ].roundId     + "'>Detaljer</a></td>" +
					           "</tr>";

						if( topRowId < loginInfo['rows'][ key ].id ){
							topRowId = loginInfo['rows'][ key ].id;
						}
						
						
						
						if( loginInfo['rows'][ key ].holeValue == 1 ){
							alert( "ACE !\n\n" + loginInfo['rows'][ key ].personName + " har rapportert en ACE pa hull " + loginInfo['rows'][ key ].holeNum + " (" + loginInfo['rows'][ key ].holeName  + ") pa " + loginInfo['rows'][ key ].courseName + "\n\n" );
						}				           
					}

					//html += "</table>";

					$( "#liveScorTableBody tr:first" ).before( html );

					setLastLiveScoreId( topRowId );
				}
			}else{
				alert( "Noe gjekk galt: " + loginInfo["statusMessage"] );
			}
		} catch(e) {
			alert( "Noe er feil med resultatet fra serveren: \n\nError:\n" + e + "\n\n" );
		}
	})
	.error(function() {
		alert("Feil ved tilkobling til serveren");
	});

 }



function getLastLiveScoreId(  ){
   var value = $.Storage.get("LastLiveScoreId" );

   if( isVariableDefined( value ) == false ){
      return parseInt( 0 );
   }else{
      return parseInt( value );
   }
}
function setLastLiveScoreId( lastID ){
   $.Storage.set( "LastLiveScoreId" , "" + lastID );
}

   


function isCourseInfoLoadedAndComplete(){   
	var result = true;
	
	for( ix = 1; ix <= 18; ix++ ){
		if( isSetHolePar( ix) === false ){
			result = false;
		}
	}        

	for( ix = 1; ix <= 18; ix++ ){
		if( isSetHoleName( ix ) === false ){
			result = false;
		}
	}    

	if( isSetCourseName( ) === false ){
		result = false;
	}
	if( isSetCourseId() === false ){
	      	result = false;
      	}

	return result;	
}
   
function createDefaultData(){   
	if( isCourseInfoLoadedAndComplete() === false ){
		updateCourseData( getDefaultCourseData() );
	}	
	
	if( isSetRoundId() == false ){
		var roundId = generateRoundId();
		setRoundId( roundId );
	}
}
   
   
function getDefaultCourseData(){
	var courseData = new Object();

	courseData['courseName'] = "Standard bane";
	courseData['courseId'] = -1;

	courseData['courseHolePar'] = new Array();
	for( ix = 0; ix < 18; ix++ ){     
		courseData['courseHolePar'][ix] = 3;
	}              
	
	courseData['courseHoleName'] = new Array();
	for( ix = 0; ix < 18; ix++ ){
		courseData['courseHoleName'][ix] = "Hull nr " + (ix +1);
	}    

	return courseData;
}
   
   
function updateCourseData( courseData ){
	setCourseName( courseData['courseName'] );      
      	setCourseId( courseData['courseId'] );

     for( ix = 0; ix < 18; ix++ ){     
            setHolePar( ix +1, courseData['courseHolePar'][ix] );
      }              
     for( ix = 0; ix < 18; ix++ ){
          setHoleName( ix +1, courseData['courseHoleName'][ix] );
      }    
      
	updateHoleNameVisuals();
	updateHoleParValueVisuals();
}


function removeRoundData(){   
   for( ix = 1; ix <= 18; ix++ ){
             $.Storage.remove("holeValue_" + ix);
   }  
   
   
   $(".value").removeClass( "selectedValue" );
   
   setRoundId( -1 );
}

function removeAllStoredData(){
    $.Storage.remove("showDetails");
    $.Storage.remove("currentHole");
    $.Storage.remove("editable");
    
    $.Storage.remove("personName");
    $.Storage.remove("personId");


    removeAllStoredCourseData();
    
    
    removeRoundData();
}
   
function removeAllStoredCourseData(){
    $.Storage.remove("courseName");
    $.Storage.remove("courseId");


    for( ix = 1; ix <= 18; ix++ ){
          $.Storage.remove("holeName_" + ix);
   }  
   for( ix = 1; ix <= 18; ix++ ){
             $.Storage.remove("holePar_" + ix);
   }  
}



function setShowDetails( newShowDetails ){
	if( newShowDetails  ){
             $.Storage.set("showDetails", "true");             
             $(".hider").html("<input type=checkbox checked=checked disabled=disabled readonly=readonly /> Vis detaljert score under runden");;             
        }else{
             $.Storage.set("showDetails", "false");
             $(".hider").html("<input type=checkbox                 disabled=disabled readonly=readonly /> Vis detaljert score under runden");;             
        }
        updateHoleValueVisuals();
}


function isShowDetails(){
   var value = $.Storage.get("showDetails");
   if( value === "true" ){              
      return true;
   }else{
      return false;
   }
}


function getStormkastScoreString(){
   var totalDetails = "";
   
   
   for( ix = 1; ix <= 18; ix++ ){
      if( isSetHoleValue( ix ) ){
   	   var val = getHoleValue( ix, 3 );
   	
   	   totalDetails = totalDetails + "" + val;
      }else{
            totalDetails = totalDetails + "" + "x";
      }
   }
   

   return totalDetails;
}



/*
function updateDetails(){
   var totalDetails = "";
   
   
   for( ix = 1; ix <= 18; ix++ ){
      if( isSetHoleValue( ix ) ){
   	   var val = getHoleValue( ix, 3 );
   	
   	   totalDetails = totalDetails + " - " + val;
      }else{
            totalDetails = totalDetails + " - " + "x";
      }
   }
   

//   $( ".total" ).html( "Tot: <b>" + getTotalScore() + "</b> " + totalDetails );
}
*/

function isRoundComplete(){
   var result = true;
      
   for( ix = 1; ix <= 18; ix++ ){
      if( isSetHoleValue( ix ) == false ){
         result = false;
      }
   }
   

   return result;
}


function getTotalScore(){
   var totalValue = 0;
   
   
   for( ix = 1; ix <= 18; ix++ ){
      if( isSetHoleValue( ix ) ){
         var val = getHoleValue( ix, 3 );
   
         totalValue = totalValue + val;      
      }
   }
   

   return totalValue;;
}


function getPlayedPar(){
   var totalValue = 0;
   
   
   for( ix = 1; ix <= 18; ix++ ){
      if( isSetHoleValue( ix ) ){
         var val = getHolePar( ix );
   
         totalValue = totalValue + val;      
      }
   }
   

   return totalValue;;
}

function getTotalPar(){
   var totalValue = 0;
   
   
   for( ix = 1; ix <= 18; ix++ ){
      var val = getHolePar( ix );
   
      totalValue = totalValue + val;      
   }
   

   return totalValue;;
}


function setCurrentHole( holeNum ){
   $.Storage.set( "currentHole" , "" + holeNum);
}
function getCurrentHole(){
   var value = $.Storage.get("currentHole" );
   
   if( isVariableDefined( value ) == false ){   
      return parseInt( 0 );
   }else{
      return parseInt( value );
   }
}

function isVariableDefined( value ){
	if( (value === null) || (typeof value === "undefined") ){   
	//if( typeof value === "undefined" ){   
	      return false;
	}else{
	      return true;
   	}
}

function isSetHoleName( holeNum ){
   var value = $.Storage.get("holeName_" + holeNum  );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getHoleName( holeNum ){
   var value = $.Storage.get("holeName_" + holeNum  );
   
   if( isVariableDefined( value ) == false ){   
      return "Hull " + holeNum;
   }else{
      return value;
   }
}
function setHoleName( holeNum, holeName ){
   $.Storage.set( "holeName_" + holeNum, holeName );
}


function isCurrentRoundExported(){
   var currentRoundId = getRoundId();   
   var value = $.Storage.get("currentRoundExported_id" );
   
   if( isVariableDefined( value ) == false ){   
          return false;
   }else{
          if( value === currentRoundId ){
          	return true;
          }else{
                return false;
          }
    }     
}
function markCurrentRoundAsExported(){
   var currentRoundId = getRoundId();
   var d=new Date();
   $.Storage.set( "currentRoundExported_id", currentRoundId );
   $.Storage.set( "currentRoundExported_time" , "" + d );
}

function getCurrentRoundExportedTime(){
   if( isCurrentRoundExported() ){        
	   var valueTime = $.Storage.get("currentRoundExported_time" );

	   if( isVariableDefined( valueTime ) == false ){   
	      return "ikke eksportert";
	   }else{
	      return valueTime;
	   }
    }else{
       return "ikke eksportert 2";
    }
}



function isSetHolePar( holeNum ){
   var value = $.Storage.get("holePar_" + holeNum  );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getHolePar( holeNum ){
   var value = $.Storage.get("holePar_" + holeNum  );
   
   if( isVariableDefined( value ) == false ){   
      return parseInt( 3 );
   }else{
      return parseInt( value );
   }
}
function setHolePar( holeNum, holePar ){
   $.Storage.set( "holePar_" + holeNum, "" + holePar);
}


function isSetSelectedCourseId(){
   var value = $.Storage.get( "SelectedCourseId" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getSelectedCourseId(){
   var value = $.Storage.get( "SelectedCourseId" );
   
   if( isVariableDefined( value ) == false ){   
      return parseInt( 0 );
   }else{
      return parseInt( value );
   }
}
function setSelectedCourseId( selectedCourseId ){
   $.Storage.set( "SelectedCourseId", "" + selectedCourseId );
}



function isSetServerCourseList(){
   var value = $.Storage.get( "ServerCourseList" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getServerCourseList(){
   var value = $.Storage.get( "ServerCourseList" );
   
   if( isVariableDefined( value ) == false ){   
      return "";
   }else{
      return value;
   }
}
function setServerCourseList( serverCourseList){
   $.Storage.set( "ServerCourseList", "" + serverCourseList );
}




function isSetUseLiveScoring( ){
   var value = $.Storage.get("liveEnabled" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getUseLiveScoring(  ){
   var value = $.Storage.get("liveEnabled"  );
   
   if( isVariableDefined( value ) == false ){   
      return false; // false is default
   }else{
      if( value === "true" ){              
         return true;
      }else{
         return false;
      }
   }
}
function setUseLiveScoring( UseLiveScoring ){
   if( UseLiveScoring ){  
   	$.Storage.set( "liveEnabled", "true" );
   }else{
   	$.Storage.set( "liveEnabled", "false");
   }
}


function isSetUseAutoForward( ){
   var value = $.Storage.get("autoForwardEnabled" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getUseAutoForward(  ){
   var value = $.Storage.get("autoForwardEnabled"  );
   
   if( isVariableDefined( value ) == false ){   
      return false; // false is default
   }else{
      if( value === "true" ){              
         return true;
      }else{
         return false;
      }
   }
}
function setUseAutoForward( UseAutoForward ){
   if( UseAutoForward ){  
   	$.Storage.set( "autoForwardEnabled", "true" );
   }else{
   	$.Storage.set( "autoForwardEnabled", "false");
   }
}


function isSetAnonymousLiveScoring( ){
   var value = $.Storage.get("liveIsAnonymous" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getAnonymousLiveScoring(  ){
   var value = $.Storage.get("liveIsAnonymous"  );
   
   if( isVariableDefined( value ) == false ){   
      return true; // true (=anonymous) is default
   }else{
      if( value === "true" ){              
         return true;
      }else{
         return false;
      }
   }
}
function setAnonymousLiveScoring( anonymousLiveScoring ){
   if( anonymousLiveScoring ){  
   	$.Storage.set( "liveIsAnonymous", "true" );
   }else{
   	$.Storage.set( "liveIsAnonymous", "false");
   }   
}


function isSetUseLiveScoringWarningShowed( ){
   var value = $.Storage.get("liveWarningShowed" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getUseLiveScoringWarningShowed(  ){
   var value = $.Storage.get("liveWarningShowed"  );
   
   if( isVariableDefined( value ) == false ){   
      return false; // false is default
   }else{
      if( value === "true" ){              
         return true;
      }else{
         return false;
      }
   }
}
function setUseLiveScoringWarningShowed( UseLiveScoringWarningShowed ){
   if( UseLiveScoringWarningShowed ){  
   	$.Storage.set( "liveWarningShowed", "true" );
   }else{
   	$.Storage.set( "liveWarningShowed", "false");
   }
}


function isSetHoleValue(holeNum ){
   var value = $.Storage.get("holeValue_" + holeNum );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getHoleValue(holeNum ){
   var value = $.Storage.get("holeValue_" + holeNum );
   
   if( isVariableDefined( value ) == false ){   
      return getHolePar( holeNum );
   }else{
      return parseInt( value );
   }
}
function setHoleValue( holeNum, holeValue ){
   $.Storage.set( "holeValue_" + holeNum, "" + holeValue);
}
function removeHoleValue(holeNum ){
   $.Storage.remove("holeValue_" + holeNum );
}

function isSetCourseName(){
   var value = $.Storage.get("courseName" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getCourseName(){
   var value = $.Storage.get("courseName" );
   
   if( isVariableDefined( value ) == false ){   
      return "Bane";
   }else{
      return value;
   }
}
function setCourseName( courseName ){
   $.Storage.set( "courseName", courseName );
}


function isSetCourseId(){
   var value = $.Storage.get("courseId" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getCourseId(){
   var value = $.Storage.get("courseId" );
   
   if( isVariableDefined( value ) == false ){   
      return -1;
   }else{
      return parseInt( value );
   }
}
function setCourseId( courseId ){
   $.Storage.set( "courseId", "" + courseId );
}


function isSetPersonName(){
   var value = $.Storage.get("personName" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getPersonName(){
   var value = $.Storage.get("personName" );
   
   if( isVariableDefined( value ) == false ){   
      return "Ikke innlogget";
   }else{
      return value;
   }
}
function setPersonName( personName ){
   $.Storage.set( "personName", personName );
}


function isSetPersonId(){
   var value = $.Storage.get("personId" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getPersonId(){
   var value = $.Storage.get("personId" );
   
   if( isVariableDefined( value ) == false ){   
      return -1;
   }else{
      return parseInt( value );
   }
}
function setPersonId( personId ){
   $.Storage.set( "personId", "" + personId );
}

function isPersonLoggedIn(){
	// simple ...
	if( getPersonId() >= 0 ){
		return true;
	}else{
		return false;
	}
}


function isSetRoundId(){
   var value = $.Storage.get("roundId" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getRoundId(){
   var value = $.Storage.get("roundId" );
   
   if( isVariableDefined( value ) == false ){   
      return -1;
   }else{
      return value;
   }
}
function setRoundId( roundId ){
   $.Storage.set( "roundId", "" + roundId );
}

function generateRoundId(){
// from resultFunctions;   value='314" . rand(1000,9999) . date("U") . "x' />

	var date = new Date();

	return "666" + 
	       ( 1000 + Math.floor(Math.random()*10000) ) +   // = rand( 1000, 9999 )
	       date.getTime() + 
	       "y";
}




function isSetLockTimeValue(){
   var value = $.Storage.get("LockTimeValue" );
   
   if( isVariableDefined( value ) == false ){   
      return false;
   }else{
      return true;
   }
}
function getLockTimeValue(){
   var value = $.Storage.get("LockTimeValue" );
   
   if( isVariableDefined( value ) == false ){   
      return 10;
   }else{
      return parseInt( value );
   }
}
function setLockTimeValue( LockTimeValue ){
   $.Storage.set( "LockTimeValue", "" + LockTimeValue );
}




function isEdit(){
   var value = $.Storage.get("editable");
   if( value === "true" ){              
      return true;
   }else{
      return false;
   }
}



function setEdit( newEdit ){
   if( newEdit ){
      $.Storage.set("editable", "true");
      
	$("*").removeClass("isLocked");
	$( ".edit" ).addClass("isLocked");

	$(".lock").removeClass( "lockSelected" );
	$(".edit").addClass( "editSelected" );            
   }else{        
	$.Storage.set("editable", "false");

	$("*").addClass("isLocked");	   	
	$( ".edit" ).removeClass("isLocked");
	$( ".edit" ).html("sdsdf");

	$(".edit").removeClass( "editSelected" );
	$(".lock").addClass( "lockSelected" );

   }
   update();
}


function hideAllHoleDivs(){
   //$(".holeDiv").css("display","none");
   $(".holeDiv").hide();
   //$(".holeDiv").slideUp();
   //$(".holeDiv").fadeOut();
}


function setHoleDivVisible( holeNum ){
   //$("#hole_div_" + holeNum).css("display","block");
   //$("#hole_div_" + holeNum).slideDown();
   //$("#hole_div_" + holeNum).fadeIn(3000);
   $("#hole_div_" + holeNum).show();
}


function createSettingsDiv(){
	document.write( "<div id='hole_div_" + -1 + "' class='holeDiv'> " );	
	
	document.write(
		"<table border=1 width=100% > " +
		"   <tr><td class='navi' >Innstillinger</td><td> " +
		"       <table border=0 width=100% > " +
		
		"       <tr><td class='headings '> Innstillinger</td></tr> " +
		"       </table> " +
		"   </td><td class='navi  next' data-holeNum='" + -1 + "'  >Hoved</td></tr> " +
		"</table> " +
		" " );
		
	
		
	document.write("<table border=1 width=100%>");

	
	document.write("<tr ><td class='menuItem lockTimeUp'  '></td></tr>");			
	document.write("<tr ><td class='menuItem lockTimeDown'  '></td></tr>");
	document.write("<tr ><td class='menuItem hider'  '></td></tr>");
	document.write("<tr ><td class='menuItem UseAutoForward'  '>xc</td></tr>");
	document.write("<tr ><td class='menuItem liveScoring'  '>xc</td></tr>");
	document.write("<tr ><td class='menuItem liveScoringAnonymous'  '>cx</td></tr>");
	
	
	
	
//	document.write("<tr ><td class='menuItem testClass2'  '>TEST 22</td></tr>");
	
	
	
	document.write("</table> ");
	
	document.write("</div>" );
}

function createStartDiv(){
	document.write( "<div id='hole_div_" + 0 + "' class='holeDiv'> " );	
	
	document.write(
		"<table border=1 width=100% > " +
		"   <tr><td class='navi  last' data-holeNum='" + 0 + "'  >Opsjoner</td><td> " +
		"       <table border=0 width=100% > " +
		
		"       <tr><td class='headings coursName'>" + getCourseName() + "</td></tr> " +
		"       <tr><td class='headings userName'>" + getPersonName() + "</td></tr> " +		
		"       </table> " +
		"   </td><td class='navi  next' data-holeNum='" + 0 + "'  >Neste</td></tr> " +
		"</table> " +
		" " );
		
	
		
	document.write("<table border=1 width=100%>");

	document.write("<tr ><td class='menuItem resetRound' >Start ny runde</td></tr>" );
	document.write("<tr ><td class='menuItem changeUser' >Logg inn</td></tr> " );
	document.write("<tr ><td class='menuItem courseList' >Velg bane: <select id='courseSelector'> </select> </td></tr> " );
//	document.write("<tr ><td class='menuItem loadDefaultCourse'  >Last standard bane</td></tr> " );
//	document.write("<tr ><td class='menuItem loadDefaultCourseServer'  >Last standard bane fra server</td></tr>");				
        document.write("<tr ><td class='menuItem loadServerCourseList' >Last baneliste fra server</td></tr>");				
		
	
	document.write("</table> ");
	
	document.write("</div>" );
}


function createEndDiv(){
    document.write( "<div id='hole_div_" + 19 + "' class='holeDiv'> " );
	
	document.write(
		"<table border=1 width=100% > " +
		"   <tr ><td class='navi last' data-holeNum='" + 19 + "'  >Forrige</td><td> " +
		"       <table border=0 width=100% > " +
		"       <tr><td class='navi totalScoreHeading' rowSpan=2 ></td>" + 
		"           <td class='headings coursName'>" + getCourseName() + "</td></tr> " +
		"       <tr><td class='headings userName'>" + getPersonName() + "</td></tr> " +		
//		"       <tr><td class='headings num totalScore'> </td></tr> " +		
//		"       <tr><td class='headings stormkastScoreString'></td></tr> " +		
		"       </table> " +
		"   </td><td class='navi'>Total</td></tr> " +
		"</table>");
		


	document.write("<table  border=1 width=100%> " );	
	document.write("<tr ><td class='menuItem num totalScore' >t</td></tr>" );
//	document.write("<tr ><td class='menuItem stormkastScoreString' >g</td></tr>" );	
	document.write("<tr ><td class='menuItem exportScore'  '>Eksporter score </td></tr>");
	document.write("</table> " );

	
	document.write(  "</div>" );
}


function createHoleDiv( holeNum ){
	document.write(

	"<div id='hole_div_" + holeNum + "' class='holeDiv'> " +

	"<table border=1 width=100% > " +
	"   <tr><td class='navi last' data-holeNum='" + holeNum + "'  >Forrige</td><td>" +
	"<table border=0 width=100%> " +
	"   <tr><td class='navi' rowSpan=2 >" + holeNum + " </td>" + 
	"       <td class='headings coursName'>" + getCourseName() + "</td></tr> " +
	"   <tr><td class='headings' id='holeName_" + holeNum + "'>" + holeNum + " not set " + holeNum + "</td></tr> " +
	"   </table>" +
	"</td><td class='navi next' data-holeNum='" + holeNum + "'  >Neste</td></tr> " +
	"</table> " +
	"        " +
	"<table border=1 width=100%>");


	document.write( "<tr >");
	for( i = 1; i <= 4; i++){
	    document.write("<td data-holeNum='" + holeNum + "'  data-holeValue='" + i + "' id='value_" + holeNum + "_" + i + "' class='value_" + holeNum + " value' >" + i + "</td>" );	
	}
	document.write("</tr> " );
	
	document.write( "<tr >");
	for( i = 5; i <= 8; i++){
	    document.write("<td data-holeNum='" + holeNum + "'  data-holeValue='" + i + "' id='value_" + holeNum + "_" + i + "' class='value_" + holeNum + " value' >" + i + "</td>" );	
	}
	document.write("</tr> " );
	
	document.write( "<tr >");
	for( i = 9; i <= 11; i++){
	    document.write("<td data-holeNum='" + holeNum + "'  data-holeValue='" + i + "' id='value_" + holeNum + "_" + i + "' class='value_" + holeNum + " value' >" + i + "</td>" );	
	}
	document.write("<td data-holeNum='" + holeNum + "'  data-holeValue='" + -1 + "' id='value_" + holeNum + "_" + -1 + "' class='value_" + holeNum + " valueReset' >Slett</td>" );	
	document.write("</tr> " );


	document.write("</tr> </table> " +
	" </div> " );
}


function updateHoleNameVisuals(){
	for( hole = 1; hole <= 18; hole++){		
		var holeName = getHoleName( hole );
		
		$("#holeName_" + hole).html( holeName );
	}
}

function updateHoleParValueVisuals(){
	for( hole = 1; hole <= 18; hole++){		
		var parValue = getHolePar( hole );
		
		$(".value_" + hole).removeClass( "parValue" );		
		$("#value_" + hole + "_" + parValue ).addClass( "parValue" );		
	}
}


function updateHoleValueVisuals(){
	for( hole = 1; hole <= 18; hole++){					
		$(".value_" + hole).removeClass( "selectedValue" );

		if( isSetHoleValue( hole )){		
			var holeValue = getHoleValue( hole );		
			$("#value_" + hole + "_" + holeValue ).addClass( "selectedValue" );		

			if( isShowDetails() || (getCurrentHole() == 19) ){			
				$( "#holeNavi_" + hole + "_value" ).html( holeValue );
			}else{
				$( "#holeNavi_" + hole + "_value" ).html( "" );
			}
		}else{
			if( isShowDetails() || (getCurrentHole() == 19) ){
				$( "#holeNavi_" + hole + "_value" ).html( "x" );
			}
			else{
				$( "#holeNavi_" + hole + "_value" ).html( "" );
			}
		}
		
		
		if( isShowDetails() || isRoundComplete() || (getCurrentHole() == 19) ){
			$( "#holeNavi_" + 19 + "_value" ).html( "<b>" + getTotalScore() + "</b>" );
		}
		else{
			$( "#holeNavi_" + 19 + "_value" ).html( "" );
		}
	}
}


function writeMainControls(){

	document.write(" " +
	"<table border=1 width=100%> " +
	"   <tr class=buttons><td class='edit selected'>&Aring;pne</td><td class=lock>L&aring;s</td></tr> " +
	"</table> " );

/*
document.write(" " +
	"<table class=tableTotal border=1 width=100%> " +
	"   <tr><td class=total>Total: 51</td></tr> " );
		"</table> " );
*/
	

	
	document.write("<table border=1 width=100%> <tr>" );
	
	document.write("<td rowspan=2 class='holeNavi' id='holeNavi_" + -1 + "'  data-holeNum='" + -1 + "'  >Opsjoner</td>" );
	document.write("<td rowspan=2 class='holeNavi' id='holeNavi_" + 0 + "'  data-holeNum='" + 0 + "'  >Hoved</td>" );
	
	
	for( hole = 1; hole <= 18; hole++){					
		document.write("<td class='holeNavi' id='holeNavi_" + hole + "'  data-holeNum='" + hole + "'  >" + hole + "</td>" );
/*	
		if( isShowDetails() ){
			document.write("<td class='holeNavi' id='holeNavi_" + hole + "'  data-holeNum='" + hole + "'  >" + hole + " - x</td>" );
		}else{
			document.write("<td class='holeNavi' id='holeNavi_" + hole + "'  data-holeNum='" + hole + "'  >" + hole + "</td>" );
		}
*/		
	}
	document.write("<td rowspan=2 class='' id='holeNavi_" + 19 + "_value'  data-holeNum='" + 19 + "'  ></td>" );
	document.write("<td rowspan=2 class='holeNavi' id='holeNavi_" + 19 + "'  data-holeNum='" + 19 + "'  >Total</td>" );


	document.write("</tr>" );
	
	
	document.write("<tr>" );
	for( hole = 1; hole <= 18; hole++){					
		document.write("<td class='holeNavi holeNaviValue' id='holeNavi_" + hole + "_value'  data-holeNum='" + hole + "' ></td>");
	}
//	document.write("<td class='holeNavi holeNaviValue' id='holeNavi_" + 19 + "_value'  data-holeNum='" + 19 + "'  ></td>" );
	
	
	document.write("</tr></table>" );


	updateHoleValueVisuals();
	
/*	
	document.write("<tr>" );
	for( hole = 1; hole <= 18; hole++){					
		if( isShowDetails() ){
			document.write("<td class='holeNavi' id='holeNavi_" + hole + "_value'  data-holeNum='" + hole + "' >x</td>");
		}else{
			document.write("<td class='holeNavi' id='holeNavi_" + hole + "_value'  data-holeNum='" + hole + "' ></td>");
			}
	}
	
		if( isShowDetails() ){
			document.write("<td class='holeNavi' id='holeNavi_" + 19 + "'  data-holeNum='" + 19 + "_value'  ><b>" + getTotalScore() + "</b></td>" );
		}else{
			document.write("<td class='holeNavi' id='holeNavi_" + 19 + "'  data-holeNum='" + 19 + "_value'  ></td>" );
	}
	
	document.write("</tr></table>" );
*/


/*
	document.write(
		"<table border=1 width=100%> " +
		"   <tr><td class=testClass>test  </td></tr> " +
		"   <tr><td class=testClass2>test2  </td></tr> " +
		"</table> " 
	);
*/	
}

