$(document).ready(function() {
	
    $('#imageframe').cycle({
        timeout: 5000,
		next: '.next',
		prev: '.prev',
		pause: 1,
    });
	
	$("#imagescroller").mouseenter(function() {
		var currentid = checkCurrentStatus();
		updateProperty(currentid);
		$(".prev").fadeIn("fast");
		$(".next").fadeIn("fast");
		$(".infobox").fadeIn("fast");
	}).mouseleave(function() {
		$(".prev").fadeOut();
		$(".next").fadeOut();
		$(".infobox").fadeOut();
		$(".infobox").html("");
	});

    $(".prev").click(function() {
        var currentid = checkCurrentStatus();
        currentid = currentid + 1;
        var top = $("#imageframe a").size();
        var goIndex = getPrevSlide(currentid, top);
        updateProperty(goIndex);
    });

    $(".next").click(function() {
        var currentid = checkCurrentStatus();
        currentid = currentid -1;
        var top = $("#imageframe a").size();
        var goIndex = getNextSlide(currentid, top);
        updateProperty(goIndex);
    });



});

function getPrevSlide(num, top) {
	var prevnum = (num-1);
	if (prevnum < 1) {
		return top;
	} else {
		return prevnum;
	}
}

function getNextSlide(num, top) {
	var nextnum = (num+1);
	if (nextnum > top) {
		return 1;
	} else {
		return nextnum;
	}
}

function updateProperty(id) {
    var address = $('#imageframe a:nth-child('+id+')').metadata({type: 'attr', name: 'data'}).address;
	var price = $('#imageframe a:nth-child('+id+')').metadata({type: 'attr', name: 'data'}).price;
	var href = $('#imageframe a:nth-child('+id+')').attr("href");
	$(".infobox").parent().attr("href", href);
	$(".infobox").html("<p><strong>Address: </strong>"+address+"</p><p><strong>Price:</strong> "+price+"</p>");
}

function getCurIndex (whichz) {
	imglen = $("#imageframe a").size();
	i=0;

	while (i < imglen) {
		var nchild = (i+1);
		var currimg = parseInt($("#imageframe a:nth-child("+nchild+")").css("z-index"));
		if (currimg == whichz) {
			return (i+1);
		} else {
			i++;
		}
	}
}

function checkCurrentStatus() {
	// count number of images
	imglen = $("#imageframe a").size();
	i=0;
	var zin = new Array();
	while (i < imglen) {
		var nchild = (i+1);
		zin[i] = parseInt($("#imageframe a:nth-child("+nchild+")").css("z-index"));
		i++;
	}
	var max_zindex = Math.max.apply(null, zin);
	var output = getCurIndex(max_zindex);
	return output;
}

