var twoDigits = function(x) {
	return (x<10?'0':'')+x;
};

var currency = function(x) {
	x = x.replace(/\./g, ',');
	var s = x.split(',');
	if (s.length == 1) {
		return x+',00';
	} else if (s[s.length-1].length < 2) {
		return x+'0';
	} else {
		return x;
	}
};

function updateClock() {
  var now = new Date();
  myClock.setTime(now.getTime()-clientUTC+serverUTC);
  var h = myClock.getHours();
  var m = myClock.getMinutes();
  var s = myClock.getSeconds();
  $('clock').update(twoDigits(h)+':'+twoDigits(m)+':'+twoDigits(s)+' UHR');
}

//place a bid
function setOneBid(id) {
	SnipsterAuctionUpdater.reset();
	new Ajax.Request('/auctions/bid/'+id+'/1/'+currentBidCounts['aid'+id]+'/'+Math.random(), {method:'post', onComplete:bidsSet});			
}

//place some bids
function setBids(id) {
	SnipsterAuctionUpdater.reset();
	var setNum = $('bidcount'+id);
	new Ajax.Request('/auctions/bid/'+id+'/'+setNum.value+'/'+currentBidCounts['aid'+id]+'/'+Math.random(), {method:'post', onComplete:bidsSet});
	setNum.value = 1;
}

var currentBidCounts = new Object();

function updateCurrentBidCount(auctionId, currentBidCount) {
	currentBidCounts['aid'+auctionId] = currentBidCount;
}

function processResponse(r) {
	var rs = r.responseText.split('|');
	showMessageTip(rs[0], rs[2]);
}

function showMessageTip(aid, msg) {
	var id = 'tt'+aid;
	$(id).update(msg);
        $(id).appear({duration: 0.5});
        $(id).observe('click', function() {$(id).fade({duration: 0.5});});
	setTimeout(function() {$(id).fade({duration: 0.5});}, 10000);
}

var bidsSet = function(r) {
	var rs = r.responseText.split("|");
	updateUserData();
	if (rs[1] >= 0) {
		updateCurrentBidCount(rs[0], rs[1]);
	}
	showMessageTip(rs[0], rs[2]);
	
	return false;
};

var updateUserData = function() {
	new Ajax.Request('/users/getUserInfo/'+Math.random(), {method:'post', onComplete:function(r) {
	  	var response = r.responseText;
	  	var ui = response.split("|");
	    if(ui.length == 2) {
	        $('bidBalance').update(ui[0]+ (ui[0]==1?' Gebot':' Gebote'));
	        $('auctionLimit').update(ui[1]+' %');
	    }
	}});
};

window.UserInfoTipSingleton = {
    timeout: null
};

function showUserInfoTip(username, userId, parent) {
    SnipsterAuctionUpdater.reset();
    var offset = parent.positionedOffset();
    var position;
    if(parent) {
        if (parent.hasClassName("spotlightUser")) {
            // Front page, spot light view.
            position = {
                'position': 'absolute',
                'left': '360px',
                'top': '267px'
            };

        } else if(parent.hasClassName("detailUser")) {
            // Auction detail view
            position = {
                'position': 'absolute',
                'left': '360px',
                'top': '260px'
            };
        } else if(parent.hasClassName("boxUser")) {
            // Which part of the screen is clicked? left/right
            var width = window.document.viewport.getWidth();
            position = {
                'position': 'absolute',
                'left': (offset[0]-130)+'px',
                'top': (offset[1]-38)+'px'
            };
            if(offset[0] < (width/2-180)) {
                // Left
                position['left'] = '200px';
            } else {
                // Right
                position['left'] = '80px';
            }
        } else if(parent.hasClassName("sidebarUser")) {
            position = {
                'position': 'absolute',
                'left': '420px',
                'top': '177px'
            };
        } else if(parent.hasClassName("historyUser")) {
            position = {
                'position': 'absolute',
                'left': '290px',
                'top': (offset[1]+22)+'px'
            };
        } else if(parent.hasClassName("listUser")) {
            position = {
                'position': 'absolute',
                'left': '290px',
                'top': (offset[1]+22)+'px'
            };
        } else {
            position = {
                'position': 'absolute',
                'top': '320px',
                'left': '440px'
            };
        }
    }
	new Ajax.Request('/getUserInfo.php?user_id='+userId, {method:'post', onComplete:function(r) {
	  	var response = r.responseText;
	  	var ui = response.split(";");
        var $tip = $("userInfoTip");
	    if(ui.length == 3) {
	    	$('userInfoTipUsername').update(username);
	    	for (var i=0; i<ui.length; i++) {
	    		var uiItems = ui[i].split("|");
	    		$('userInfoTipValue'+i).update(uiItems[0]);
	    		if (i > 0) {
		    		$('userInfoTipRating'+i).className = 'rating_'+uiItems[1];
	    		}
	    	}
            $tip.appear({duration: 0.5});
            if(parent) {
                $tip.setStyle(position);
           }


           // Set a timeout.
           if(UserInfoTipSingleton.timeout) {
               // Clear old timeout and set new.
               window.clearTimeout(UserInfoTipSingleton.timeout);
           }
           UserInfoTipSingleton.timeout = window.setTimeout(hideUserInfoTip, 10000);
           
           // Make the tip clickable
           $tip.observe('click', hideUserInfoTip);
        }
	}});
}

function hideUserInfoTip() {
    $('userInfoTip').fade({duration: 0.5});
    // Clear the timeout
    if(UserInfoTipSingleton.timeout) {
        window.clearTimeout(UserInfoTipSingleton.timeout);
    }
}

// This handle must be overwritten when activity index has not 'normal' size.
var updateActivityIndex = function(auctionId, activity, isActive) {
	updateActivityIndexSpecific(auctionId, activity, isActive, 'normal');
};

function updateActivityIndexSpecific(auctionId, activity, isActive, size) {
	//if (Math.random() <= 0.25) alert(auctionId + ' ' + activity + ' ' + isActive + '/' + (isActive!='0'?'T':'F'));
	activity = Math.max(activity-2, 0);
	var active = $('aia'+auctionId);
	var inactive = $('aiia'+auctionId);
	if (isActive!=0) {
		var offset = (parseInt(activity))*10;
		switch (size) {
		case 'small':
			offset = (parseInt(activity))*8-1;
			break;
		}
		inactive.style.display='none';
		$('cat'+auctionId).style.marginLeft=offset+'px';
		$('cab'+auctionId).style.marginLeft=offset+'px';
		active.style.display='block';
	} else {
		active.style.display='none';
		inactive.style.display='block';
	}
}

function getElementsByClassName(c,t) {
	var array = [];
	var tags = document.getElementsByTagName(t);
	for(var i=0,len=tags.length;i<len;i++) {
		if(tags[i].className == c) {
			array.push(tags[i]);
		}
	}
	return array;
}

//save watchlist and redirect to it
function saveWatchlist(auctionId) {

	if(!auctionId) {
		var watchListItems = getElementsByClassName('watchlist','input');
		var saveItems = '';
	
		for(var i=0,len=watchListItems.length;i<len;i++) {
			if(watchListItems[i].checked) saveItems += watchListItems[i].name+'|';
		}
		
		if(saveItems != '') {	
			document.location.href = '/watchlists/save/'+saveItems;
		} else {
			alert('Sie haben keine Auktion ausgewählt');
		}
	} else {
		document.location.href = '/watchlists/save/'+auctionId+'|';
	}

}

function selectAll(c) {
	
	var tags = document.getElementsByTagName('input');
	
	for(var i=0,len=tags.length;i<len;i++) {
		if(tags[i].className == c) {
			tags[i].checked = true;
		}
	}
	
	return false;
}

var actions = new Array(); 
						
function viewBox(id) {
																			
	// close
	if(actions[id] == 'open') {
													
		document.getElementById('body'+id).style.display='none';
		document.getElementById('thread'+id).className='accordion_toggle';
		actions[id] = 'closed';
													
	// open
	} else {
		document.getElementById('body'+id).style.display='block';
		document.getElementById('thread'+id).className='accordion_toggle_active';
		actions[id] = 'open';
													
	}
												
}

// Newsticker
newsticker = Class.create();
newsticker.prototype = {
	initialize: function()
	{
		// Get elements
		this.interval = 10000;
		this.container = $("newsticker");
		this.messages  = $A(this.container.getElementsByTagName("li"));
		this.number_of_messages = this.messages.length;
		if (this.number_of_messages == 0)
		{
			// this.showError();
			return false;
		}
		this.current_message = 0;
		this.previous_message = null;
		this.hideMessages();
		this.showMessage();
		// Install timer
		this.timer = setInterval(this.showMessage.bind(this), this.interval);
  	},
	showMessage: function()
	{
		Effect.Appear(this.messages[this.current_message]);
		setTimeout(this.fadeMessage.bind(this), this.interval-2000);
		if (this.current_message < this.number_of_messages-1)
		{
			this.previous_message = this.current_message;
			this.current_message = this.current_message + 1;
		} else {
			this.current_message = 0;
			this.previous_message = this.number_of_messages - 1;
		}
	},
	fadeMessage: function()
	{
		Effect.Fade(this.messages[this.previous_message]);
	},
	hideMessages: function()
	{
		this.messages.each(function(message)
		{
			Element.hide(message);
		});
	}
};

Event.observe(window, "load", function(){new newsticker();}, false);

function setNum(id,action,num) {
	
	var currentElement = document.getElementById(id);	
	var currentValue = parseInt(currentElement.value);
	var numValue = parseInt(num);
	
	
	if(action == 'increment') {
		var nextValue = currentValue + numValue;
	} else if (action == 'decrement') {
		var nextValue = currentValue - numValue;
	} else {
		var nextValue = currentValue;
	}

	if (isNaN(nextValue)) nextValue = 1;
	else if(nextValue < 1) nextValue = 1;
	else if (nextValue > 99) nextValue = 99;
		
	currentElement.value = nextValue;
	
	return false;
	
}

function reminder_add(auctionId) {
	new Ajax.Request('/reminders/add/'+auctionId,{method:'post', onComplete:processResponse});
}

function updateWatchlistItem(auctionId) {
    var e = $('wl'+auctionId);
    var src = e.src;
    if (src.search(/unchecked.+/) == -1) {
        var action = 'del';
        e.src = src.replace(/checked/g,"unchecked");
        e.title = 'Zur Watchlist hinzufügen';
    } else {
        var action = 'add';
        e.src = src.replace(/unchecked/g,"checked");
        e.title = 'Aus Watchlist entfernen';
    }
	// if(e == true)
	// 	var action = 'add';
	// else
	// 	var action = 'del';
	// 	
	new Ajax.Request('/watchlists/update/'+auctionId+'/'+action, {method:'post'});
}

window.TipSingleton = {
    timeout: null
};

function fadeInOut(e) {
    var els = $$('.helpBoxWrapper .helpBox');
    els.each(function (ele) {
        if (ele != e) {
            ele.hide();
            // ele.previous().setStyle({'zIndex':''});
        }
    });
    if(e.visible()) {
       e.fade({duration: 0.5});
       window.clearTimeout(TipSingleton.timeout);
    } else {
        window.clearTimeout(TipSingleton.timeout);
        e.appear({duration: 0.5});
        // e.previous().setStyle({'zIndex':'999'});
        TipSingleton.timeout = window.setTimeout(function () {
            e.fade({duration: 0.5});
        }, 10000);
    }
}

function clickableTooltip() {
    var zIndex = 1000;
    $$(".helpBoxWrapper .icon").each(function (ele) {
    	ele.appear({duration: 3});
        zIndex = zIndex - 5;
        ele.getOffsetParent().setStyle({'zIndex': zIndex});
        ele.observe('click', function() {
            fadeInOut(ele.next());
        });
    });
}

function clickableUsername() {
    $$(".sidebarHeader span").first().observe('click', function() {
        showUserInfoTip(userName, userId, this);
    });
}

function delayedLoading() {
    var agt = navigator.userAgent.toLowerCase();
    var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    if(is_ie) {
        $$(".header h1").each(function (element) {
            element.observe('click', function () {
                window.location = "/";
            });
        });
        $$(".innerBox .countdown, .productImage img").each(function (element) {
            element.style.display = 'block';
        });
    }
}

//Event.observe(window, "load", updateUserData, false);
Event.observe(window, "load", function() {
    setInterval(updateClock, "1000");
    clickableUsername();
    clickableTooltip();
}, false);
document.observe("dom:loaded", function() {
   setTimeout(delayedLoading,1);
});
//Event.observe(window, "load", function(){new enableTooltips()}, false);
//Event.observe(window, "load", updateClock, false);
