$(document).ready(function() {
		// JSON URL
		var jsonURL = "https://www.bipm.org/SntpV3/servlet/SNTPServlet";
        var inlineDataUrl = $('.clock').data('clock-url');
        if(inlineDataUrl){
            jsonURL = inlineDataUrl;
        }

		// Create a newDate() object
		var UtcDate = new Date();

		// BIPM UTC Date

		var BIPM_UTC_Seconds;
		var BIPM_UTC_Hour;
		var BIPM_UTC_Minutes;
		var BIPM_UTC_Ms;
		var IsConnected = "false";
		var first = "false";

		// Affichage local
		var hours;
		var minutes;
		var seconds;
		var millisec;

		// Timelaps
		var timelaps = 0;
		var ms;

		function RandomString(length) {

			var str = '';
			for ( ; str.length < length; str += Math.random().toString(36).substr(2) );
			return str.substr(0, length);
		}



		setInterval( function() {
						if ( IsConnected == "true") {
								var h = parseInt(hours);
								var m = parseInt(minutes);
								var s = parseInt(seconds);

									if ( millisec > 0 && first == "true") {

										 millisec += timelaps/2;
										 ms = Math.floor(millisec/100);
										 // alert( "millsec" + millisec + " math.fllor: " + Math.floor(millisec/100) + " timelaps: " + timelaps/2);
										 first = "false";

										} else{

											++ms;
											// Mise à jour de l'heure UTC
											if ( ms == 10) { ms = 0;s++; }
											if ( s == 60 ) { s = 0; m++; }
											if ( m == 60 ) { m = 0; h++; }
											if ( h == 24 ) h = 0;
											// Next day
											if ( h == 0 && m == 0 && s == 0 ) GetUTC();
											hours   = h;
											minutes = m;
											seconds = s;
											millisec = ms;
									}
						} else {
							// local
							hours = new Date().getHours();
							minutes = new Date().getMinutes();
							seconds = new Date().getSeconds();
							millisec = Math.floor(new Date().getMilliseconds()/100);

						}

						// Add a leading zero
						$("#hours").html(( hours < 10 ? "0" : "" ) + hours);
						$("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
						$("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);

			} , 100);


		function GetUTC() {
					// Date emission
					var date_send = new Date();
					var languageParam ='US';
					if( Liferay.ThemeDisplay.getLanguageId() != 'en_US'){
						languageParam ='FR';
					}
					var form_data = {
						username: "BIPM_UTC",
						password: RandomString(32),
						locale:languageParam
					};
					//alert("Waiting for BIPM/UTC Server Response... ");
					 $("#ReturnString").css("color","#1E1182");
					 $('.clock-origin').html('LOCAL');

					 $("#ReturnString").hide();

					$.ajax({
						type: "GET",
						url: jsonURL ,
						dataType: "json",//, //set to JSON
						mimeType: 'application/json; charset=ISO-8859-1',
						data: form_data,
						// data: form_data,
						error: function(data) {
									IsConnected = "false";
							  		$("#ReturnString").html("Error while getting Time from BIPM/UTC clock, use local clock instead:" +JSON.stringify(data));
									$("#ReturnString").css("color","#B22222");
                            		$("#ReturnString").show();
									$('#clock-date').html(date_send.toDateString());

						},
						success: function(data) {

									$("#ReturnString").html('');
                            		$('.clock-origin').html('UTC')

									IsConnected = "true";
									first = "true";
									var dateLab = new Date();
									var date_recv = new Date();

									dateLab.setDate(data["BIPM_UTC_Day"]);
									dateLab.setMonth(data["BIPM_UTC_Month"]);
									dateLab.setYear(data["BIPM_UTC_Year"]);


									// Output the day, date, month and year
									$('#clock-date').html( data["BIPM_UTC_Date"] );

									// Get the HH: MM SS MDS from JSON object
									BIPM_UTC_Seconds = data["BIPM_UTC_Seconds"];
									BIPM_UTC_Hour    = data["BIPM_UTC_Hour"];
									BIPM_UTC_Minutes = data["BIPM_UTC_Minutes"];
									BIPM_UTC_Ms		 = data["BIPM_UTC_Ms"];

									UtcDate = new Date();
									UtcDate.setHours(BIPM_UTC_Hour);
									UtcDate.setMinutes(BIPM_UTC_Minutes);
									UtcDate.setSeconds(BIPM_UTC_Seconds);

									hours   = UtcDate.getHours();
									minutes = UtcDate.getMinutes();
									seconds = UtcDate.getSeconds();
									millisec = parseInt(BIPM_UTC_Ms);

									// Add a leading zero to the hours value
									$("#hours").html(( hours < 10 ? "0" : "" ) + hours);
									$("#min").html(( minutes < 10 ? "0" : "" ) + minutes);
									$("#sec").html(( seconds < 10 ? "0" : "" ) + seconds);

									timelaps = date_recv.getTime() - date_send.getTime();
									delay = timelaps/2000;
									$('#clock-estimated-delay').html(delay.toFixed(2) );
						}

					})

			}

		GetUTC();

		setInterval(GetUTC,10000);

}



);

