var timer = null;

//This is called each time a product option is changed on the quote panel
function getQuote(optionId, optionChoiceValue) {
    if (timer != null)
        clearTimeout(timer);

    document.body.style.cursor = 'wait';
    var printingJobObject = getPrintingJobObject();

    var selectedOptions = printingJobObject.SelectedOptions;
    for (var i = 0; i < selectedOptions.length; i++) {
        if (selectedOptions[i] != null && selectedOptions[i].OptionId == optionId) {
            selectedOptions[i].OptionChoiceId = optionChoiceValue;
            break;
        }
    }

    getQuoteAjax(printingJobObject);
}

function getQuoteAjax(printingJobObject) {
    var DTO = JSON.stringify({ 'jobTicket': printingJobObject });
    $.ajax({
        type: "POST",
        mode: "queue",
        url: "/AjaxLibrary.aspx/GetProductPageQuote",
        contentType: "application/json; charset=utf-8",
        data: DTO,
        dataType: "json",
        success: function(result) {
            var res = JSON.parse(result.d);
            getQuoteCallback({ value: res });
        }
    });
}

//This function is called each time a set product option changes(Shrink Wrapping, Padding)
function getQuoteOnSetChange(optionId, setCount) {
    if (timer != null)
        clearTimeout(timer);
        
    document.body.style.cursor = 'wait';
    
    document.body.focus(); // blur any textboxes so custom trim logic in "onchange" is not lost
    setTimeout(function doNothing() { }, 500);  // give it a second to recalculate custom trim and write the JSON string back to the hidden field
    
    var printingJobObject = getPrintingJobObject();

    var selectedOptions = printingJobObject.SelectedOptions;
    for (var i = 0; i < selectedOptions.length; i++) {
        if (selectedOptions[i] != null && selectedOptions[i].OptionId == optionId) {
            selectedOptions[i].SetCount = setCount;
            break;
        }
    }

    getQuoteAjax(printingJobObject);
}

//returns the PrintingJobTicked from the hidden field
function getPrintingJobObject() {
    var printingJob = document.getElementById(document.getElementById('printingJobFieldID').value).value;
    return JSON.parse(printingJob);
}

//this is executed when the AJAX response is received
function getQuoteCallback(jobQuote) {    
    if (jobQuote.value == null) {
        alert('There was an error obtaining the price quote, and it cannot be displayed.');
        return;
    }

    if (jobQuote.value.ErrorMessage != null) {
        alert(jobQuote.value.ErrorMessage);
        document.body.style.cursor = 'default';
    }
    else {
        setHiddenField(jobQuote.value);
        var printingJob = getPrintingJobObject();
        if (printingJob.AvailableOptions != null) {
            for (var i = 0; i < printingJob.AvailableOptions.length; i++) {
                var optionField = document.getElementById('ProductOption_' + printingJob.AvailableOptions[i].OptionId);
                if (optionField != null) {
                    var ui = document.getElementById(optionField.value);
                    if (ui != null) {
                        var so = ui.value;
                        ui.options.length = 0;
                        var optionChoices = printingJob.AvailableOptions[i].OptionChoices;
                        for (var j = 0; j < optionChoices.length; j++) {
                            var newOption = new Option(optionChoices[j].ChoiceName, optionChoices[j].OptionChoiceId)
                            ui.options[ui.options.length] = newOption;
                            if (so == optionChoices[j].OptionChoiceId) { ui.selectedIndex = j; }
                        }

                        ui.disabled = ui.options.length < 2;
                    }
                }
            }
        }

        document.getElementById(document.getElementById('spanItemTotalID').value).childNodes[0].nodeValue = printingJob.ItemTotal;
        document.getElementById(document.getElementById('spanItemTotal1ID').value).childNodes[0].nodeValue = printingJob.ItemTotal;
        document.getElementById(document.getElementById('spanUnitCostID').value).childNodes[0].nodeValue = printingJob.UnitCost;
        document.body.style.cursor = 'default';
    }
}

//sets the hidden field value with the current printing job object
function setHiddenField(printingJob) {
    var hiddenField = document.getElementById(document.getElementById('printingJobFieldID').value);    
    hiddenField.value = JSON.stringify(printingJob);
}

//this function is called when the custom job sizes are modified, it validates that the inserted values are correct
function chkCustomCut(isHeight, customTrimSizeTicket) {    
    var customTrimTicket = JSON.parse(customTrimSizeTicket);
    var maxSize = getMaxSize(customTrimTicket);
    var maxWidth = getMaxWidth(maxSize);
    var maxHeight = getMaxHeight(maxSize);

    var customWidth = document.getElementById(customTrimTicket.TxtCustomWidthClientID);
    var customHeight = document.getElementById(customTrimTicket.TxtCustomHeightClientID);

    if (isNaN(customWidth.value) || new Number(customWidth.value) > maxWidth || new Number(customWidth.value) < customTrimTicket.MinWSize) {
        customWidth.value = maxWidth;
    }

    if (isNaN(customHeight.value) || new Number(customHeight.value) > maxHeight || new Number(customHeight.value) < customTrimTicket.MinHSize) {
        customHeight.value = maxHeight;
    }

    if (customTrimTicket.IsFoldedPostCards) {
        //half folding
        if (document.getElementById(customTrimTicket.FoldingUIClientID).value == 1020) {
            if (Math.max(customWidth.value, customHeight.value) < 6) {
                if (isHeight) customHeight.value = maxHeight;
                if (!isHeight) customWidth.value = maxWidth;
            }
        }

        //letter folding
        if (document.getElementById(customTrimTicket.FoldingUIClientID).value == 1019) {
            if (Math.max(new Number(customWidth.value), new Number(customHeight.value)) < 9) {
                if (isHeight) customHeight.value = maxHeight;
                if (!isHeight) customWidth.value = maxWidth;
            }
        }
    }

    var printingJob = getPrintingJobObject();
    printingJob.CustomTrimJobSize = customHeight.value + 'X' + customWidth.value;
    setHiddenField(printingJob);
    
    getQuoteAjax(printingJob);
}

//this function is called when custom trimming option is changed
function initCustomCut(customTrimSizeTicket) {
    var customTrimTicket = JSON.parse(customTrimSizeTicket);    
    var cc = document.getElementById(customTrimTicket.DdlCustomCutClientID).value == 'No';
    var txtCustomHeight = document.getElementById(customTrimTicket.TxtCustomHeightClientID);
    var txtCustomWidth = document.getElementById(customTrimTicket.TxtCustomWidthClientID);

    document.getElementById(customTrimTicket.LblCustomHeightClientID).disabled = cc;
    document.getElementById(customTrimTicket.LblCustomWidthClientID).disabled = cc;
    txtCustomHeight.disabled = cc;
    txtCustomWidth.disabled = cc;
    var printingJob = getPrintingJobObject();
    printingJob.CustomTrim = !cc;

    if (cc) {
        txtCustomWidth.value = '';
        txtCustomHeight.value = '';
    } else {
        var maxSize = getMaxSize(customTrimTicket);
        var maxWidth = getMaxWidth(maxSize);
        var maxHeight = getMaxHeight(maxSize);

        txtCustomWidth.value = maxWidth;
        txtCustomHeight.value = maxHeight;

        printingJob.CustomTrimJobSize = maxSize;
    }    
    setHiddenField(printingJob);
}

function getMaxSize(customTrimTicket) {
    var sizeOption = document.getElementById(customTrimTicket.SizeUIClientID);
    var maxSize = sizeOption.options[sizeOption.selectedIndex].text.toUpperCase();   
    if (maxSize.indexOf(' ') > 0) { maxSize = maxSize.substr(0, maxSize.indexOf(' ')); }

    return maxSize;
}

function getMaxWidth(maxSize) {
    return new Number(maxSize.substr(maxSize.indexOf('X') + 1, maxSize.length - (maxSize.indexOf('X') + 1)));
}

function getMaxHeight(maxSize) {
    return new Number(maxSize.substr(0, maxSize.indexOf('X')));
}
         

