var originX = 250;
var originY = 138;
var box
var image
var pieces = new Array();
var draggingElement
var IE, iPad
var zIndex
var maxX
var nextX, nextY
var mouseX, mouseY
var time;
var timer;

soundManager.url = '/public/flash/';
soundManager.flashVersion = 9;
soundManager.useHTML5Audio = true;
soundManager.onready(function() {
    soundManager.createSound({
        id: 'put',
        url: '/public/sound/put.mp3',
        autoLoad: true,
        autoPlay: false,
        volume: 100
    });
    soundManager.createSound({
        id: 'success',
        url: '/public/sound/success.mp3',
        autoLoad: true,
        autoPlay: false,
        volume: 100
    });
});

function init() {
    box = $('box');
    image = $('image');
    draggingElement = false;
    IE = document.all ? true : false;
    iPad = /(Android|iPhone|iPad|iPod).+Mobile.+Safari/i.test(navigator.userAgent);
    zIndex = 2;
    maxX = document.body.clientWidth;
    box.style.width = imageWidth + 'px';
    box.style.height = imageHeight + 'px';
    nextX = imageWidth + 25;
    nextY = 0;
    if (!iPad) {
        document.onmousemove = mouseMove;
    }
    disableSelection();
    if (iPad) {
        document.getElementById('previewImage').addEventListener('touchstart', showImage, false);
        document.getElementById('previewImage').addEventListener('touchend', hideImage, false);
    } else {
        document.getElementById('previewImage').onmousedown = showImage;
        document.getElementById('previewImage').onmouseup = hideImage;
        document.getElementById('previewImage').onmouseout = hideImage;
    }
}

function disableSelection() {
    document.onselectstart = new Function('return false');
    document.oncontextmenu = new Function('return false');
    document.onmousedown = function(e){if (e && e.preventDefault) {e.preventDefault();}}
}
function enableSelection() {
    document.onselectstart = new Function('return true');
    document.oncontextmenu = new Function('return true');
    document.onmousedown = new Function('return true'); 
}
	
function showImage() {
    image.style.display = 'block';
}
	
function hideImage() {
    image.style.display = 'none';
}
	
function addPiece(id, left, top) {
    var img = new Image();
    img.id = id;
    img.className = 'piece';
    img.src = dir + id + '.gif';
    img.destLeft = left;
    img.destTop = top;
    img.handleX = 0;
    img.handleY = 0;
    if (iPad) {
        img.addEventListener('touchstart', imageDrag, false);
        img.addEventListener('touchend', imageDrop, false);
        img.addEventListener('touchmove', mouseMove, false);
    } else {
        img.onmousedown = imageDrag;
        img.onmouseup = imageDrop;
    }
    img.onload = setImagePosition;
    img.getLeft = imageGetLeft;
    img.getTop = imageGetTop;
    img.setLeft = imageSetLeft;
    img.setTop = imageSetTop;
    img.setOpacity = imageSetOpacity;
    img.style.zIndex = 1;
    img.fixed = false;
    $('box').appendChild(img);
    pieces.push(img);
}
function imageGetLeft() {
    return parseInt(this.style.left);
}
	
function imageGetTop() {
    return parseInt(this.style.top);
}
	
function imageSetLeft(left) {
    this.style.left = left + 'px';
}
	
function imageSetTop(top) {
    this.style.top = top + 'px';
}
	
function imageSetOpacity(opacity) {
    IE ? this.style.filter = "Alpha(opacity="+parseInt(100*opacity)+")" : this.style.opacity = opacity;
}
function updateTimer() {
    var date = new Date();
    var sec = Math.round((date.getTime() - time) / 1000);
    var min = parseInt(sec / 60);
    sec = sec - min * 60;
    $('time').innerHTML = min + ':' + (sec < 10 ? '0' + sec : sec);
}
	
function imageDrag(e) {
    if (!iPad && draggingElement) {
        return false;
    }
    if (!validButton(e)) {
        return false;
    }
    if (iPad) e.preventDefault();
    if (!time) {
        var date = new Date();
        time = date.getTime();
        timer = setInterval(updateTimer, 1000)
    }
    this.dragging = true;
    if (this.fixed) {
        this.fixed = false;
        updatePiecesLeft(1);
    }
    getMouseXY(e);
    this.handleX = mouseX - this.getLeft();
    this.handleY = mouseY - this.getTop();
    this.style.zIndex = zIndex++;
    this.setOpacity(.8);
    draggingElement = this;
    return false;
}
	
function imageDrop(e) {
    if (!validButton(e)) {
        return false;
    }
    if (!iPad && !draggingElement) {
        return false;
    }
    this.dragging = false;
    if (iPad) e.preventDefault();
    this.setOpacity(1);
        
    if (Math.abs(this.getLeft() - this.destLeft) > 20 || Math.abs(this.getTop() - this.destTop) > 20) {
        this.fixed = false;
        draggingElement = false;
        return false;
    }
    this.setLeft(this.destLeft);
    this.setTop(this.destTop);
    try {
        soundManager.play('put');
    } catch (e) {
    }
    this.fixed = true;
    updatePiecesLeft(-1);
    draggingElement = false;
    return false;
}
	
function setImagePosition() {
    if (nextX + this.width > maxX - 250) {
        nextY += this.height - 10;
        nextX = nextY > imageHeight + 20 ? 0 : imageWidth + 25;
    }
    this.setLeft(nextX);
    this.setTop(nextY);
    nextX += this.width;
}
	
function mouseMove(e) {
    if (iPad) {
        if (!this.dragging) {
            return false;
        }
        e.preventDefault();
        getMouseXY(e);
        this.setLeft(mouseX - this.handleX);
        this.setTop(mouseY - this.handleY);
        return false;
    }

    if (!draggingElement) {
        return false;
    }
    getMouseXY(e);
    draggingElement.setLeft(mouseX - draggingElement.handleX);
    draggingElement.setTop(mouseY - draggingElement.handleY);
    return false;
}
	
function getMouseXY(e) {
    if (iPad) {
        mouseX = e.changedTouches[0].pageX;
        mouseY = e.changedTouches[0].pageY;
        return;
    }
    if (IE) {
        mouseX = event.clientX + document.body.scrollLeft;
        mouseY = event.clientY + document.body.scrollTop;
        return;
    }
    mouseX = e.pageX;
    mouseY = e.pageY;
}
    
function validButton(e) {
    if (iPad) return true;
    var button = IE ? event.button : e.which;
    return button == 1;
}
    
function updatePiecesLeft(delta) {
    var current = parseInt(document.getElementById('piecesLeft').innerHTML);
    document.getElementById('piecesLeft').innerHTML = current + delta;
    if (current + delta == 0) {
	finishGame();
    }
}
function finishGame() {
    var date = new Date();
    new Ajax.Request('/' + lang + '/puzzle/resolve', {
        method: 'post',
        parameters: {id: puzzleId, time: Math.round((date.getTime() - time) / 1000)}
    });
    clearInterval(timer);
    pageTracker._trackPageview("/resolved.html");
    showImage();
    try {
        soundManager.play('success');
    } catch (e) {
    }
    if (iPad) {
        document.getElementById('previewImage').removeEventListener('touchstart', showImage, false);
        document.getElementById('previewImage').removeEventListener('touchend', hideImage, false);
    } else {
        document.getElementById('previewImage').onmousedown = new Function('return false');
        document.getElementById('previewImage').onmouseup = new Function('return false');
        document.getElementById('previewImage').onmouseout = new Function('return false');
    }
    for (var i = 0; i < pieces.length; i++) {
        pieces[i].style.display = 'none';
    }
    $('related').show();
    if ($('solved')) {
        $('solved').innerHTML = parseInt($('solved').innerHTML) + 1;
    } else {
        $('psolved').innerHTML = 'Solved: <span id="solved">1</span>';
    }
}
function description_send() {
    new Ajax.Request('/' + lang + '/puzzle/add_description', {
	method: 'post',
	parameters: {id: puzzleId, title: $F('title'), description: $F('description_text')},
	onSuccess: function(transport) {
	    $('new_description').hide();
	},
	onFailure: function(transport) {
	    alert(transport.responseText);
	}
    });
}