var autoplay = 0;
var singlegroup = 0;
var newbids = 0;

$(function() {
	$(".autofocus").focus();
	$(".header").click(function() {
		document.location.href = "/";
	});
	if ($(".gmap").length > 0) loadGmap();
	initInterface();
	objListener();
	searchListener();
	refreshBasket();
	if ($(".fpitem").length > 0) refreshImage(0);
	$(".showstartbutton").click(function() {
		showObj();
	});
	//fixHeight();
});

function initInterface()
{
	$(".mainmenu li").mouseover(function() {
		$(this).stopTime();
		$(this).siblings("li").children("ul").hide();
		$(this).children("ul").show();
	});
	$(".mainmenu li").mouseout(function() {
		var menuitem = $(this);
		$(this).oneTime(1000, function() {
			menuitem.children("ul").hide();
		});
	});
}

function objListener()
{
	$(".objlink").unbind("click");
	$(".objlink").click(function() {
		var clickid = $(this).attr("id");
		showObj(clickid);
	});
}

function searchListener()
{
	$(".searchform #searchstring").keydown(function(event) {
		if (event.keyCode == 13 && $(this).val()) {
			var url = "/catalogue/" + $(".searchform").attr("id") + "/?searchString=" + $(this).val();
			document.location.href = url;
		} 
	});
	$(".searchform #objid").keydown(function(event) {
		if (event.keyCode == 13 && $(this).val()) {
			var url = "/catalogue/" + $(".searchform").attr("id") + "/" + $(this).val();
			document.location.href = url;
		} 
	});
}

function shopObjListener()
{
	$(".shopobjlink").click(function() {
		var clickid = $(this).attr("id");
		showShopObj(clickid);
	});
}

function showObj(clickid) {
	$(".middlecol").stopTime();
	var dialogwidth = Math.round($(window).width()/1.1);
	var dialogheight = Math.round($(window).height()/1.1);
	var showGroupLink = $(".fpitem").length > 0 ? 1 : 0;
	$.post("/ajax/objinfo", {objid: clickid, width: dialogwidth-20, height: dialogheight - 230, showGroupLink: showGroupLink, isautoplay: autoplay, singlegroup: singlegroup, auctionId: $(".showstartbutton").attr("id").replace(/auction-/, "")}, function(data) {
	    if ($(".objinfodialog").length > 0) {
	    	$(".objinfodialog").html(data);	
	    }
	    else {
	    	$("body").prepend('<div class="dialog objinfodialog" title="Holmasto">' + data + '</div>');
	    	$(".dialog").dialog({
	    		modal: true,
	    		height: dialogheight,
	    		width: dialogwidth,
	    		close: function(event, ui) {
					singlegroup = 0;
	    			$(".dialog").remove();
	    			$(window).unbind("keydown");
					refreshImage(0);
					if ($("div.mybids").length > 0 && newbids) location.reload(true); 
	    		}
	    	});
	    }
		if ($(".mainimage").length > 0) {
			var title = $(".dialog input.title").val();
			if (title) $(".objinfodialog").dialog("option", "title", "HOLMASTO: " + title);
			
			$(".dialog .bottom").css("top", $(".dialog").height() - $(".dialog .bottom").height() + 10);
			$(".dialog .bottom").width($(".dialog").width()-10);
			if ($(".otherimages").length > 0) {
				var otherwidth = parseInt($(".otherimages").css("width"));
				$(".dialog .mainimage").width($(".mainimage").width() - otherwidth - 20);
			}
			$(".dialog .description").width($(".mainimage").width());
			$(".mainimage img").attr("src", $(".mainimage input.imgurl").val()).load(function() {
				fixDescriptionHeight();
				refreshMagnifyPos();
				$(".mainimage img").unbind("load");
			});
			//$(".mainimage div.magnify").css("left");
			refreshObjNavi();	
		}
		else {
			// we show the group choice
			singlegroup = 0;
			$(".dialog .maingroup").unbind("click");
			$(".dialog .maingroup").click(function() {
				var gid = $(this).attr("id").replace(/menu-group-/, "");
				singlegroup = ($(this).parents(".specificgroup").length > 0) ? gid : 0;
				if (gid) {
					$.post("/ajax/getfirstobj", {gid: gid}, function (data) {
						autoplay = 5;
						showObj(data);
					});
				}
			});
		}
	    
	});
}

function refreshMagnifyPos()
{
	var rsize = $(".dialog .mainimage").find("input.realsize").val();
	if (rsize) {
		rsize = rsize.split("x");
		if (parseInt(rsize[0]) > $(".mainimage img").width()) {
			$(".mainimage div.magnify").show();
			var pos = $(".mainimage img").position();
			var newpos = parseInt(pos.left) + 10;
			$(".mainimage div.magnify").css("left", newpos + "px");
			mainimageClickListener();
			return true;
		}
	}
	$(".dialog .mainimage div.magnify").hide();
	$(".dialog .mainimage").unbind("click");
	return false;
}

function showShopObj(clickid) {
	var dialogwidth = Math.round($(window).width()/1.1);
	var dialogheight = Math.round($(window).height()/1.1);
	var showGroupLink = $(".fpitem").length > 0 ? 1 : 0;
	$.post("/ajax/shopobjinfo", {objid: clickid, width: dialogwidth-20, height: dialogheight - 230, showGroupLink: showGroupLink}, function(data) {
	    if ($(".objinfodialog").length > 0) {
	    	$(".objinfodialog").html(data);	
	    }
	    else {
	    	$("body").prepend('<div class="dialog objinfodialog" title="Holmasto">' + data + '</div>');
	    	var title = $(".dialog input.title").val();
	    	if (title) $(".objinfodialog").attr("title", 'HOLMASTO: ' + title);
	    	$(".dialog").dialog({
	    		modal: true,
	    		height: dialogheight,
	    		width: dialogwidth,
	    		close: function(event, ui) {
	    			$(".dialog").remove();
	    			$(window).unbind("keydown");
	    		}
	    	});
	    }
	    
	    $(".dialog .prices").width($(".dialog .description").width());
	    $(".dialog .dialognavi").width($(".dialog .description").width());
	    $(".dialog .bottom").css("top", $(".dialog").height()-$(".dialog .bottom").height());
	    addToBasketListener();
	    refreshShopObjNavi();
	});
}

function refreshObjNavi()
{
	$(".dialog .nextlink").unbind("click");
	$(".dialog .prevlink").unbind("click");
	$(".dialog .otherimage div.image").unbind("click");
	$(".dialog div.description").unbind("click");
	
	$(".dialog .nextlink").click(function() {
		showObj($(this).attr("id"));
	});
	$(".dialog .prevlink").click(function() {
		showObj($(this).attr("id"));
	});
	$(window).unbind("keydown");
	$(window).keydown(function(event) {
		if (event.keyCode == 39) $(".nextobj a").click();
		else if (event.keyCode == 37) $(".prevobj a").click();
  	});
    $(".objinfodialog .controls select").change(function() {
       autoplay = $(this).val();
       $(".objinfodialog").stopTime();
       if (parseInt(autoplay)) startAutoplay();
    });
    if (parseInt(autoplay) > 0) {
        $('.objinfodialog .controls select option[value="'+autoplay+'"]').prop("selected", true);
        startAutoplay();
    }
    $(".objinfodialog select.deliverymethod").change(function() {
        $.post("/ajax/toggledeliverymethod", {newmethod: $(this).val(), objId: $(".newbid").attr("id")});
    });
    $(".objinfodialog .controls .pausebutton input").click(function() {
        if ($(this).val() == 'pause') {
            $(".objinfodialog").stopTime();
            $(this).val('play');
        }
        else {
            startAutoplay();
            $(this).val('pause');
        }
    });
    $(".otherimages div.image").click(function() {
		$(".mainimage, .mainimage div.magnify").show();
    	$(".mainimage").css("overflow", "hidden");
		
    	$(".otherimages div.image").removeClass("activeimage");
    	$(this).addClass("activeimage");
    	var newurl = $(this).find("input.imgurl").val();
		$("div.mainimage input.imgurl").val(newurl);
		$("div.mainimage input.realsize").val($(this).find("input.realsize").val());
    	$("div.mainimage img").attr("src", newurl).load(function() {
			fixDescriptionHeight();
			refreshMagnifyPos();
			$(".mainimage img").unbind("load");
		});
    });
	
	$(".dialog div.description").click(function() {
		if ($(".dialog .mainimage").css("display") == "block")  $(".dialog div.description").css("height", "auto");
		else fixDescriptionHeight();
		$(".dialog .mainimage").slideToggle();
	});
}

function mainimageClickListener()
{
	$(".dialog .mainimage").unbind("click");
	$(".dialog .mainimage").click(function() {
    	$(".mainimage").css("height", $(".mainimage").height()); // what does this even do?
		var url = $(this).find("img").attr("src");
		if (url.indexOf("?original") == -1) {
			// expand!
			$(".dialog div.description").hide();
			$(".mainimage div.magnify").hide();
			$(this).css("overflow", "scroll");
			$("input.originalheight").val($(this).height());
			$(this).css("height", $(".dialog").height() - $(".dialog .bottom").height() - 50);
			var altpic = "";
			if ($(".activeimage").length > 0) altpic = $(".activeimage").attr("id").replace(/alt-/, "");
			var newurl = "/objimage/" + $("input.auctioncode").val() + "/" + $("input.tempid").val() + "/0/0/0/" + altpic + "?original=1";
		}
		else {
			// unexpand!
			$(".mainimage div.magnify").show();
			$(".dialog div.description").show();
			$(this).css("overflow", "hidden");
			$(this).height($("input.originalheight").val());
			var newurl = $("div.mainimage input.imgurl").val();
		}
		$(".mainimage img").attr("src", newurl);
    });
}

function refreshImage(number)
{
	if (!number) number = 0;
	$(".middlecol").oneTime(5000, function() {
		console.log("Loading random item number " + number);
		$.post("/ajax/fpitem", {itemnumber: number, oldid: $(".fpitem").eq(number).find("div.image").attr("id")}, function(data) {
			$(".fpitem").eq(number).replaceWith(data);
			var nextnumber = number+1;
			if (nextnumber >= $(".fpitem").length) nextnumber = 0;
			objListener();
			refreshImage(nextnumber);
		});
	});
}

function fixDescriptionHeight()
{
	var h = $(".dialog").height() - $(".mainimage").height() - $("div.bottom").height();
	if ($(".dialog div.description").height() > h) {
		$(".dialog div.description").height(h);
		$(".dialog div.readmore").show();
	}
	else $(".dialog div.readmore").hide(); 
}

function startAutoplay()
{
    if (parseInt(autoplay) > 0) {
       $(".objinfodialog .controls .pausebutton").show();
       $(".objinfodialog").oneTime(autoplay * 1000, function() {
            $(".objinfodialog .nextobj a").click();
       });
    }
}

function fixHeight()
{
	var newheight = $(document).height()-$(".footer").height()-50;
	if ($(".container").height() < newheight) {
		$(".container").height(newheight);
		var newmiddleheight = $(".container").height() - $(".header").height()-$(".footer").height()-100;
		if ($(".container .middlecol").height() < newmiddleheight) $(".container .middlecol").height(newmiddleheight);
	}
}

function loadGmap()
{
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("gmap"));
		var center = new GLatLng(60.197329,24.94935);
		map.setCenter(center, 15);
		map.addOverlay(new GMarker(center));
		map.addControl(new GSmallMapControl());
	}
}

function enterBid()
{
	var bidamount = $(".newbid").val();
	var previousbid = parseInt($(".previousbid").val());
	var objid = $(".newbid").attr("id");
	if (!checkInteger(bidamount) || !bidamount) alert($(".onlynumberserror").val());
	else if (previousbid >= parseInt(bidamount)) alert($(".toolowerror").val());
    else if ($("select.deliverymethod option:selected").val() == 0) alert($(".deliveryerror").val());
	else {
		if (confirm($(".confirmstring").val())) {
			$.post("/ajax/checkbid", {objid: objid, bidamount: bidamount}, function() {
				showObj(objid);
				newbids = 1;
			});
		}	
	}
}

function refreshBasket()
{
    $(".shoppingbasket").load("/ajax/shoppingbasket", {}, function() {
    	shopObjListener();
    });
}

function checkInteger(str)
{
	var allowedchars = "0123456789";
	var isNumber = true;
	var chr;
	for (i = 0; i < str.length && isNumber == true; i++) {
		chr = str.charAt(i); 
		if (allowedchars.indexOf(chr) == -1) isNumber = false;
	}
	return isNumber;
}
