
/**
 * TileList
 * @constructor
 */
function TileList(parentElem, priceElem, countElem) {
    this.parentElem = parentElem;
    this.priceElem = priceElem;
    this.countElem = countElem;
    this.elements = {};
    this.totalPrice = 0.00;
    this.tileMap = null;
    this.elementCount = 0;
    this.orderTilesLink = document.getElementById
}

TileList.prototype.add = function(tile) {
    var me = this;
    if (tile.id in this.elements) {
        return false;
    }
    var li = document.createElement('li');
    var text = document.createElement('input');
    var label = document.createElement('label');
    var price = document.createElement('span');
    var remove = document.createElement('a');
    remove.appendChild(document.createTextNode('x'));
    remove.className = 'removeTile';
    var tileName = tile.id;

    pDomApi.addEvent(remove, 'click', function () { me.tileMap.removeTile(tileName); });

    label.className = 'item';
    label.appendChild(document.createTextNode(tile.num + '.'));

    text.className = 'text';    // because of IE we set classname like this
    text.setAttribute('type', 'text');
    text.setAttribute('name', 'tiles['+tile.id+']');
    text.setAttribute('value', (('name' in tile) && (tile.name!='_empty_tilename_')) ? tile.name : '');
    text.setAttribute('maxlength', 50);
    text.onblur = function () { tileList.ajaxUpdate(); }

    price.className = 'price';
    price.appendChild(document.createTextNode('\u20AC '));
    price.appendChild(document.createTextNode(tile.price));
    price.appendChild(remove);
    this.totalPrice = parseFloat(tile.totalprice);  // received from the server

    li.appendChild(label);
    li.appendChild(price);
    li.appendChild(text);
    this.parentElem.appendChild(li);

    this.elements[tile.id] = {
        element: li,
        price: tile.price,
        priceElem: price
    };
    ++this.elementCount;

    this.updateTotalPrice();

    return true;
};

TileList.prototype.remove = function(tile) {
    var found = false;
    var lastPrice = 0, currentPrice = 0;
    if (tile.id in this.elements) {
        for(var id in this.elements) {
            if (id == tile.id) {
                found = true;
            }
            if (found) {
                // tile to be removed has been found
                currentPrice = this.elements[id].price;
                this.elements[id].price = lastPrice;
                this.elements[id].priceElem.replaceChild(document.createTextNode(lastPrice),
                    this.elements[id].priceElem.childNodes[1]);
                lastPrice = currentPrice;
            }
        }
        this.totalPrice -= parseFloat(lastPrice);
        this.elements[tile.id].element.parentNode.removeChild(this.elements[tile.id].element);
        delete(this.elements[tile.id]);
        --this.elementCount;

        this.updateTotalPrice();

    }
};

TileList.prototype.clearList = function() {

    var lastPrice = 0, currentPrice = 0;
    for(var id in this.elements) {
        // tile to be removed has been found
        currentPrice = this.elements[id].price;
        this.elements[id].price = lastPrice;
        this.elements[id].priceElem.replaceChild(document.createTextNode(lastPrice),
            this.elements[id].priceElem.childNodes[1]);
        lastPrice = currentPrice;

	    this.totalPrice -= parseFloat(lastPrice);
	    this.elements[id].element.parentNode.removeChild(this.elements[id].element);
	    delete(this.elements[id]);
	    --this.elementCount;
    }

    this.updateTotalPrice();
}

TileList.prototype.ajaxUpdate = function() {

    ulTileList = document.getElementById('tileList');

	if (ulTileList!=undefined) {
        tiles = ulTileList.getElementsByTagName('input');
    } else {
      return false;
    }

	params = Array();
	for (var i=0; i<tiles.length; i++) {
	  params[tiles[i].name] = tiles[i].value;
	}


    // make ajaxCall to /portal/order/saveSelection.cmd
    AjaxRequest.post(
    {
      'url':'/'+projectUrl+'/portal/order/saveSelection.cmd',
      'parameters':params,
      'ajaxCall':'1',
      'onSuccess':function(req){ return true; /*console.log('Success!');*/ },
      'onError':function(req){ return false; /* console.log('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);*/ }
    });
};
/**
 * Updates the total price field.
 */
TileList.prototype.updateTotalPrice = function() {
    this.priceElem.replaceChild(document.createTextNode(this.totalPrice.toFixed(2)),
        this.priceElem.childNodes[0]);
    this.countElem.replaceChild(document.createTextNode(this.elementCount),
        this.countElem.childNodes[0]);
};

function tileSelected(tile) {
	
	if (tile.constructor == Array ) {
    	for (var i=0; i< tile.length; i++) {
    	    tileList.add(tile[i]);
    	}
    } else {
        tileList.add(tile);
    }
    tileList.ajaxUpdate();
}

function tileDeselected(tile) {
	if (tile==undefined) { tileList.clearList(); }
	else { tileList.remove(tile); }
    tileList.ajaxUpdate();
}

// setup event handlers to load/unload the map.
pDomApi.addEvent(window, 'domload', function() {
	var tileElem = document.getElementById('selectedItems');
	var tileListElem = document.createElement('ul');
	tileListElem.setAttribute('id', 'tileList');
	tileElem.appendChild(tileListElem);
    tileList = new TileList(tileListElem,
        document.getElementById('tileListPrice'),
        document.getElementById('totalTiles'));

    var tileMap = new TileMap('mapSelection', 480, 460);
    if (tileMap.initialize('selection')) {
        tileMap.tileHosts = hosts;
        tileMap.start();

        tileList.tileMap = tileMap;
        GEvent.addListener(tileMap, 'tileselected', tileSelected);
        GEvent.addListener(tileMap, 'tiledeselected', tileDeselected);
        // load (default) selection
        tileMap.loadSelection(tileSelection);
        tileMap.loadInactiveSelection(inactiveSelection);
        pDomApi.addEvent('clearSelection', 'click', function(e) {tileMap.clearSelection(); });
        pDomApi.addEvent('confirmSelection', 'click', function(e) {
            if (! e) { var e = window.event; }
            var elem = e.target ? e.target : e.srcElement;

            while (elem.tagName.toLowerCase() != 'form') {
                elem = elem.parentNode;
            }
            elem.submit();
            pDomApi.preventDefault(e);  // IE still wants to follow the link after form submission
         });
    }

});

pDomApi.addEvent(window, 'unload', function() {	GUnload(); });

var tileList;
translation.lbl_tile = 'Parcel ';
