/***************************************************
* Class: Auction, Auctions, System
* Created: 2008-12-14
* Modified: 2009-02-16
* Author: Raido Orumets
*
* Copyright © PixmaSoft OÜ
* info@pixmasoft.ee
* http://www.pixmasoft.ee
***************************************************/

var LOCAL_CICLE = 1000;
//var REMOTE_CICLE = 1100; //3100
var SYNC_CICLE = 2100; //3100
var CHECKING_TIME = 30000;
var REQUEST_TIMEOUT = 8000;
var LOCAL_TIMEOUT = 3600000;
var SPLASH_TIMEOUT = 900000; //15 min
var AUCTION_INTERVAL_END = 10000; //11000;
var AUCTION_INTERVAL_END_SOUND = 10000;
var AUCTION_INTERVAL_MIDDLE = 59000; //60000;

var AUCTION_PRICE = new Array();
var CLIENT_DATE = new Date();
var CURRENT_DATE = new Date();
var FLASH_TEMP_DATE = new Date();
//var SYSTEM_DATE = "2008-12-14 12:44:35";
//var USERNAME = "test";
var DEBUG = false;
var DEBUG_AUCTION = Array();

var ABORT_ALL = false;

var ALLOW_AUTO_BIDDER = true;

function Auction(id, type){

	var id;
	var time_interval;
	var interval;
	var date_start;
	var date_end;
	var date_close;
	var price;
	var last_bidder;
	var is_top;			//true, false
	var is_24h;			//true, false
	var is_auto_bidder;	//true, false
	var status;			//coming, running, paused, checking, sold

	{
		this.id = id;
		this.type = type
		this.price = 0;
		this.last_bidder = false;
		this.is_top = false;
		this.is_24h = false;
		this.is_auto_bidder = false;
		this.status = false;
		this.view = 'auction';
		this.interval = new Date();
		Auctions.auctions[this.id] = this;

		this.dom_auctionItem = $("#auctionItem" + this.id + " ." + type + "_bid_button").hide();
		this.dom_timeTag = $("#timeTag" + this.id);
	}

	//------------------------------------------------------
	// Setters
	//------------------------------------------------------

	this.setId = function(id){
		this.id = id;
	}

	this.setDateStart = function(date_start){
		this.date_start = createDateFromSQLString(date_start);
	}

	this.setDateEnd = function(date_end){
		this.date_end = createDateFromSQLString(date_end);
	}

	this.setDateClose = function(date_close){
		this.date_close = createDateFromSQLString(date_close);
	}

	this.setPrice = function(price){
		this.price = price;
	}

	this.setLastBidder = function(last_bidder){
		this.last_bidder = last_bidder;
	}

	this.setIsTop = function(is_top){
		this.is_top = is_top;
	}

	this.setIs24h = function(is_24h){
		this.is_24h = is_24h;
	}

	this.setIsAutoBidder = function(is_auto_bidder){
		this.is_auto_bidder = is_auto_bidder;
	}

	this.setTimeInterval = function(time_interval){
		this.time_interval = time_interval;
	}

	this.setStatus = function(status){
		this.status = status;
	}

	this.setView = function(view){
		this.view = view;
	}

	//------------------------------------------------------
	// Getters
	//------------------------------------------------------

	this.getId = function(){
		return this.id;
	}

	this.getStatus = function(){
		return this.status;
	}

	this.getLastBidder = function() {
		if(this.ifManyLastBidders()){
			var rows = this.last_bidder.split(";");
			var cols = rows[0].split("=");
			return cols[0];
		} else {
			return this.last_bidder;
		}
	}

	this.getLastBidders = function() {
		if(!this.ifManyLastBidders()) return;
		var rows = this.last_bidder.split(";");
		var html = '<table width="100%" border="0" cellspacing="0" cellpadding="2">\n';
		var table_row;
		for (var i = 0; i < (rows.length - 1); i++) {
			var cols = rows[i].split("=");
			table_row = ((i+1)%2)?1:2;
			html += '	<tr>\n';
			html += '		<td height="22" align="left" valign="middle" style="padding-left: 5px; padding-right: 10px; font-weight: bold;" class="table_row_' + table_row + '">' + cols[0] + '</td>\n';
			html += '		<td align="left" valign="middle" class="table_row_' + table_row + '">' + cols[1] + '</td>\n';
			html += '		<td align="left" valign="middle" class="table_row_' + table_row + '">' + cols[2] + ' ' + Translation.currency + '</td>\n';
			html += '	</tr>\n';
		}
		html += '</table>\n';
		return html;
	}

	this.getDateTime = function(date){
		//date.setTime(TIME_MODIFICATION);
		var date_string = System.getMySQLTimeFormat(date).split(" ");
		//return System.formatDate(date_string[0]) + ' <img src="admin/img/icon/time_10px.png" alt="" border="0" width="10" height="10" /> ' + System.formatTime(date_string[1]);
		return System.formatDate(date_string[0]) + ' - ' + System.formatTime(date_string[1]);
	}

	//------------------------------------------------------
	// Show/hide
	//------------------------------------------------------

	this.showStatus = function(){

		switch(this.status){
			case "coming":
				this.showStatusComing();
				break;
			case "running":
				this.showStatusRunning();
				break;
			case "paused":
				this.showStatusPaused();
				break;
			case "checking":
				this.showStatusChecking();
				break;
			case "sold":
				this.showStatusSold();
				break;
			default:
				//alert("Error: Unknown status [" + this.status + "]");
				break;
		}
	}

	this.showStatusComing = function(){
		this.showStatusPaused();

		this.dom_auctionItem.hide();
		$("#auctionBetButtonComing" + this.id).show();
		if(this.ifDetailView() || this.is_top){
			$("#auctionDateStart" + this.id).html(Translation.auction_date_start + ": " + "<span>" + this.getDateTime(this.date_start) + "</span>&nbsp;");
		} else {
			$("#auctionDateStart" + this.id).html(Translation.auction_date_start + ":<br />" + "<span>" + this.getDateTime(this.date_start) + "</span>");
		}
	}

	this.showStatusRunning = function(){
		this.dom_auctionItem.hide();

		if(this.ifLoggedUserIsBidder()){
			$("#auctionBetButtonBidded" + this.id).show();
			//$("#bidButtonLoading" + this.id).hide();
			//$("#auctionBetButton2" + this.id).fadeTo("normal", 0.33);
		} else {
			//$("#auctionBetButton2" + this.id).fadeTo(1, 1);
			$("#auctionBetButton" + this.id).show();
		}
		$("#auctionBetSMS" + this.id).show();
		if(this.ifDetailView()){
			ALLOW_AUTO_BIDDER = true;
		}
		$("#counterTag" + this.id).show();
		if(!this.ifDetailView()){
			if(this.is_top){
				$("#counterTag" + this.id + ' img.top_auction_icon').show();
			} else {
				$("#counterTag" + this.id + ' img.auction_icon').show();
			}
		}
		$("#auctionDateStart" + this.id).hide();
		$("#auctionDateEnd" + this.id).hide(); //show();
		$("#auctionDateSold" + this.id).hide();
		$("#timeTag" + this.id).text(System.formatTime(this.interval.getMinutes() + ":" + this.interval.getSeconds())).css('font-size', '22px');
		this.showIntervalColors();
	}

	this.showStatusPaused = function(){
		this.dom_auctionItem.hide();

		$("#auctionBetButtonPaused" + this.id).show();

		$("#auctionBetSMS" + this.id).hide();
		if(this.ifDetailView()){
			ALLOW_AUTO_BIDDER = true;
		}
		$("#counterTag" + this.id).show();

		switch(this.type){

			case 'top_auction':
				$("#counterTag" + this.id + ' img.top_auction_icon').hide();
				break;

			case 'menu_auction':
				$("#counterTag" + this.id + ' img.menu_auction_icon').hide();
				$("#timeTag" + this.id).css('font-size', '19px !important');
				break;

			case 'detail_auction':
				break;

			default:
				$("#counterTag" + this.id + ' img.auction_icon').hide();
				break;
		}

		$("#auctionDateStart" + this.id).show();
		$("#auctionDateEnd" + this.id).hide();
		$("#auctionDateSold" + this.id).hide();
		$("#timeTag" + this.id).text(System.formatTime(this.interval.getMinutes() + ":" + this.interval.getSeconds()));
		if(this.ifDetailView() || this.is_top){
			$("#auctionDateStart" + this.id).html(Translation.auction_date_start + ": " + "<span>" + this.getDateTime(this.date_start) + "</span>&nbsp;");
		} else {
			$("#auctionDateStart" + this.id).html(Translation.auction_date_start + ":<br />" + "<span>" + this.getDateTime(this.date_start) + "</span>");
		}
		this.showIntervalColors();

		//Countdown
		var countdown = new CountDown();
		countdown.from = new Date();
		countdown.to = this.date_start;

		$("#timeTag" + this.id).text(countdown.getCountDown()).css('font-size', '22px');
	}

	this.showStatusChecking = function(){
		//$("#timeTag" + this.id).text("(" + this.getCheckingCounter() + ") " + Translation.auction_check_bids);
		$("#timeTag" + this.id).text(Translation.auction_check_bids).css("font-size", "12px");

		this.dom_auctionItem.hide();

		$("#auctionBetButtonChecking" + this.id).show();

		$("#auctionBetSMS" + this.id).show();
		if(this.ifDetailView()){
			ALLOW_AUTO_BIDDER = false;
		}
		$("#counterTag" + this.id).show();
		$("#auctionDateStart" + this.id).hide();
		$("#auctionDateEnd" + this.id).hide();
		$("#auctionDateSold" + this.id).hide();
		//$("#auctionBetButton2" + this.id).fadeTo("slow", 0.33);
	}

	this.showStatusSold = function(){
		//this.showStatusPaused();
		this.dom_auctionItem.hide();

		$("#auctionBetButtonSold" + this.id).show();

		$("#auctionBetSMS" + this.id).hide("slow");
		if(this.ifDetailView()){
			$("#autoBidder").hide("slow", function(){
				$("#autoBidder").remove();
			});
		}
		$("#counterTag" + this.id).hide("slow");
		$("#auctionDateStart" + this.id).hide();
		//$("#auctionDateEnd" + this.id).hide("slow");
		if(this.ifDetailView() || this.is_top){
			$("#auctionDateSold" + this.id).html(Translation.auction_date_sold + ": " + "<span>" + this.getDateTime(this.date_start) + "</span>&nbsp;");
		} else {
			$("#auctionDateSold" + this.id).html(Translation.auction_date_sold + ":<br />" + "<span>" + this.getDateTime(this.date_start) + "</span>");
		}
		$("#auctionDateSold" + this.id).show();
	}

	this.showLastBidderFade = function(){
		if(this.ifBidAdded()){
			$("#timeTag" + this.id).highlightFade({start:[255,160,0], interval:10, speed:600});
			$("#bestTag" + this.id).highlightFade({start:[255,160,0], interval:10, speed:600});
			if(!this.ifLoggedUserIsBidder()){
				//$("#auctionBetButton2" + this.id).fadeTo(1, 1);
			} else {
				if(this.is_auto_bidder && this.ifManyLastBidders()){
					AutoBidder.refresh(true);
				}
			}
		}
	}

	this.showIntervalColors = function(){
		var timeTag = $("#timeTag" + this.id);
		if(this.is_top){
			timeTag.css("font-size", "22px");
			timeTag.removeClass("top_auction_counter_text_3");
			timeTag.removeClass("top_auction_counter_text_2");
			timeTag.removeClass("top_auction_counter_text_1");

			if(this.interval <= AUCTION_INTERVAL_END){
				timeTag.addClass("top_auction_counter_text_3");
				if(this.interval <= AUCTION_INTERVAL_END_SOUND){
					this.playSound();
				}
			} else if (this.interval <= AUCTION_INTERVAL_MIDDLE){
				timeTag.addClass("top_auction_counter_text_2");
			} else {
				timeTag.addClass("top_auction_counter_text_1");
			}
		} else {
			timeTag.css("font-size", "22px");
			timeTag.removeClass("auction_counter_text_3");
			timeTag.removeClass("auction_counter_text_2");
			timeTag.removeClass("auction_counter_text_1");

			if(this.interval <= AUCTION_INTERVAL_END){
				timeTag.addClass("auction_counter_text_3");
				if(this.interval <= AUCTION_INTERVAL_END_SOUND){
					this.playSound();
				}
			} else if (this.interval <= AUCTION_INTERVAL_MIDDLE){
				timeTag.addClass("auction_counter_text_2");
			} else {
				timeTag.addClass("auction_counter_text_1");
			}
		}
	}

	this.showOverallParameters = function(){
		$("#priceTag" + this.id).text(this.price);
		$("#bestTag" + this.id).text(this.getLastBidder());
		if(this.ifManyLastBidders()){
			$("#auctionLastUsers" + this.id).html(this.getLastBidders());
		}
	}

	//------------------------------------------------------
	// System
	//------------------------------------------------------

	this.runSystem = function(){
		if(this.date_start <= CURRENT_DATE){
			this.setStatus("running");
			this.interval = new Date(this.date_end - CURRENT_DATE);
			if((this.interval <= 0 && this.interval >= -CHECKING_TIME) || System.formatTime(this.interval.getMinutes() + ":" + this.interval.getSeconds()) == "00:00"){
				this.setStatus("checking");
			} else if (this.interval < -CHECKING_TIME){
				if(ABORT_ALL){
					this.setStatus("checking");
				} else {
					this.setStatus("sold");
				}
			}
		} else {
			if(this.status == "paused" || (this.status == "running" && this.date_start.getDay() != CURRENT_DATE.getDay())){
				this.setStatus("paused");
			} else {
				this.setStatus("coming");
			}
			this.interval = new Date(this.date_end - this.date_start);
		}
	}

	this.ifBidAdded = function(){
		return (AUCTION_PRICE[this.id] != "undefined" && AUCTION_PRICE[this.id] != null && this.price != AUCTION_PRICE[this.id])?true:false;
	}

	this.ifLoggedUserIsBidder = function(){
		return (USERNAME != null && USERNAME != "" && USERNAME != "-" && USERNAME == this.getLastBidder())?true:false;
	}

	this.ifManyLastBidders = function(){
		return (this.last_bidder.indexOf(";") != -1)?true:false;
	}

	this.ifDetailView = function(){
		return (this.view == 'detail_auction')?true:false;
	}

	this.getCheckingCounter = function(){
		var seconds = Math.abs(this.interval.getSeconds() - (60 - (CHECKING_TIME/1000)) + 1);
		return (seconds > (CHECKING_TIME/1000))?(CHECKING_TIME/1000):seconds;
	}

	this.playSound = function(){
		//TODO:
		//alert(System.getMySQLTimeFormat(FLASH_TEMP_DATE) + " ja " + System.getMySQLTimeFormat(CURRENT_DATE));
		//if(System.getMySQLTimeFormat(FLASH_TEMP_DATE) != System.getMySQLTimeFormat(CURRENT_DATE)){
		//	AuctionFlashMovie.Play();
		//	FLASH_TEMP_DATE = CURRENT_DATE;
		//}
	}

	//------------------------------------------------------
	// Init
	//------------------------------------------------------

	this.init = function(){
		/*if(this.is_auto_bidder){
			AutoBidder.setAuctionId(this.id);
		}*/
		this.runSystem();
		this.showStatus();
		this.showLastBidderFade();
		this.showOverallParameters();
		// -------------------
		//$(".pixmasoft").text(" Status[" + this.id + "]: " + this.status);
		//$(".pixmasoft").html("CURRENT_DATE: " + System.getMySQLTimeFormat(CURRENT_DATE) + "<br>date_start: " + System.getMySQLTimeFormat(this.date_start) + "<br>date_end: " + System.getMySQLTimeFormat(this.date_end));
		// -------------------
		AUCTION_PRICE[this.id] = this.price;
		//Auctions.auctions[this.id] = this;
		//DEBUG = DEBUG + 1;
		//DEBUG_AUCTION[this.id] = ((DEBUG_AUCTION[this.id])?DEBUG_AUCTION[this.id]:0) + 1;
	}
}

Auctions = {

	auctions: new Array(),

	refreshData: function(string){
		var auctions_data = string.split("#");
		for (var i = 0; i < auctions_data.length; i++) {
			if (i == 0) {
				//TODO: System time
				//$(".pixmasoft").text(auctions_data[i]);
			} else if (auctions_data[i] !== null) {
				var auction = auctions_data[i].split("|");
				if(typeof(Auctions.auctions[auction[0]]) !== "undefined"){
					var obj = Auctions.auctions[auction[0]];
					obj.setDateStart(auction[4]);
					obj.setDateEnd(auction[1]);
					obj.setLastBidder(auction[2]);
					obj.setPrice(auction[3]);
				}
				//obj.init();
			}
		}
	},

	requestData: function(db){
		var ids = "";
		var comma = false;
		for (var i in Auctions.auctions){
			if (Auctions.auctions[i].getStatus() == "running" || Auctions.auctions[i].getStatus() == "checking" || Auctions.auctions[i].getStatus() == "sold" || Auctions.auctions[i].getStatus() == "coming" || Auctions.auctions[i].getStatus() == "paused") {
				if(comma){
					ids += ",";
				} else {
					comma = true;
				}
				ids += Auctions.auctions[i].getId();
			}
		}
		if (ids != null) {
			$.ajax({
				type: "POST",
				url: DOC_URL + "auction.php",
				data: {
					//"ids": 	ids,
					//"u": ((u)?u:false),
					"sync": ((db)?true:false)
				},
				cache: false,
				dataType: "text",
				error: function(XMLHttpRequest, textStatus, errorThrown){
					ABORT_ALL = true;
				},
				success: function(string){
					Auctions.refreshData(string);
					ABORT_ALL = false;
				}
			});
		}

		// ---------------------------------------

		/*$(".pixmasoft").text("ids=" + ids);
		var txt = "";
		for (var i in Auctions.auctions){
			if(AUCTION_PRICE[Auctions.auctions[i].getId()] != "undefined" || AUCTION_PRICE[Auctions.auctions[i].getId()] != null){
				txt += i + ": " + AUCTION_PRICE[Auctions.auctions[i].getId()] + "<br>";
			}
		}
		$(".copyright").html(txt);*/

		// ---------------------------------------
	},

	refreshTime: function(){

		for (var i in Auctions.auctions){
			var obj = Auctions.auctions[i];
			obj.init();
		}
	},

	init: function(){
		Auctions.requestData();
	}
}

System = {

	server_date: new Date(),
	client_date: new Date(),
	time_diff: new Date(),

	setServerDate: function(datetime){
		this.server_date = createDateFromSQLString(datetime);
	},

	setClientDate: function(datetime){
		this.client_date = datetime;
	},

	setSystemDate: function(){
		this.time_diff = this.client_date.getTime() - this.server_date.getTime();
		CURRENT_DATE.setTime(new Date() - this.time_diff);
	},

	formatDate: function(date_string){
		var numbers = date_string.split("-");
		return this.formatNumber(numbers[2]) + "." + this.formatNumber(numbers[1]) + "." + this.formatNumber(numbers[0]);
	},

	formatTime: function(time_string){
		var numbers = time_string.split(":");
		time_string = "";
		for(i=0; i<numbers.length; i++){
			time_string += this.formatNumber(numbers[i]) + (((i+1) !== numbers.length)?":":"")
		}
		return time_string;
	},

	getMySQLTimeFormat: function(date){
		return this.formatNumber(date.getFullYear()) + "-" + this.formatNumber(date.getMonth()+1) + "-" + this.formatNumber(date.getDate()) + " " + this.formatNumber(date.getHours()) + ":" + this.formatNumber(date.getMinutes()) + ":" + this.formatNumber(date.getSeconds());
	},

	formatNumber: function(number){

		number = parseFloat(number);

		return (number < 10)?"0" + parseInt(number):number;
	},

	showClock: function(){
		var time = new Date(CURRENT_DATE.getTime() + TIME_MODIFICATION);
		$("#clock").text(this.formatTime(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds()));
	},

	showDate: function(){
		var time = new Date(CURRENT_DATE.getTime() + TIME_MODIFICATION);
		$("#date").text(time.getDate() + ". " + Translation.month[time.getMonth()] + " " + time.getFullYear());
	},

	ifMidNight: function(){
		var time = new Date(CURRENT_DATE.getTime());
		var clock = this.formatTime(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
		if((clock == "00:00:00" || clock == "00:00:01")){
			return true;
		} else {
			return false;
		}
	},

	abortAll: function(){
		if(ABORT_ALL){
			/*if(!Shadowbox.isOpen()){
				Shadowbox.open({
					player:     'html',
					content:    '<div class="shadowbox_message" align="center"><br />' + Translation.internet_error_popup_text_1 + '<br />' + Translation.internet_error_popup_text_2 + '<br /><br /><input type="button" class="button" value="' + Translation.internet_error_popup_button + '" onclick="window.location.reload();" /></div>',
					options:	{
						modal: true,
						displayNav: false,
						enableKeys: false
					},
					height:     150,
					width:      300
				});
			}*/
		}
	},

	init: function(){
		this.setServerDate(SYSTEM_DATE);
		this.setClientDate(CLIENT_DATE);
		this.setSystemDate();
		this.showClock();
		this.showDate();
		this.abortAll();
		if(this.ifMidNight()){
			Auctions.requestData(true);
		}
		Auctions.refreshTime();
	}
}

Splash = {

	splash_time: 0,
	splash_time_confirm: 20000,

	splash_timeout: SPLASH_TIMEOUT,

	setTime: function(time){
		this.splash_time = time;
	},

	getTime: function(){
		return this.splash_time;
	},

	increaseTime: function(){
		this.splash_time += 1000;
	},

	restart: function(){
		this.setTime(0);
	},

	redirect: function(){
		window.location = DOC_URL + "splash.php?lang_id=" + LANG_ID;
	},

	showConfirmPopup: function(){
		Translation.splash_popup_text = Translation.splash_popup_text.replace('{splash_time_confirm}', '<span id="splash_time_confirm">' + (this.splash_time_confirm/1000) + '</span>');

		Shadowbox.open({
			player:     'html',
			content:    '<div class="shadowbox_message" align="center"><br />' + Translation.splash_popup_text + '<br /><br /><br /><input type="button" class="button" value="' + Translation.splash_popup_button_text + '" onclick="Splash.restart(); Shadowbox.close();" /></div>',
			options:	{
				modal: true,
				displayNav: false,
				enableKeys: false
			},
			height:     190,
			width:      420
		});
	},

	init: function(){
		if((this.splash_timeout - this.getTime()) == this.splash_time_confirm){
			this.showConfirmPopup();
		}
		if((this.splash_timeout - this.getTime()) <= this.splash_time_confirm){
			$("#splash_time_confirm").text((this.splash_timeout - this.getTime())/1000);
		}
		if(this.getTime() >= this.splash_timeout){
			this.redirect();
		} else {
			setTimeout('Splash.init()', 1000);
			this.increaseTime();
		}
	}
}

PopupAdd = {

	show: function(){
		Shadowbox.open({
			player:     'html',
			content:    '<div><a href="' + DOC_URL + LANG_ID + '/user/register/' + '"><img src="img/auction_popup_add_' + LANG_ID + '.png" border="0" /></a></div>',
			options:	{
				modal: false,
				displayNav: true,
				enableKeys: true
			},
			width:      450,
			height:     360
		});
		$.cookie('popup_add', 'true', {expires: 7, path: '/', domain: ''});
	},

	init: function(){
		if(!POPUP_ADD && USERNAME) return;
		if($.cookie('popup_add') == null){
			setTimeout(PopupAdd.show, 20000);
		}
	}
}

Sync = {

	init: function(){
		$.ajax({
			type: "GET",
			url: DOC_URL + "sync.php",
			cache: false,
			dataType: "text",
			error: function(XMLHttpRequest, textStatus, errorThrown){
				ABORT_ALL = true;
			},
			success: function(string){
				ABORT_ALL = false;
			}
		});
	}
}

//$(window).load(function(){
	setInterval(function() {System.init()}, LOCAL_CICLE);
	setInterval(function() {Auctions.init()}, REMOTE_CICLE);
	//setInterval(function() {Sync.init()}, SYNC_CICLE);
	Splash.init();
	//PopupAdd.init();
//});

Test = {

	init: function(){
		$.ajax({
			type: "GET",
			url: DOC_URL + "auctions.txt",
			cache: false,
			dataType: "json",
			/*beforeSend: function(x) {
				if(x && x.overrideMimeType) {
					x.overrideMimeType("application/json;charset=utf-8");
				}
			},*/
			error: function(XMLHttpRequest, textStatus, errorThrown){
				ABORT_ALL = true;
			},
			success: function(json){
				$(".pixmasoft").text(json.date);
			}
		});
	}
}

//setInterval('Test.init()', 3000);

function createDateFromSQLString(datetime) {
	var datetime_split = datetime.split(" "); //YYYY-MM-DD HH:mm:ss
	var date_split = datetime_split[0].split("-");
	var time_split = datetime_split[1].split(":");

	return new Date(date_split[0], date_split[1] - 1, date_split[2], time_split[0], time_split[1], time_split[2]);
}

function count(array){
	var length = 0;
	for (var i in array){
		length++;
	}
	return length;
}

function array_repair(_array){
	var array = new Array();
	for (var i in _array){
		array[array.length] = _array[i];
	}

	return array;
}

function CountDown(){

	{
		this.from = new Date();
		this.to = null;
	}

	this.getCountDown = function(){

		var time = Math.round((this.to - this.from)/1000);
		var sec = time%60;
		time = Math.floor(time/60);
		var min = time%60;
		time = Math.floor(time/60);
		var hour = time%24;
		var day = Math.floor(time/24);

		return ((day == 0)?'':(System.formatNumber(day) + (day==1?":":":"))) + System.formatNumber(hour) + (hour==1?":":":") + System.formatNumber(min) + (min==1?":":":") + System.formatNumber(sec) + (sec==1?"":"");
	    //return ((day == 0)?'':(day + (day==1?" d ":" d "))) + hour + (hour==1?" h ":" h ") + min + (min==1?" m ":" m ") + ((sec == 0)?'':(sec + (sec==1?" s ":" s ")));
		//return ((day == 0)?'':(day + (day==1?"day ":"days "))) + hour + (hour==1?"hour ":"hours ") + min + (min==1?"min ":"mins ") + ((sec == 0)?'':(sec + (sec==1?"sec ":"secs ")));
	}
}

/* Auction bookmark */

function makeBid(auction_id){
	//ajaxRequest(DOC_URL + "auction_bidder.php?id=" + auction_id, "GET", alertMakeBid);
	//$("#bidButtonLoading" + auction_id).show();
	$.ajax({
		type: "POST",
		url: DOC_URL + "auction_bidder.php",
		data: {id: auction_id},
		cache: false,
		dataType: "text",
		success: function(html){
			alertMakeBid(html, auction_id);
			Splash.restart();
		}
	});
}

function alertMakeBid(response, auction_id){

	var xml = new XMLParser(response);
	var user_bids = $('#user_bids');

	if(xml.getTag("message") == "message_bid_added"){
		user_bids.text(xml.getTag("bids"));
		Auctions.requestData(true);

	} else if(xml.getTag("message") == "message_bid_added" && xml.getTag("bids") == "0"){
		user_bids.text("0");
		//$("#bidButtonLoading" + auction_id).hide();

	} else if(xml.getTag("message") == "message_no_bids"){
		user_bids.text("0");
		//$("#bidButtonLoading" + auction_id).hide();

		Shadowbox.open({
			player:     'html',
			content:    '<div class="shadowbox_message" align="center"><br />' + Translation.auction_error_no_bids + '<br /><br /><br /><br /><input type="button" class="button" value="' + Translation.auction_go_buy_bids + '" onclick="openBidPacketWindow(\'' + Translation.auction_go_buy_bids + '\', \'' + DOC_URL + 'popup.php?lang_id='+ LANG_ID +'&module=user&action=load_money&id=\')" /> <input type="button" class="button" value="' + Translation.close + '" onclick="Shadowbox.close();" /></div>',
			height:     170,
			width:      370
		});

	} else if(xml.getTag("message") == "message_auction_ended"){
		Shadowbox.open({
			player:     'html',
			content:    '<div class="shadowbox_message" align="center"><br />' + Translation.auction_error_auction_has_ended + '<br /><br /><br /><br /><input type="button" class="button" value="' + Translation.close + '" onclick="Shadowbox.close();" /></div>',
			height:     170,
			width:      370
		});
		//$("#bidButtonLoading" + auction_id).hide();

	} else {

	}
}

/* Auction bookmark */

function addAuctionBookmark(auction_id){
	//ajaxRequest(DOC_URL + "auction_bookmark.php?id=" + auction_id, "GET", alertAuctionBookmark);
	$.ajax({
		type: "POST",
		url: "auction_bookmark.php",
		data: {id: auction_id},
		cache: false,
		dataType: "text",
		success: alertAuctionBookmark
	});
	//TODO: loading
}

function alertAuctionBookmark(response){
	var xml = new XMLParser(response);
	if(xml.getTag("message") == "auction_bookmark_added"){
		//document.getElementById("futureAuctionButton" + xml.getTag("auction_id")).style.cursor = "default";
		document.getElementById("futureAuctionButtonTextAdd" + xml.getTag("auction_id")).style.display = "none";
		document.getElementById("futureAuctionButtonTextAdded" + xml.getTag("auction_id")).style.display = "block";

	} else if(xml.getTag("message") == "auction_bookmark_exists"){
		//document.getElementById("futureAuctionButton" + xml.getTag("auction_id")).style.cursor = "default";
		document.getElementById("futureAuctionButtonTextAdd" + xml.getTag("auction_id")).style.display = "none";
		document.getElementById("futureAuctionButtonTextAdded" + xml.getTag("auction_id")).style.display = "block";
		getLoginMessage(Translation.auction_future_bookmark_error_exists, Translation.close);

	} else if(xml.getTag("message") == "auction_bookmark_error"){
		getLoginMessage(Translation.auction_future_bookmark_error_login, Translation.close);
	}
}

/* SITE */

$(window).resize(function(){
	if($(window).width() < 1130){
		$("#sticker").hide();
	} else {
		$("#sticker").show();
	}
	if(navigator.appVersion.indexOf("MSIE 6.") == -1){
		$("#body").css("height", $(document).height()-$("#footer_container").height()+10);
	}
});

$(window).ready(function(){
	if($(window).width() < 1130){
		$("#sticker").hide();
	} else {
		$("#sticker").show();
	}
	if(navigator.appVersion.indexOf("MSIE 6.") == -1){
		$("#body").css("height", $(document).height()-$("#footer_container").height()+10);
		if($('#body_right_container').height() > $('.content').height() && window.location.href.indexOf("happy_winners") == -1){
			$(".content_body").css("height", $('#body_right_container').height()-30);
		}
	}
});

/* POPUP */

function getAuctionLoginMessage(auction_id, auction_name){

	var html = '';
	html += '<div class="auction_error_popup">\n';
	html += '	<div class="auction_error_popup_login_or_send_sms">' + Translation.auction_error_popup_login_or_send_sms.replace('{auction_name}', '<strong>' + auction_name + '</strong>') + '</div>\n';
	html += '	<div class="auction_error_popup_register_or_send_sms">\n';
	html += '		<div class="button_register" style="float: left !important; top: -5px !important; left: 0px !important; position: relative !important;" onClick="location.href=\'' + DOC_URL + LANG_ID + '/user/register\'">\n';
	html += '			<div class="button_register_text" align="center">' + Translation.auction_error_popup_register_now + '</div>\n';
	html += '		</div>\n';
	html += (!IS_SMS_BIDDING)?'':'		<div class="auction_error_popup_or_send_sms">' + Translation.auction_error_popup_or_send_sms + '</div>\n';
	html += '	</div>\n';
	html += (!IS_SMS_BIDDING)?'':'	<div class="auction_error_popup_sms"><img src="img/auction_icon_mobile.png" alt="" width="16" height="16"> ' + Translation.auction_error_popup_send_sms.replace('{sms_keyword}', '<span class="auction_bid_sms_text_color">' + SMS_BID_KEYWORD + ' ' + auction_id + '</span>').replace('{sms_number}', '<span class="auction_bid_sms_text_color">' + SMS_BID_SHORTCODE + '</span>')  + '</div>\n';
	html += '	<div class="auction_error_popup_login_message">' + Translation.auction_error_popup_login_message + '</div>\n';
	html += '	<div class="auction_error_popup_login">\n';
	html += '		<form action="' + DOC_URL + LANG_ID + '/user/login" method="post" name="login_form2" id="login_form2" target="_self">\n';
	html += '			<div class="auction_error_popup_login_field" style="padding-left: 20px;">\n';
	html += '				<img src="img/auction_login_field_left.png" alt="" width="5" height="24" class="login_field_left" />\n';
	html += '				<input name="username" id="username" type="text" onKeyPress="return submit_enter2(this,event)" value="' + Translation.user_login_field_username + ':" onFocus="if(this.value==\'' + Translation.user_login_field_username + ':\'){this.value=\'\'};" onBlur="if(this.value==\'\'){this.value=\'' + Translation.user_login_field_username + ':\'};" class="login_field_input" />\n';
	html += '				<img src="img/auction_login_field_right.png" alt="" width="5" height="24" class="login_field_right" />\n';
	html += '			</div>\n';
	html += '			<div class="auction_error_popup_login_field">\n';
	html += '				<img src="img/auction_login_field_left.png" alt="" width="5" height="24" class="login_field_left" />\n';
	html += '				<input name="pwd" id="pwd" type="password" onKeyPress="return submit_enter2(this,event)" value="' + Translation.user_login_field_password + ':" onFocus="if(this.value==\'' + Translation.user_login_field_password + ':\'){this.value=\'\'};" onBlur="if(this.value==\'\'){this.value=\'' + Translation.user_login_field_password + ':\'};" class="login_field_input" />\n';
	html += '				<img src="img/auction_login_field_right.png" alt="" width="5" height="24" class="login_field_right" />\n';
	html += '			</div>\n';
	html += '			<div class="auction_error_popup_login_field">\n';
	html += '				<div class="login_button" onClick="submit_login2();">\n';
	html += '					<div class="login_button_text" align="center">' + Translation.user_login_button_login + '</div>\n';
	html += '				</div>\n';
	html += '			</div>\n';
	html += '			<input name="password" id="password" type="hidden" value="" />\n';
	html += '		</form>\n';
	html += '		<div class="auction_error_popup_login_lost_password"><a href="javascript:void(0)" onClick="Shadowbox.open({player:\'iframe\', content:\'' + DOC_URL + 'popup.php?lang_id=' + LANG_ID + '&module=user&action=lost_password\', height: 250, width: 450});">' + Translation.user_login_link_lost_password + '</a></div>\n';
	html += '	</div>\n';
	html += '</div>\n';

	Shadowbox.open({
        player:     'html',
        content:    html,
        height:     300,
        width:      400,
		options:	{enableAllKeys: true}
    });
}

function getLoginMessage(error_message, close_button_text){
	Shadowbox.open({
        player:     'html',
        content:    '<div class="shadowbox_message" align="center"><br />' + error_message + '<br /><br /><br /><br /><input type="button" class="button" value="' + close_button_text + '" onclick="Shadowbox.close();" /></div>',
        height:     200,
        width:      300
    });
}

function openMobileWindow (title_text, url){
	Shadowbox.open({
        player:     'iframe',
        content:    url,
		//title:	title_text,
        height:     370,
        width:      200
    });
}

function openBidPacketWindow (title_text, url){
	if(USERNAME){
		Shadowbox.open({
			player:     'iframe',
			content:    url,
			title:	title_text,
			width:      860,
			height:     720,
			options: {handleOversize: "none"}
		});
	} else {
		Shadowbox.open({
			player:     'iframe',
			content:    url,
			title:	title_text,
			width:      525,
			height:     400,
			options: {handleOversize: "none"}
		});
	}
}