if (typeof(console) == 'undefined') {console = {};console.debug = alert;}

$('otherSizesToggler').observe('click', function (event) {
    event.stop();
    $('widthHeightContainer').toggle();
});

$('objectWidth').observe('change', calculatePrice);
$('objectWidth').observe('keyup', calculatePrice);
$('objectHeight').observe('change', calculatePrice);
$('objectHeight').observe('keyup', calculatePrice);
$('framedContainer').observe('click', calculatePrice);
$('cuttingModelsContainer').observe('click', calculatePrice);

$('orderLink').observe('click', function (event) {
  event.stop();
  $('formPreOrder').submit();
});

Event.observe(document, 'dom:loaded', calculatePrice);

$$('a.thumb-elements').invoke('observe', 'click', function (event) {
    event.stop();

    var iEle = $('dummyImage');
    if (! iEle) {
        iEle = new Element('img', {id: 'dummyImage'}).setStyle({display:'none'});
        document.body.appendChild(iEle);
    }

    iEle.stopObserving();
    iEle.src = event.element().up().href;

    if (iEle.complete) {
        $('largeImage').src = iEle.src;
        loadInfo();
        window.scrollTo(0, 0);
    } else {
        iEle.observe('load', aThumbOnClick);
    }
});

function aThumbOnClick(event) {
    event.stop();
    var iEle = $('dummyImage');
    iEle.stopObserving();

    $('largeImage').src = iEle.src;
    loadInfo();
    window.scrollTo(0, 0);
}

function loadInfo() {
    var code = $('largeImage').src.replace(/^.+\//, '').replace(/\..+$/, '');
    new Ajax.Request(CFG.base_url + '/read_info.php', {
        method: 'get',
        parameters: {code: code},
        onComplete: function (transport) {
            infoToHTML(transport.responseXML, code);
        }
    });
}

function infoToHTML(domResponse, code) {
    var id = getPathFirstElement(domResponse, "/item/id");
    //~ $('informationId').update(id);

    $('productId').value = code;
    $('informationName').update(getPathFirstElement(domResponse, "/item/name"));
    $('informationInfo').update(getPathFirstElement(domResponse, "/item/info"));

    $('coeficientA').value = getPathFirstElement(domResponse, "/item/coeficients/a");
    $('coeficientB').value = getPathFirstElement(domResponse, "/item/coeficients/b");
    $('coeficientC').value = getPathFirstElement(domResponse, "/item/coeficients/c");
    $('coeficientD').value = getPathFirstElement(domResponse, "/item/coeficients/d");
    $('objectWidth').value = getPathFirstElement(domResponse, "/item/defaultwidth");
    $('objectHeight').value = getPathFirstElement(domResponse, "/item/defaultheight");

    $('defaultwidth').update(getPathFirstElement(domResponse, "/item/defaultwidth"));
    $('defaultheight').update(getPathFirstElement(domResponse, "/item/defaultheight"));

    $('cuttingModelsContainer').descendants().invoke('stopObserving');
    $('cuttingModelsContainer').descendants().invoke('remove');

    buildCuttingElements(domResponse);
    calculatePrice();
}

function getPathFirstElement(xml, path) {
    var nodes = null;
    if (window.ActiveXObject) {
        nodes = xml.selectNodes(path);
        return nodes[0].childNodes[0].nodeValue;
    } else if (document.implementation && document.implementation.createDocument) {
        try {
            nodes = document.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
        } catch (e) {
            try {
                nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
            } catch (e) {
                return null;
            }
        }

        var result = nodes.iterateNext();
        return result.childNodes[0].nodeValue;
    }
}

function buildCuttingElements(xml)
{
    var path = '/item/cuttingmodels/model';
    var nodes = null;
    var id = null;

    if (window.ActiveXObject) {
        nodes = xml.selectNodes(path);
        for (var iterator = 0; iterator < nodes.length; iterator++) {
            id = nodes[iterator].childNodes[0].nodeValue;
            $('cuttingModelsContainer').insert(buildCuttingElement(id));
        }
    } else if (document.implementation && document.implementation.createDocument) {
        try {
            nodes = document.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
        } catch (e) {
            try {
                nodes = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
            } catch (e) {
                return;
            }
        }
        var iterator = 0;
        while ((result = nodes.iterateNext())) {
            id = result.childNodes[0].nodeValue;
            $('cuttingModelsContainer').insert(buildCuttingElement(id));
            iterator++;
        }
    }

    $('cuttingModelsContainer').select('input[type=radio]').first().checked = true;
}


function buildCuttingElement(id) {
    var container = new Element('div', {id: 'cuttingModels' + id + 'Container'});
    var label = new Element('label').writeAttribute('for', 'cuttingModels' + id).insert(new Element('img', {src: CFG.base_url + '/image/cutting_models/' + id + '.gif'}));
    var radio = new Element('input', {id:'cuttingModels' + id, type: 'radio', name: 'cutting_model', value: id});
    container.insert(label).insert(new Element('br')).insert(radio);
    return container;
}


function calculatePrice()
{
    var width = Math.abs(parseInt($('objectWidth').value, 10));
    var height = Math.abs(parseInt($('objectHeight').value, 10));
    var coeficientA = parseInt($('coeficientA').value, 10);
    var coeficientB = parseInt($('coeficientB').value, 10);
    var coeficientC = parseInt($('coeficientC').value, 10);
    var coeficientD = parseInt($('coeficientD').value, 10);

    var cutMethod = null;
    $A($('formPreOrder').elements['cutting_model']).each(function (item) {
        if (item.checked) {
            cutMethod = item.value;
        }
    });

    var price = ((width * height) / 10000) * coeficientA;
    if ((width * height) / 10000 < 1) {
        price = price * (1 / Math.pow((width * height) / 10000,0.33));
        }
    if ($('framedYes').checked) {
        var p2 = (2 * (width + height) / 100) * coeficientB;
        price = price + p2;
    }
    if (cutMethod != 1) {
        if ($('framedYes').checked) {price = (price * (100 + coeficientC)) / 100; } else {price = (price * (100 + coeficientD)) / 100; };
    }

    precision = 2;
    price = Math.round(price * Math.pow(10, precision)) / Math.pow(10, precision);
    if (isNaN(price)) {
      price = 'Ati introdus valori invalide.';
    }

    $('informationPrice').update(price);
    $('priceInput').value = price;
}
