var mapcontainer;
var mapdata;
var disallowed;
var mapsettings;
var selectedmodule;
var calculation = new Object;

function init_map() {
	mapcontainer = $('map');
	if (mapcontainer && mapdata.data.length > 0) {
		var mapId = mapcontainer.firstDescendant().id.substring(6);
		mapcontainer.update();
		mapcontainer.maptitle = new Element('h4', {id: 'moduleTitle'});
		mapcontainer.mapdescription = new Element('div', {'class': 'moduleDescription'});
		mapcontainer.mapelement = new Element('div', { id: "map_" + mapId, 'class': 'mapdisplay' });
		var container = new Element('div', {'class': 'controlcontainer'});
		var suggestmodule = new Element('div', { id: "suggestmodule", 'class': 'breaker' });
		var suggestform = new Element('form', { id:'suggestform', action: '#' });
		suggestform.insert(new Element('span').update('Bel&oslash;p:'));
		suggestform.insert(new Element('input', { id: 'price_input' }));
		var suggestbtn = new Element('input', {type: 'submit', value: 'Finn modul!', id: 'suggest_btn' });
		Event.observe(suggestform, 'submit', doSuggest, false);
		//suggestform.observe('submit', function() { doSuggest; });
		suggestform.insert(suggestbtn);
		suggestmodule.insert(suggestform);
		suggestmodule.insert(new Element('div', { id: 'suggest_info' }));
		mapcontainer.controlelement = new Element('div', { id: "control_" + mapId, 'class': 'mapcontrol' });
		mapcontainer.calculationelement = new Element('div', { id: "calculation_" + mapId, 'class': 'mapcalculation' }).hide();
		container.insert(mapcontainer.controlelement).insert(mapcontainer.calculationelement);
		mapcontainer.insert(mapcontainer.maptitle)
			.insert(mapcontainer.mapdescription)
			.insert(mapcontainer.mapelement)
			.insert(container)
			.insert(suggestmodule);
		
		mapsettings = mapdata;
		mapcontainer.controlelement.insert(buildControlPanel(mapsettings));
		setMap(mapId);
	}
}
function doSuggest(e) {
	Event.stop(e);
	var price = $('price_input').value;
	var suggestinfo = $('suggest_info');
	if(Number(price) < Number(mapdata.baseprice)) {
		suggestinfo.update('<span style="color: red;">Tast inn bel&oslash;p st&oslash;rre enn basispris kr ' + mapdata.baseprice + ',-.</span>');
	}
	else {
	
	var modules = Math.floor(price / mapdata.baseprice);
	var countA = new Array();
	$$('.maptable td').each(function (td) {
		var m = new Array();
		m.push(td.modulename);
		m.push(td.modulecount);
		m.push(td.id);
		countA.push(m);
		
  });
	countA.sort(sortvalue);
  countA.reverse();
	var output = "";
	var hitA = new Array();
	var hit;
	var first = true;
	
	for (var i=0; i<countA.length; i++) {
		if(countA[i][1] <= modules){
			if(first){ hit = countA[i][1]; }	
			if(hit==countA[i][1]) {
				hitA.push(countA[i]);
			}else {
				break;	
			}
			hit = countA[i][1];
			first = false;
		}
	}
	var firstTd = $(hitA[0][2]);
	var info = 'Aktuelle moduler: ';
	for (var i=0; i<hitA.length; i++) {
		if(i==hitA.length-1) {
			info += hitA[i][0] + ".";
		}
		else if(i==hitA.length-2) {
			info += hitA[i][0] + " og ";
		}
		else {
			info += hitA[i][0] + ", ";
		}
	}
	suggestinfo.update(info);
	setModule(firstTd);
	}
}
function sortvalue(a,b) {
	a = a[1];
	b = b[1];
	return a == b ? 0 : (a < b ? -1 : 1)
}
function buildControlPanel(settings) {
    form = new Element('form');
    form.insert(new Element('label', { 'for': mapcontainer.controlelement.id + '_mapselect' }).update('Plassering'));
    form.insert(new Element('br'));
    select = new Element('select', { id: mapcontainer.controlelement.id + '_mapselect', 'class': 'mapselect' });
    for (mapno = 0; mapno < settings.data.length; mapno++) {
        mapinstance = settings.data[mapno];
        select.insert(new Element('option', { value: mapinstance.id}).update(mapinstance.name));
    }
    select.observe('change', function() { setMap($F(select)) });
    form.insert(select);
    
    extrafieldset = new Element('fieldset', { id: mapcontainer.controlelement.id + '_extras'});
    /*extrafieldset.insert(new Element('legend').update('Tillegg'));*/
    form.insert(extrafieldset);
    return form;
}

function buildExtraList() {
    extralist = new Element('ul', { 'class': 'extras' });
    var extraCount = !!mapdata.extras.length ? mapdata.extras.length : 0;

		for (extrano = 0; extrano < extraCount; extrano++) {
    	extrali = new Element('li');
      extra = mapdata.extras[extrano];
      extraid = extrafieldset.id + '_' + extra.name;
      switch(extra.category) {
        case 'fast_flatt':
          extraelement = new Element('input',  { id: extraid, type: 'checkbox', value: true, 'class': 'extraelement', disabled: 'disabled', 'checked': 'checked', 'defaultChecked': 'true' });
          break;
        default:
          extraelement = new Element('input',  { id: extraid, type: 'checkbox', value: true, 'class': 'extraelement' });
          break;
      }
      extrali.insert(extraelement);
      extrali.insert(new Element('label', { id: extraelement.id + '_label', 'for': extraelement.id }).update(extra.name));                
      extraelement.ExtraData = extra;
      extraelement.observe('click', function() { doCalculation(); });

			extralist.insert(extrali);
    }
    return extralist;
}

function buildMap() {
    maptable = new Element('table', { 'class': 'maptable', cellspacing: 0, cellpadding: 0 });
    /*thead = new Element('thead');*/
    /*maptable.insert(new Element('caption').update(mapdata.Name));*/
    /*maptable.insert(thead);*/
    tbody = new Element('tbody');
    rc = 5;
    if(mapdata.map_columns) {
      cc = mapdata.map_columns;
    }
    else {
      cc = mapdata.columns;
    }
    for(var rowno = 0; rowno < rc; rowno++) {
			var r = mapdata["row_" + (rowno+1) + "_split"];
        switch(r) {
            case "1":
                tbody.insert(buildModuleRow("top", cc, rc - rowno)); 
                tbody.insert(buildModuleRow("bottom", cc, rc - rowno)); break;
            default:
                tbody.insert(buildModuleRow("full", cc, rc - rowno)); break;
        }
    }
    maptable.insert(tbody);
    return maptable;
}



function buildModuleRow(rowtype, columncount, row) {
    tr = new Element('tr');
    for(var column = 0; column < columncount; column++) {
        modulename = row.toString() + (columncount - column);
        if (rowtype == 'bottom') modulename = modulename + 'B';
        td = new Element('td', { 
            'class': rowtype, 
            id: mapcontainer.mapelement.id + '_' + modulename 
        }).update(modulename);
        td.modulename = modulename;
        td.row = row;
        td.column = (columncount - column);
        td.ishalf = (rowtype == 'bottom');
        td.dimensionx = Math.round(mapdata.module_width * td.column + mapdata.horisontal_spacing * (td.column - 1));
        td.dimensiony = Math.round(mapdata.module_height * td.row + mapdata.vertical_spacing * (td.row - 1));
        if (rowtype == 'bottom') {
            td.dimensiony = Number(td.dimensiony) - Number(mapdata.module_height) + Number(mapdata.half_module_height);
        }
        td.dimension = td.dimensionx + 'x' + td.dimensiony + ' mm';
				
        td.modulecount = (row - (rowtype == 'bottom' ? 0.5 : 0)) * (columncount - column);
        if (isAllowed(modulename)) {
            td.observe('click', function(e) {
                var module = $(Event.element(e));
                setModule(module);
            });
            td.addClassName('selectable');        
        } else {
            td.addClassName('disallowed');
        }
        tr.insert(td);
    }
    return tr;
}

function setModule(module) {
    selectedmodule = module;
    visualizeModule(selectedmodule);
		mapcontainer.calculationelement.show();
    doCalculation();
}

function visualizeModule(module) {
    $$('.maptable td').each(function (td) { if (td.hasClassName('selected')) td.removeClassName('selected'); });
    $$('.maptable td').each(function (td) { 
        selected = (td.column <= module.column 
            && (td.row < module.row
                || td.row == module.row && 
                    ((module.ishalf == td.ishalf) || !module.ishalf)
                )
            );
        if (selected) td.addClassName('selected'); 
    });
}

function isAllowed(module) {
  if (disallowed) {
  	for (var index = 0, len = disallowed.length; index < len; ++index) {
      if (disallowed[index] == module) return false;
    }
  }
  return true;
}

function doCalculation() {
    mapcontainer.calculationelement.update();
    if (selectedmodule) { // Only calculate if there's a selected module
        calculation.total = mapdata.baseprice * selectedmodule.modulecount;
				if(calculation.total > mapdata.max_price && !!mapdata.max_price) {
					calculation.total = Math.floor(mapdata.max_price);
				}
				else if(calculation.total < mapdata.min_price && !!mapdata.min_price) {
					calculation.total = Math.floor(mapdata.min_price);
				}
        calculationtable = new Element('table', { 'class': 'calculationtable', cellspacing: 0, cellpadding: 0 });
        calculationtbody = new Element('tbody');
        calculationtbody.insert(buildCalculationRow('Modul', selectedmodule.modulename, 'modulename'));
        calculationtbody.insert(buildCalculationRow(mapdata.lang_modulecount, selectedmodule.modulecount, 'modulecount'));
        calculationtbody.insert(buildCalculationRow(mapdata.lang_dimension, selectedmodule.dimension, null));
        calculationtbody.insert(buildCalculationRow(mapdata.lang_total, calculation.total + ',-', null));
        $$('.extraelement').each(function(x) {
            switch(x.tagName.toLowerCase()) {
                case 'select':
                    xdata = x.options[x.selectedIndex].ExtraData;
                    break;
                case 'input':
                    xdata = null;
                    if (x.type == 'checkbox') {
                        if (x.checked) xdata = x.ExtraData;
                    }
                    break;
            }
            xcount = selectedmodule.modulecount;
            if (xdata) { // if we found data about the extras we calculate the cost of this extra
                switch(xdata.category) {
									case 'flatt':
										xsum = Number(xdata.price);
										break;
                  case 'fast_flatt':
										xsum = Number(xdata.price);
										break;
									case 'pr_modul':
										xsum = xcount * xdata.price;
										break;
								}
                // Then make sure we don't exceed cost limits
                if (xdata.max_price > 0 && xsum > xdata.max_price) xsum = Number(xdata.max_price);
                if (xdata.min_price > 0 && xsum < xdata.min_price) xsum = Number(xdata.min_price);
                calculation.total = calculation.total + xsum;
								
                calculationtbody.insert(buildCalculationRow(xdata.name, Math.floor(xsum) + ',-', null));
            }
        })
        calculationtbody.insert(buildCalculationRow('Total', '<strong>kr ' + Math.floor(calculation.total) + ',-</strong>', 'total'));
        calculationtable.insert(calculationtbody);
        mapcontainer.calculationelement.insert(calculationtable);
				mapcontainer.calculationelement.insert(new Element('div').update(new Element('sup').update(mapdata.lang_priceinfo)));
    }
}

function buildCalculationRow(text, price, classname) {
    return new Element('tr', { 'class': classname }).insert(new Element('th').update(text)).insert(new Element('td').update(price))
}
function setMap(mapid) {
	var mapselected = false;
	for (mapno = 0; mapno < mapsettings.data.length; mapno++) {
  	mapinstance = mapsettings.data[mapno];
    if (mapinstance.id == mapid) { mapselected = true; break; }
  }
  if (mapinstance) {
  	selectedmodule = null;
    mapdata = mapinstance;
		disallowed = mapdata.disallow_custom.split(",");
    for (i = 0, len = $(mapcontainer.controlelement.id + '_mapselect').options.length; i < len; i++) {
    	option = $(mapcontainer.controlelement.id + '_mapselect').options[i];
      if (parseInt(option.value) == parseInt(mapid)) { option.selected = true; }
    }
		if (!mapselected) { $(mapcontainer.controlelement.id + '_mapselect').options[i-1].selected = true; }
		var extrasfieldset = $(mapcontainer.controlelement.id + '_extras');
		extrasfieldset.update();
		if(!!mapdata.extras) {
			/*extrasfieldset.insert(new Element('legend', {id:'mapLegend'}).update('Tillegg'));*/
			extrasfieldset.insert(buildExtraList());
		}
    mapcontainer.mapelement.update();
		mapcontainer.maptitle.update(mapdata.name);
		!!mapdata.description ? mapcontainer.mapdescription.update(mapdata.description) : mapcontainer.mapdescription.update("&nbsp;");
    mapcontainer.mapelement.insert(buildMap(mapdata));
		mapcontainer.calculationelement.hide();
    doCalculation();
	}
}
function fixMail(){
	var A_main = $$("#postContent a");
	var A_left = $$("#apiContentLeft a");
	fixObjects(A_main);
	fixObjects(A_left);
}
function fixObjects(obj) {
	for(var i=0;i<obj.length;i++){
		// obfuscate mail where the address is in innerHTML
		var is_mail_inner = obj[i].innerHTML.search(/\(at\)/);
		var is_mail_href = obj[i].href.search(/contact/);
		if(is_mail_inner>0 || is_mail_href>0){
			obj[i].innerHTML = obj[i].innerHTML.replace("(dot)",".").replace("(at)","@");
			var adr = obj[i].href.split("/contact/");
			var mailadr = adr[1].split("+");
			var mailstr = "mailto:" + mailadr[0] + "@" + mailadr[1] + "." + mailadr[2];
			obj[i].href = mailstr;
		}
	}
}
document.observe("dom:loaded", function() {
  init_map();
	fixMail();
});
