// Include customer registry scripts
// TODO: make a js output manager or something, srsly
document.write('<script type="text/javascript" src="/ajax/customerRegistry.js"></script>');

//Ajax object declaration 

var ajaxObj = new XMLHTTP("ajax/mybic_server.php");

// Ajax debug
ajaxObj.debug=0;

//global declaration
var labels = new Array();
var selected = new Array();
var defaultSelects = new Array();
var valid;
var lastSelected;
var teste;
var formName;
var id;

/*Returns cost price*/
function catPrices(obj, idItem)
{
    id = idItem;
    formName = 'item' + id; 
    
    disableForm(document.getElementById(formName));
    
    reloadSelects(obj);
        
    var postVars = 'action=itemDetailPrices'+ajaxObj.getForm(formName);
    ajaxObj.call(postVars, respCatPrices);
}

function respCatPrices(resp)
{
    /*Update Price*/
    if(document.getElementById('price' + id) != null)
        document.getElementById('price' + id).innerHTML = resp['price'];
    
    /*Update Retail Price*/
    if(document.getElementById('retailPrice' + id) != null)
        document.getElementById('retailPrice' + id).innerHTML = resp['retailPrice'];

    /*Update Price Savings*/
    if(document.getElementById('priceSavings' + id) != null)
        document.getElementById('priceSavings' + id).innerHTML = resp['yourSavingsPrice'];
    
    /*Update SKU*/
    if(document.getElementById('sku' + id) != null)
        document.getElementById('sku' + id).innerHTML = resp['sku'];
    
    enableForm(document.getElementById(formName));
}

/*returns an addon price*/
function catAddonPrices(idItem)
{
    id = idItem;
    formName = 'item' + id; 
    
    clearMsg()
    disableForm(document.getElementById(formName));
    
    var postVars = 'action=itemDetailPrices'+ajaxObj.getForm(formName);
    ajaxObj.call(postVars, respCatPrices);
}

function respReloadSelects(resp)
{
    var level;
    var arraySelect = new Array();
    var i, j;

    var form = document.getElementById(formName);
    selects = form['cost[]'];
    
    if (resp.length != 0)
    {
        for (level in resp)
        {    
            selects[level -1].options.length = 0;
            selects[level -1].options[0] = new Option(labels[level -1], "0");
                
            i = 1;
            for (j=0; j < resp[level].length; j++)
            {    
                selects[level -1].options[i] = new Option(resp[level][j]['name'], resp[level][j]['id']);
                
                if (selected[level -1] == resp[level][j]['id'])
                    selects[level -1].options[i].selected = true;        
                
                i++;
            }
        }
    }
}

/*Reloads cost Selects with valid options*/
function reloadSelects(obj)
{
    var ids, costIds, i;
    var postVars;

    lastSelected = obj.value;
    
    clearMsg();
    
    var form = document.getElementById(formName);
    
    costIds = form['cost[]'];
    
    if (labels[0] == null)
    {
        makeLabels(costIds);
        makeDefaultSelects(costIds);
    }
    
    teste = obj;
    ids = makeCostsIds(obj, costIds);
    
    if (costIds.length == ids.length) {
        isValidOption(ids); }
    else
    {
        postVars = 'action=validCosts&ajaxPost='+ids+'&idItem='+id;
        ajaxObj.call(postVars, respReloadSelects)
    }        
    
}

/*checks if an set of options are valid, if not all cost selects are reloaded
This function prevents a customer to choose a invalid set of options*/

function isValidOption(ids)
{
    var postVars = 'action=isValidOption&ajaxPost='+ids+'&idItem='+id;
    ajaxObj.call(postVars, respIsValidOption)
}

function respIsValidOption(resp)
{
    valid = parseInt(resp); 
    var form = document.getElementById(formName);
    costIds = form['cost[]'];
    
    ids = makeCostsIds(teste, costIds);
    
    if (valid == 0)
        postVars = 'action=validCosts&ajaxPost='+lastSelected+'&idItem='+id; 
    else
    { 
        respReloadSelects(defaultSelects);
        return 0;
    }
    
    ajaxObj.call(postVars, respReloadSelects);
}


function makeCostsIds(obj, costIds)
{
    var finalArray = new Array(); 
    var i, j;
    
    j=0;
    for (i=0; i < costIds.length; i++)
    {    
        if (costIds[i].value > 0)
        {
            finalArray[j] = costIds[i].value;
            j++;    
        }
    selected[i] = costIds[i].value;
    }
    
    return finalArray;
    
}


/*make an array of all cost selects labels, like "choose color"*/
function makeLabels(selects)
{
    
    //if selects is an array
    if (isArray(selects))
        for (i=0; i < selects.length; i++)
            labels[i] = selects[i].options[selects[i].length -1].text;
    
    //else select is an Select Object
    else
        for (i=0; i < selects.length; i++)
            labels[i] = selects.options[selects.length -1].text;
    
}

/*makes an array of all cost selects*/
function makeDefaultSelects(selects)
{
    var i, j, z;
    
    
    if (isArray(selects))
    {
        for (i=1; i <= selects.length; i++)
            defaultSelects[i] = new Array();
    
        for (i=1; i <= selects.length; i++)
            for (j=0; j < selects[i -1].options.length; j++)
            { 
                if (selects[i -1].options[j].value != 0)
                {
                    defaultSelects[i][j] = new Array();
                    defaultSelects[i][j]['id'] = selects[i -1].options[j].value;
                    defaultSelects[i][j]['name'] = selects[i -1].options[j].text;    
                }
            }
    }
    else
    {
        defaultSelects[1] = new Array();
        
        for (i=0; i < selects.length; i++)
            { 
                if (selects.options[i].value != 0)
                {
                    defaultSelects[1][i] = new Array();
                    defaultSelects[1][i]['id'] = selects.options[i].value;
                    defaultSelects[1][i]['name'] = selects.options[i].text;    
                }
            }
    }
}

/*adds a product to cart*/
function addToCart()
{    
    if(typeof(AddToCartIdItemValue) != "undefined")
    {
        formName = AddToCartIdItemValue;
    }
        
    disableForm(document.getElementById(formName));
    
    if(document.getElementById('msg' + id))
    {
        document.getElementById('msg' + id).innerHTML = "";
    }
    else
    {
        document.getElementById('msg').innerHTML = "";
    }
    
    var postVars = 'action=addToCart'+ajaxObj.getForm(formName);
    ajaxObj.call(postVars, respAddToCart);
    
    /*Cart View call */
    var postVars = 'action=checkCartView';
    ajaxObj.call(postVars, cartView);
    
    if(typeof(AddToCartIdItemValue) != "undefined")
    {
        enableForm(document.getElementById(formName));
    }
    
}

/*Change qty of products in cart view*/
function cartView(resp) {

    rates = document.getElementById('cartView');
    if (rates)
        document.getElementById('cartView').innerHTML = resp;
}
    

/*resp add to cart function of ajax*/
function respAddToCart(resp)
{
    if(resp[1] == 1)
    {
        var itemAdded = language['itemAddedRfp'];
        var viewCart = language['viewCartRfp'];
    }
    else
    {
        var itemAdded = language['itemAdded'];
        var viewCart = language['viewCart'];
    }
    
    if(document.getElementById('msg' + id))
    {
        document.getElementById('msg' + id).innerHTML = itemAdded + '<br />  <a href="/cart.html">(' + viewCart +')</a>';
    }
    else
    {
        document.getElementById('msg').innerHTML = itemAdded + '<br />  <a href="/cart.html">(' + viewCart +')</a>';
    }
    enableForm(document.getElementById(formName));
    
}


/*Clears the item message*/
function clearMsg(idItem)
{
    if (idItem == undefined)
        idItem = id;
        
    document.getElementById('msg' + idItem).innerHTML = "";
}

/*checks Inventory of a item*/
function checkInventory(idItem)
{

    id = idItem;
    formName = 'item' + id;
 

    if (checkBanks(document.getElementById(formName)) != 0)
    {
        var postVars = 'action=checkInventory'+ajaxObj.getForm(formName);
        
        ajaxObj.call(postVars, respCheckInventory);            
        
    }
    else alert ( language['chooseAllOptions'] );

}

/*resp check Inventory function of ajax*/
function respCheckInventory(resp)
{
    
    if (resp == "OFF")
    {
        addToCart();
        return true;
    }
        
    var form = document.getElementById(formName);
    var userQty = form['productQty'];
    
    userQty = parseInt(userQty.value);
    resp = parseInt(resp);
    
    if (resp <= 0)
    {
        document.getElementById('msg' + id).innerHTML = language['productUnavailable'];
        return true;
    }
        
    if (userQty > resp)
    {
        document.getElementById('msg' + id).innerHTML = language['thereAreOnly'] + ' ' + resp + ' ' + language['available'];
        form['productQty'].value = resp;
    }
    else
        addToCart();
    
    enableForm(document.getElementById(formName));
}

function searchPagination(act,pag,searchString) {
    
    document.getElementById('actPagination').value = act;
    document.getElementById('pagPagination').value = pag;
    document.getElementById('searchStringMM').value = searchString;    
    //alert('[ '+document.getElementById('actPagination').value+' - '+document.getElementById('pagPagination').value+' - '+document.getElementById('searchStringMM').value+" ]");
    document.getElementById('searchFormPagination').submit();
    
}

function showPicture(id,hide) {
    for(x=1;x<=hide;x++)
        document.getElementById('image'+x).style.display='none';
    
    document.getElementById('image'+id).style.display=''
}


function applyDiscountCoupon(id)
{
    idForAjaxResponse = id;
    
    var postVars = 'action=ajaxDiscount&couponNumber=' + document.getElementById('DiscontCouponField' + id).value + '&idItem=' + id + '&productDefaultPrice=' + document.getElementById('price' + id).innerHTML;
    ajaxObj.call(postVars, respApplyDiscountCoupon);
}


function respApplyDiscountCoupon(resp)
{
    if(resp['msg'].length > 0)
    {
        document.getElementById('msg' + idForAjaxResponse).innerHTML = resp['msg'];
    }
    else
    {
        document.getElementById('price' + idForAjaxResponse).innerHTML = '$' + resp['formatedValue'];
        document.getElementById('msg' + idForAjaxResponse).innerHTML = "";
    }
}

