/**
 * @author manuel
 */
var INITIAL_MAX_WIDTH = 100;
var INITIAL_MAX_HEIGHT = 100;

var activeObject;


function addImage(path, id, z, price){
    var img = document.createElement('img');
    img.setAttribute('src', path);
    img.setAttribute('class', 'sheetobjects');
    $('#sheetBox').append(img);
    $(img).load(function(){
        var ratio = this.width / this.height;
        if (this.width > INITIAL_MAX_WIDTH) {
            this.width = INITIAL_MAX_WIDTH;
            this.height = Math.round(this.width / ratio);
        }
        if (this.height > INITIAL_MAX_HEIGHT) {
            this.height = INITIAL_MAX_HEIGHT;
            this.width = Math.round(this.height * ratio);
        }
        var sheetBox = document.getElementById('sheetBox');
        var wrapper = $(this).resizable({
            aspectRatio: true,
            resize: function(event, ui){
                var pL = $('#sheetBox').position().left;
                var pR = $(sheetBox).width() + pL;
                var pT = $('#sheetBox').position().top;
                var pB = pT + $(sheetBox).height();
                var ratio = ui.originalSize.width / ui.originalSize.height;
                
                if (pR <= ui.position.left + ui.size.width) {
                    ui.size.width = pR - ui.position.left;
                    ui.size.height = Math.round(ui.size.width / ratio);
                }
                if (pB <= ui.position.top + ui.size.height) {
                    ui.size.height = pB - ui.position.top;
                    ui.size.width = Math.round(ui.size.height * ratio);
                }
                
            }
        }).parent('.ui-wrapper');
        wrapper.draggable({
            containment: 'parent'
        });
        wrapper.css('position', 'absolute');
        wrapper.css('top', $('#sheetBox').position().top);
        wrapper.css('left', $('#sheetBox').position().left);
        wrapper.click(activate);
        wrapper.children('.ui-resizable-handle').each(function(){
            this.style.zIndex = 0;
        });
        $(wrapper).css('z-index', $('#sheetBox').children().length - 1);
        wrapper[0].productId = id;
    });
}

function activate(ev){
    $('#sheetBox').children().each(function(){
        $(this).removeClass("activeSheetObject")
    });
    $(this).addClass("activeSheetObject");
    activeObject = this;
    activateButtons();
    $('#current_pid').html(activeObject.productId);
}

function zPlusObject(){
    var objects = $('#sheetBox').children();
    objects.sort(function(a, b){
        return (a.style.zIndex < b.style.zIndex) ? -1 : (b.style.zIndex < a.style.zIndex ? 1 : 0);
    });
    var i = 0;
    while (objects[i] != activeObject && i < objects.length) {
        i++;
    }
    if (i < objects.length - 1) {
        objects[i] = objects[i + 1];
        objects[i + 1] = activeObject;
        objects[i].style.zIndex = i;
        objects[i + 1].style.zIndex = i + 1;
    }
}

function zMinusObject(){
    var objects = $('#sheetBox').children();
    objects.sort(function(a, b){
        return (a.style.zIndex < b.style.zIndex) ? -1 : (b.style.zIndex < a.style.zIndex ? 1 : 0);
    });
    var i = 0;
    while (objects[i] != activeObject && i < objects.length) {
        i++;
    }
    if (i > 0) {
        objects[i] = objects[i - 1];
        objects[i - 1] = activeObject;
        objects[i].style.zIndex = i;
        objects[i - 1].style.zIndex = i - 1;
    }
}

function deleteObject(){
    var objects = $('#sheetBox').children();
    objects.sort(function(a, b){
        return (a.style.zIndex < b.style.zIndex) ? -1 : (b.style.zIndex < a.style.zIndex ? 1 : 0);
    });
    var i = 0;
    while (objects[i] != activeObject && i < objects.length) {
        i++;
    }
    objects.splice(i, 1);
    document.getElementById('sheetBox').removeChild(activeObject);
    activeObject = null;
    disableButtons();
    
    for (var j = 0; j < objects.length; j++) {
        objects[j].style.zIndex = j;
    }
}


function saveSheet(){
    topleft = $('#sheetBox').position();
    sheet = {
        product_instances_a: new Array(),
        name: "TESTNAME",
        info: "TESTINFO"
    }
    var _items = $('#sheetBox').children();
    for (var i = 0; i < _items.length; i++) {
        var xy = $(_items[i]).position();
        var oneItem = {
            product_id: _items[i].productId,
            product_type: 'Product', //Ändern für UserProducts
            x: xy.left - topleft.left,
            y: xy.top - topleft.top,
            z: _items[i].style.zIndex,
            width: $(_items[i]).width(),
            height: $(_items[i]).height()
        }
        sheet.product_instances_a[i] = oneItem;
    }
     $.post('/sheets', {
	 	sheet: $.toJSON(sheet)
	 },
	 onSheetSaved);
}



///////////// HELPERS //////////////

function activateButtons(){
    $('.objButtons').each(function(){
        this.disabled = false;
    });
}

function disableButtons(){
    $('.objButtons').each(function(){
        this.disabled = true;
    });
}

//////////// CALLBACKS ///////////
function onSheetSaved(data, textStatus) {
	if(textStatus=="success") {
		$('<a href="#sheetSavedPopup">sdf</a>').fancybox({
			'callbackOnClose' : function(){top.location=$.evalJSON(data).location;}
		}).click();
		setTimeout(function(){top.location=$.evalJSON(data).location;},5000);
	}
}
