/**
 * Konstruktor obiekt zegara aukcji.
 * 
 * @param started
 * @param duration
 */

//var serverDifference = 0;

function Clock( started, duration, messageLessThanMinute)
{	
	//this.lessThanMinute = messageLessThanMinute;
	this.clockTimer = null;
	this.synchronizeTimer = null;
	this.duration = duration;
	this.startedAt = started;
	var now = new Date();
	this.lastTime = null;	
	this.serverDifference = 0;
	this.synchronize();
}

Clock.prototype.synchronize = function()
{	

	var before = new Date();
	var beforeTime = before.getTime();
	
	$.get('/serverTime.php?sid=' + before.getTime(),{}, function(data){
		var response = new Date();
		var responseTime = response.getTime();				
		var serverTime = data;
		//if ((responseTime - beforeTime)<1000) {
			clock.serverDifference = serverTime - beforeTime + (responseTime - beforeTime);			
			this.clockTimer = window.setInterval( function () { clockInstance.tick(); }, 1000);
		//} else {
			//clock.synchronize();	
		//};
	});		
	
}

Clock.prototype.tick = function()  
{
	var now = new Date();		
 
	this.lastTime = now.getTime() + this.serverDifference;
	//var left = Math.floor( parseInt(this.startedAt) + this.duration - Math.floor(this.lastTime / 1000));
	var left = Math.floor(parseInt(this.startedAt) + this.duration - Math.floor(this.lastTime / 1000));
	
	if( left <= 0)
	{
		$('.clockView').html( '');
		//window.setTimeout( function () { clockInstance.tick(); }, 1000);	
		$('.priceLink').hide();
		$('.priceLabel').show();
		return;
	}	
	
//	if ((left < 60000) && (this.lessThanMinute<>null)) {
//		$('#clockView').html(  this.lessThanMinute);
//	} else {
	    var sLeft = '';
	    var days = Math.floor( left / (24 * 3600));
	    if( days > 0) sLeft += days + 'D';
	    var hours = Math.floor( (left % (3600 * 24)) / 3600);
	    var minutes = Math.floor( (left % 3600)/60);
	    var seconds = left % 60;
	    sLeft += ' ' + hours + 'h ' + minutes + 'm ' + seconds + 's';
		$('.clockView').html(  sLeft);
//	}		
    //window.setTimeout( function () { clockInstance.tick(); }, 1000);

}

Clock.prototype.start = function()
{
	if( this.clockTimer != null) return; //clock already running
	clockInstance = this;
}

Clock.prototype.stop = function()
{
	clockInstance = this;
//	window.clearInterval( this.clockTimer);
//	this.clockTimer = null;
//	window.clearInterval( this.synchronizeTimer );
//	this.synchronizeTimer = null;
	window.clearInterval( this.clockTimer);
	this.clockTimer = null;
	window.clearInterval( this.synchronizeTimer );
	this.synchronizeTimer = null;

}

function formatDate( date)
{
	var formatted = '' + date.getFullYear() + '-' + (date.getMonth() <= 9 ? '0':'') + (date.getMonth() + 1) + '-' + (date.getDate() <= 9 ? '0':'') + date.getDate() 
		+ ' ' + (date.getHours() <= 9 ? '0':'') + date.getHours() + ':' + (date.getMinutes() <= 9 ? '0':'') + date.getMinutes();
	return formatted;
}

var currentQuery = null;

/**
 * Permanentne sprawdzanie statusu, co sekunde 
 * @param url - adres docelowy
 * @param id - identyfikator licytacji - samochod lub aukcja zaleznie od wywolania
 * @param time - ostatni czas sprawdzenia
 * @param callback - funkcja wolana po sprawdzeniu
 */
function statusChecker( url, id, time, callback, stop)
{
	var now = new Date();
	//var urlAjax = url + '?sid=' + now.getTime();
	var urlAjax = url;
	//now.setTime(now.getTime() + this.serverDifference);

	//alert(url);
	
	currentQuery = $.ajax({
		url : urlAjax,
		timeout: 60000,
		dataType : 'json',
		cache : false,
		async: true,
		data: { id: id, time: time, ts: now.getTime()},
		success:  
	        function( data, textStatus){
				//alert(data['status']);
				currentQuery = null;
			
	        	if( textStatus == 'success' &&  data['status'] == 'ok' )
	        	{	        		
	        		if( callback != null) callback( data);	        
	        		if( data['auction_car'] != null && (	        				
	        					data['auction_car']['status'] == 'finished' 
        						|| data['auction_car']['status'] == 'withdrawn'
	        					|| data['auction_car']['status'] == 'not_approved'
        						|| data['auction_car']['status'] == 'approved'
    							|| data['auction_car']['status'] == 'sold'
								|| data['auction_car']['status'] == 'not_paid'))
	        		{
	        			return;
	        		}
	        		
	        		newTime = data['time'];
	        		//var f = function() { 
	        		//	statusChecker( url, id, newTime, callback);
	        		//};
	        		//if (stop!=1) window.setTimeout( f, 1000);
	        		if (stop!=1) statusChecker( url, id, newTime, callback);
	        	}
	        	else
	        	{
		        	$('#status').html( data['status']);
		        	//var f = function() { statusChecker( url, id, time, callback);}
		        	//if (stop!=1) window.setTimeout( f, 1000);
		        	if (stop!=1) statusChecker( url, id, time, callback);
	        	}
	        },
		error:
	        function( data, textStatus) {
	        	//alert(textStatus);
	        	currentQuery = null;
	        	//var f =function() { statusChecker( url, id, time, callback);};
	        	//if (stop!=1) window.setTimeout( f, 1000);
	        	if (stop!=1) statusChecker( url, id, time, callback);
	        }
	});
}

function makeBid( url, carId, bid, callback, uid, price)
{
	if( uid != null)
	{
		var data = { id: carId, bid: bid, uid: uid, ts: new Date().getTime(), price: price };
	}
	else
	{
		var data = { id: carId, bid: bid, ts: new Date().getTime(), price: price}
	}
	$.getJSON(
		url, data, function( data, textStatus) {
    		if( callback != null) callback( data);
        }
	);
}

function finalCall( url, carId, finalCall, callback)
{
	var data = { car_id: carId, final_call: finalCall, ts: new Date().getTime()}
	$.getJSON(
		url, data, function( data, textStatus) {
			if( typeof callback == 'function') callback( data);
	    }
	);
	
}

function buyNow( url, carId, callback)
{
	var data = { id: carId, ts: new Date().getTime()}
	$.getJSON(
		url, data, function( data, textStatus) {
			if( callback != null) callback( data);
	    }
	);
}


var comet = {
	    connection   : false,
	    iframediv    : false,
	    callback     : false,
	 
	    initialize: function( url, carId, callback) 
	    {
			var targetUrl = url + "?id=" + carId;
			comet.callback = callback;
			if (navigator.appVersion.indexOf("MSIE") != -1) 
			{
		 
		        // For IE browsers
		        comet.connection = new ActiveXObject("htmlfile");
		        comet.connection.open();
		        comet.connection.write("<html>");
		        comet.connection.write("<script>document.domain = '"+document.domain+"'");
		        comet.connection.write("</html>");
		        comet.connection.close();
		        comet.iframediv = comet.connection.createElement("div");
		        comet.connection.appendChild(comet.iframediv);
		        comet.connection.parentWindow.comet = comet;
		        comet.iframediv.innerHTML = "<iframe id='comet_iframe' src='" + targetUrl + "'></iframe>";
		 
			} 
			else if (navigator.appVersion.indexOf("KHTML") != -1) 
			{
	 
				// for KHTML browsers
				comet.connection = document.createElement('iframe');
				comet.connection.setAttribute('id',   'comet_iframe');
				comet.connection.setAttribute('src',  targetUrl);
				with( comet.connection.style) {
					position   = "absolute";
					left       = top   = "-100px";
					height     = width = "1px";
					visibility = "hidden";
				}
				document.body.appendChild(comet.connection);
			} 
			else 
			{
				// For other browser (Firefox...)
				comet.connection = document.createElement('iframe');
				comet.connection.setAttribute('id',     'comet_iframe');
				with (comet.connection.style) {
					left       = top   = "-100px";
					height     = width = "1px";
					visibility = "hidden";
					display    = 'none';
				}
				comet.iframediv = document.createElement('iframe');
				comet.iframediv.setAttribute('src', targetUrl);
				comet.connection.appendChild(comet.iframediv);
				document.body.appendChild( comet.connection);
			}
	    },
	 
	    // this function will be called from destination url
	    process: function( data) {
	    	comet.callback( data);
	    },
	 
	    onUnload: function() {
	    	if (comet.connection) {
	    		comet.connection = false; // release the iframe to prevent
										// problems with IE when reloading the
										// page
	    	}
	    }
	}


function formatNumber( nStr, digits)
{
	if( typeof digits == 'undefined')
	{
		digits = 0;
	}
	nStr += '';
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	return x1 + x2.substring( 0, digits);
}

function displayMessage( message)
{
	$('#system_message').find('.ui-dialog-content').html( message);
	$('#system_message').show();
//	window.setTimeout( function() { $('#system_message:visible').fadeOut('slow');}, 3000);
}

function closeMessage()
{
	$('#system_message:visible').fadeOut('fast');
}

Array.prototype.inArray = function (value,caseSensitive)
//Returns true if the passed value is found in the
//array. Returns false if it is not.
{
	var i;
	for (i=0; i < this.length; i++) 
	{
		//use === to check for Matches. ie., identical (===),
		if(caseSensitive){ //performs match even the string is case sensitive
			if (this[i].toLowerCase() == value.toLowerCase()) 
			{
				return true;
			}
		}
		else
		{
			if (this[i] == value) 
			{
				return true;
			}
		}
	}
	return false;
};

function DoNav(theUrl)
{
	document.location.href = theUrl;
}

