// func.js

var current_taxes = [];
var availObj = document.getElementById('product_avail');

/*
    Math.round() wrapper
*/
function round(n, p) {
    if (isNaN(n))
        n = parseFloat(n);
    if (!p || isNaN(p))
        return Math.round(n);
    p = Math.pow(10, p);
    return Math.round(n*p)/p;
}

/*
    Price format
*/
function price_format(price, thousand_delim, decimal_delim, precision) {
    var thousand_delim = (arguments.length > 1 && thousand_delim !== false) ? thousand_delim : '';
    var decimal_delim = (arguments.length > 2 && decimal_delim !== false) ? decimal_delim : '.';
    var precision = (arguments.length > 3 && precision !== false) ? precision : '2';

    if (precision > 0) {
        precision = Math.pow(10, precision);
        price = Math.round(price*precision)/precision;
        var top = Math.floor(price);
        var bottom = Math.round((price-top)*precision)+precision;

    } else {
        var top = Math.round(price);
        var bottom = 0;
    }

    top = top+"";
    bottom = bottom+"";
    var cnt = 0;
    for (var x = top.length; x >= 0; x--) {
        if (cnt % 3 == 0 && cnt > 0 && x > 0)
            top = top.substr(0, x)+thousand_delim+top.substr(x, top.length);

        cnt++;
    }

    return (bottom > 0) ? (top+decimal_delim+bottom.substr(1, bottom.length)) : top;
}


/*
    Rebuild page if some options is changed
*/ 
function check_options(ind_opt) {


    var variantid = false;
    var local_taxes = [];

    price = default_price;

    ages = 0;
    for(i in names)
        if(names[i]["class_type"]=="age") {
            ages = i;
            break;
        }

    if (ind_opt == -15) {main_opt = 0; ind_opt=0;}
    if (ind_opt)
    {
        if (ind_opt == count_opts) main_opt = ind_opt;
        else
            for(i in opts)
                if (opts[i] && ind_opt==i && i<count_opts)
                {
                    if (document.getElementById('po'+opts[i]['classid']).value != -100) i++;
                    main_opt = i;
                    break;
                }   
        main_index = opts[main_opt]['orderby'];
        main_classid = opts[main_opt]['classid'];
        ind_orderby = opts[ind_opt]['orderby'];
        ind_classid = opts[ind_opt]['classid'];
        if (ind_opt < count_opts)
            for(i in opts)
            if (i >= main_opt && opts[i] && opts[i]['classid']) 
            {
                sec  = document.getElementById('sc'+i);
        if(sec)
            sec.style.display = 'none';
                slct = document.getElementById('po'+opts[i]['classid']);
        slct.disabled=true;
        slct.options.length=0;
        slct.options[slct.options.length] = new Option("...","-100");
/*
                if (ages)
                for(j in names[ages]['options'])
                        if (document.getElementById('po'+ages+'_'+j))
                document.getElementById('po'+ages+'_'+j).disabled=true;
*/
            }
        if (main_opt <= count_opts)
        {
            var k=0;
            var mini_variants = [];
            for(i in variants)
            {
                var flag=1;
                for(j in names)
        {
            po = document.getElementById('po'+j);
            if (po && !modifiers[j])
            if (!po.disabled && po.value !=-100 && !(variants[i][1] && variants[i][1][j] == po.value ))
                flag=0;
        }

                if (flag)
        {
            mini_variants[k] = i;
            k++;
        }
            }
    slct = document.getElementById('po'+main_classid);
    if(slct.value == -100)
	{
        slct.options.length=0;
        slct.options[slct.options.length] = new Option("...","-100");
            for(i in names[main_classid]['options'])
            {
                if (names[main_classid]['options'][i])
                {
                    variants_prices_not_null = 0;
                    for(var j in mini_variants) {
                        if (variants[mini_variants[j]] && variants[mini_variants[j]][1])
                            if (variants[mini_variants[j]][1][main_classid] == i && variants[mini_variants[j]][0][0] >0)
                {variants_prices_not_null++;break;}
                        }
        if (variants_prices_not_null)
            slct.options[slct.options.length] = new Option(names[main_classid]['options'][i],i);
                }
            }
}
        }
        if (document.getElementById('po'+main_classid))
            document.getElementById('po'+main_classid).disabled=false;
    if(document.getElementById('sc'+main_opt))
        document.getElementById('sc'+main_opt).style.display = '';
        if (main_opt == count_opts && document.getElementById('po'+main_classid).value !=-100 ) main_opt++;
        if (document.getElementById('price_detail'))
            if (main_opt > count_opts)
            {        
                document.getElementById('price_detail').style.visibility="visible";
                document.getElementById('submithref').style.display="";
                if (ages)
                    for(j in names[ages]['options'])
                        if (document.getElementById('po'+ages+'_'+j)) document.getElementById('po'+ages+'_'+j).disabled=false;
            }
            else 
            {
                document.getElementById('price_detail').style.visibility="hidden";
                document.getElementById('submithref').style.display="none";
                if (ages)
                    for(j in names[ages]['options'])
                        if (document.getElementById('po'+ages+'_'+j)) document.getElementById('po'+ages+'_'+j).disabled=true;
            }
    }

    tmprice = price;
    tprice = 0;
cycl = ages ? names[ages]["options"] : [0] ;
for(zz in cycl)
if(zz*1==zz)
{
    /* Find variant */
    if (variants.length>0){
    for (var x in variants) {
        if (variants[x][1]){
        if (variants[x][1].length == 0)
            continue;

        variantid = x;
        for (var c in variants[x][1]) {
            if(ages==c && zz==variants[x][1][c])
        continue;
            else if (getPOValue(c) != variants[x][1][c]) {
                variantid = false;
                break;
            }
        }

        if (variantid)
            break;
    }
    }
    }
    /* If variant found ... */
    if (variantid) {
        price = variants[variantid][0][0];
        orig_price = variants[variantid][0][1];
        avail = 100;

    if(price>0);
    else // exceptions
    if (ages && (names[ages]['options'][variants[variantid][1][ages]].toUpperCase() == "ADULTO" || names[ages]['options'][variants[variantid][1][ages]].toUpperCase() == "ADULT"))
    {
        if (document.getElementById('product_price'))
            document.getElementById('product_price').innerHTML = err_unavalable_combination;
        return false;
    }
    }
    else if(!ages)
        price = tmprice;

    /* Find modifiers */
    var _tmp = modi_price(price, local_taxes, orig_price);

    if(ages)
        tprice += _tmp[0]*getPOValue(ages+'_'+zz);
    else
        price = _tmp[0];
// alert('price=' + _tmp[0] + '; amnt = ' +getPOValue(ages+'_'+zz));
}

    if(ages)
        price = tprice;

    if (!availObj)
        availObj = document.getElementById('product_avail');

    if(availObj)
	price *= availObj.value;

    /* Update form elements */
    /* Update price */
    if (document.getElementById('product_price'))
        document.getElementById('product_price').innerHTML = price_format(price < 0 ? 0 : price) + " EUR";

/*
    // Update product quantity
    if (document.getElementById('product_avail_txt')) {
        if (avail > 0) {
            document.getElementById('product_avail_txt').innerHTML = substitute(txt_items_available, "items", (variantid ? avail : product_avail));
        } else {
            document.getElementById('product_avail_txt').innerHTML = lbl_no_items_available;
        }
    }

    var select_avail = min_avail;
    // Update product quantity selector
    if (!availObj)
        availObj = document.getElementById('product_avail');

    if (availObj && availObj.tagName.toUpperCase() == 'SELECT') {
        if (!isNaN(min_avail) && !isNaN(avail)) {
            var first_value = -1;
            if (availObj.options[0])
                first_value = availObj.options[0].value;

            if (first_value == min_avail) {

                // New and old first value in quantities list is equal
                if ((avail-min_avail+1) != availObj.options.length) {
                    if (availObj.options.length > avail) {
                        var cnt = availObj.options.length;
                        for (var x = (avail < 0 ? 0 : avail); x < cnt; x++)
                            availObj.options[availObj.options.length-1] = null;
                    } else {
                        var cnt = availObj.options.length;
                        for (var x = cnt+1; x <= avail; x++)
                            availObj.options[cnt++] = new Option(x, x);
                    }
                }
            } else {

                // New and old first value in quantities list is differ
                while (availObj.options.length > 0)
                    availObj.options[0] = null;
                var cnt = 0;
                for (var x = min_avail; x <= avail; x++)
                    availObj.options[cnt++] = new Option(x, x);
            }
            if (availObj.options.length == 0)
                availObj.options[0] = new Option(txt_out_of_stock, 0);
        }
        select_avail = availObj.options[availObj.selectedIndex].value;
    }

    if ((alert_msg == 'Y') && (min_avail > avail))
        alert(txt_out_of_stock);
*/

    return true;
}

/*
    Calculate product price with price modificators
*/
function modi_price(_price, _taxes, _orig_price) {
var return_price = round(_price, 2);

    /* List modificators */
    for (var x2 in modifiers) {
        var value = getPOValue(x2);
        if (!value || !modifiers[x2][value])
            continue;

        /* Get selected option */
        var elm = modifiers[x2][value];
        return_price += parseFloat(elm[1] == '$' ? elm[0] : (_price*elm[0]/100));

    }

    return [return_price, _taxes];
}


/*
    Get product option value
*/
function getPOValue(c) {
    if (!document.getElementById('po'+c) || document.getElementById('po'+c).tagName.toUpperCase() != 'SELECT')
        return false;
    return document.getElementById('po'+c).options[document.getElementById('po'+c).selectedIndex].value;
}

/*
    Get product option object by class name / class id
*/
function product_option(classid) {
    if (!isNaN(classid))
         return document.getElementById("po"+classid);

    if (!names)
        return false;

    for (var x in names) {
        if (names[x]['class_name'] != classid)
            continue;
        return document.getElementById('po'+x);
    }

    return false;
}

/*
    Get product option value by class name / or class id
*/
function product_option_value(classid) {
    var obj = product_option(classid);
    if (!obj)
        return false;

    if (obj.type != 'select-one')
        return obj.value;

    var classid = parseInt(obj.id.substr(2));
    var optionid = parseInt(obj.options[obj.selectedIndex].value);
    if (names[classid] && names[classid]['options'][optionid])
        return names[classid]['options'][optionid];

    return false;
}


