/* Checkbox list functions =============================================================== */
function checkAll(form_object, checkbox_name) 
{
    if (form_object[checkbox_name].length == null) {
        form_object[checkbox_name].checked = true;
    } else {
        for(i=0; i<form_object[checkbox_name].length; i++) {
            form_object[checkbox_name][i].checked = true; 
        }
    }
}

function uncheckAll(form_object, checkbox_name) 
{ 
    if (form_object[checkbox_name].length == null) {
        form_object[checkbox_name].checked = false;
    } else {
        for(i=0; i<form_object[checkbox_name].length; i++) {
            form_object[checkbox_name][i].checked = false; 
        }
    }
}

/* Devlab forms processing =============================================================== */
function devlabFormPost(ctrlButton, formName, urlPost, urlSuccess, urlError)
{
    ctrlButton.disabled = true;
    var formData = $(formName).serialize();
    $.post(urlPost, formData, function(data){ devlabResponseWrap(data, urlSuccess, urlError, ctrlButton); });
}

function devlabResponseWrap(data, urlSuccess, urlError, ctrlButton)
{
    try {
        response_array = $.parseJSON(data);

        result = response_array.result;
        redirect_url = ("redirect_url" in response_array) ? response_array.redirect_url : "/";
        message = ("message" in response_array) ? response_array.message : "/";
        
        if (result == "success") {
            window.location = (urlSuccess == "") ? redirect_url : urlSuccess;
        } else if (result == "error") {
            ctrlButton.disabled = false;
            document.getElementById('error_msg').innerHTML = message;
            document.getElementById('error_msg').style.display = 'block';
            //refresh captcha
            if (document.getElementById("captcha") != null) {
                document.getElementById('captcha').src = '/captcha?' + Math.random();
            }
            window.location = redirect_url;
        } else {
            //do nothing
        }
    } catch (e) {
        if (data == 'true') { //success
            window.location = urlSuccess;
        } else { //error
            ctrlButton.disabled = false;
            document.getElementById('error_msg').innerHTML = data;
            document.getElementById('error_msg').style.display = 'block';
            //refresh captcha
            if (document.getElementById("captcha") != null) {
                document.getElementById('captcha').src = '/captcha?' + Math.random();
            }
            window.location = urlError;
        }
    }
    
    /*if (data == 'true') { //success
        window.location = urlSuccess;
    } else if (data == 'true') { //success
        window.location = urlSuccess;
    } else { //error
        ctrlButton.disabled = false;
        document.getElementById('error_msg').innerHTML = data;
        document.getElementById('error_msg').style.display = 'block';
        //refresh captcha
        if (document.getElementById("captcha") != null) {
            document.getElementById('captcha').src = '/captcha?' + Math.random();
        }
        window.location = urlError;
    }*/
}

/* Discount coupone ====================================================================== */
function showDiscountCoupone()
{
    document.getElementById('discount_coupone_placeholder').style.display = 'block';
    window.location = "#";
}

/* Shipping cost calculator ============================================================== */
function calcShipCost(data)
{
    var str = $("#form_shipCost").serialize();
    $.post("/calculator/index/ajaxshipcost", str, calcShipCost_handleresponse);
}

function calcShipCost_handleresponse(data)
{
    document.getElementById('ship_costResultText').innerHTML = data;
    document.getElementById('ship_costResult').style.display = 'block';
}

/* Payment creation functions ============================================================ */
function findCustomer(url)
{
    var data = $('#form_findCustomer').serialize();
    $.getJSON(url, data, function findCustomer_handleresponse(data) {
        //cleanup
        for(var i=document.getElementById("user_list").rows.length; i>2; i--) {
            document.getElementById("user_list").deleteRow(i - 1);
        }

        //add new data
        $.each(data, function(index, item) {
            var username = item['firstname']+' '+item['lastname'];
            rowHTML = '<tr>' +
                '<td>' + item['id'] + '</td>' +
                '<td>' + username +'</td>' +
                '<td>'+ '<a href="#" onclick="selectCustomer('+"'"+item['id']+"', '"+username+"', '"+item['email']+"'"+');">'+item['email']+'</a></td>' +
                '</tr>';

            tableAddRow('#user_list', rowHTML);
        });
    } );
}

/*function populate_paymentType(type) {
    var list = document.getElementById("transaction_payment_type");
    clearOptions(list);
    addToOptionList(list, '-1', '');

    if (type == 'debit') {
        addToOptionList(list, 'order', 'Заказ');
        addToOptionList(list, 'ship_intl', 'Доставка международная');
        addToOptionList(list, 'ship_domestic', 'Доставка местная');
    } else if (type == 'credit') {
        addToOptionList(list, 'payment', 'Поступление денег');
        addToOptionList(list, 'refund', 'Возврат денег клиенту');
    }
}*/

/*function clearOptions(OptionList) {
   // Always clear an option list from the last entry to the first
   for (x = OptionList.length; x >= 0; x--) {
      OptionList[x] = null;
   }
}*/

function addToOptionList(OptionList, OptionValue, OptionText) {
   // Add option to the bottom of the list
   OptionList[OptionList.length] = new Option(OptionText, OptionValue);
}

function selectCustomer(id, username, email)
//function selectCustomer()
{
    //alert('123123'); 
    document.getElementById('search_form').style.display = 'none';
    document.getElementById('selected_user').innerHTML = username + ' / e-mail: '+email+' / user# ' + id;
    document.getElementById('transaction_user_id').value = id;
    document.getElementById('payment_form').style.display = 'block';
}

function tableAddRow(tableName, rowHTML){
    jQtable = $(tableName);
    jQtable.each(function(){
        var $table = $(this);
        if($('tbody', this).length > 0){
            $('tbody', this).append(rowHTML);
        }else {
            $(this).append(rowHTML);
        }
    });
}

function returnData(url, params)
{
    var result = [];
    $.ajax({
      url: url,
      async: false,
      dataType: 'json',
      data: params,
      success: function (data) {
        result = data;
      }
    });
    
    return result;
}

function strpos(haystack, needle, offset) {
  var i = (haystack+'').indexOf(needle, (offset || 0));
  return i === -1 ? false : i;
}

function delete_row(obj) {
    $(obj).parent().parent().parent().remove();
}

