﻿/// <reference path="jquery-1.4.2.min.js"/>

var ftc_change_price = {
    $filmTransferPriceArea: null,
    $hardDrivePriceArea: null,
    $validationMessage: null,
    $errorControl: null, //contais an control causing the error
    percetageDiscount: 0,
    showHardDriveTable: function() {
        var $table = ftc_change_price.$hardDrivePriceArea.find("table:first");
        $table.find("tr.dynamic").remove();
        for (var iHDIndex = 0; iHDIndex < ftc_pricing.hardDrivePricing.length; iHDIndex++) {
            var hardDricePrice = ftc_pricing.hardDrivePricing[iHDIndex];
            var sizeGB = hardDricePrice.sizeGB;
            var $dataRow = $("<tr class='dynamic'></tr>");
            ftc_change_price.addCellHTML('Hard Drive', $dataRow, sizeGB, "sizeGB");
            ftc_change_price.addCellHTML('Hard Drive', $dataRow, sizeGB, "price");
            ftc_change_price.addCellHTML('Hard Drive', $dataRow, sizeGB, "withProtection");

            var hours = sizeGB / 62;
            var feet = Math.floor((hours * 800) / 100) * 100;
            $dataRow.append("<td  class='noWrap'>Up to " + feet + " ft<br />or ~" + Math.floor(hours) + " hours</td>");
            feet = Math.floor((hours * 1500) / 100) * 100;
            $dataRow.append("<td  class='noWrap'>Up to " + feet + " ft<br />or ~" + Math.floor(hours) + " hours</td>");

            $table.find("tr:last").after($dataRow);
        }
        $table.find("tr").removeClass("alt");
        $table.find("tr:even").addClass("alt");
    },
    showFilmTransferTable: function() {
        var $table = ftc_change_price.$filmTransferPriceArea.find("table");
        $table.find("tr.dynamic").remove();
        var numberOfFeet = ftc_pricing.filmTranferPricing[0].storages[0].prices;
        for (var indexNumberOfFeet = 0; indexNumberOfFeet < numberOfFeet.length; indexNumberOfFeet++) {
            var feetNum = numberOfFeet[indexNumberOfFeet][0];
            var $priceRow = $("<tr class='dynamic'></tr>");
            ftc_change_price.addCellHTML('Feet', $priceRow, feetNum);
            ftc_change_price.addCellHTML('Film Transfer', $priceRow, feetNum, 'DVD', '8mm / Super 8mm');
            ftc_change_price.addCellHTML('Film Transfer', $priceRow, feetNum, 'Blu-Ray', '8mm / Super 8mm');
            ftc_change_price.addCellHTML('Film Transfer', $priceRow, feetNum, 'DVD', '16mm');
            ftc_change_price.addCellHTML('Film Transfer', $priceRow, feetNum, 'Blu-Ray', '16mm');
            $table.find("tr:last").prev().before($priceRow);
        }
        ftc_change_price.addCellHTML('Sound Transfer', null, null, null, '8mm / Super 8mm');
        ftc_change_price.addCellHTML('Sound Transfer', null, null, null, '16mm');
        ftc_change_price.addCellHTML('Color Correction');
        $table.find("tr").removeClass("alt");
        $table.find("tr:even").addClass("alt");
    },
    showExtraCopiesPrices: function() {
        ftc_change_price.addCellHTML('Extra Copies', null, null, 'DVD');
        ftc_change_price.addCellHTML('Extra Copies', null, null, 'Blu-Ray');
    },
    getDiscountPercent: function() {
        if ('discountPercentage' in ftc_pricing) {
            var dateExpirePercentage = new Date(ftc_pricing.discountPercentage.expire_year, ftc_pricing.discountPercentage.expire_month_starts_from_zero, ftc_pricing.discountPercentage.expire_day);
            var todayPercentage = new Date();
            if (todayPercentage < dateExpirePercentage) {
                return ftc_pricing.discountPercentage.value;
            }
        }
        return 0;
    },
    //returns true if the page display the price in cents for the given data type
    displayCents: function(dataType) {
        return (dataType == "Film Transfer" ||
                dataType == "Color Correction" ||
                dataType == "Sound Transfer");
    },
    addCellHTML: function(dataType, $priceRow, number, subType, filmType) {
        if (dataType === undefined) {
            dataType = "Film Transfer";
        }
        var value = ftc_change_price.getData(dataType, filmType, subType, number);
        var valueText = ftc_change_price.getCellText(value, dataType, subType);
        var $htmlElement = null;
        switch (dataType) {
            case "Color Correction":
                $htmlElement = $("#colorCorrectionCell").html(valueText);
                break;
            case "Sound Transfer":
                if (filmType == "16mm") {
                    $htmlElement = $("#soundTransfer16mm").html(valueText);
                } else {
                    $htmlElement = $("#soundTransfer8mm").html(valueText);
                }
                break;
            case "Extra Copies":
                if (subType == "DVD") {
                    $htmlElement = $("#DVDExtraCopyPrice").html(valueText);
                } else {
                    $htmlElement = $("#blurayExtraCopyPrice").html(valueText);
                }
                break;
            default:
                cellClass = "price-cell-" + dataType.replace(" ", "").toLowerCase();
                $htmlElement = $("<td class='" + cellClass + "'>" + valueText + "</td>");
                if (dataType == "Feet" || (dataType == "Hard Drive" && subType == "sizeGB")) {
                    $htmlElement.addClass("bold");
                }
        }

        var priceItemObject = {
            "dataType": dataType,
            "filmType": filmType,
            "subType": subType,
            "number": number,
            "price": value
        };
        $htmlElement.data("priceItem", priceItemObject);
        if (ftc_obb.isAdmin) {
            $htmlElement.hover(function() { $(this).addClass("grayBox"); }, function() { $(this).removeClass("grayBox"); })
            .click(function() {
                //show a text box for editing
                var $cell = $(this);
                if ($cell.children("input").length > 0) {
                    //alredy has a textbox
                    return;
                }
                if (ftc_change_price.$errorControl !== null) {
                    return;
                }
                var textBoxValue = null;
                switch ($cell.data("priceItem").dataType) {
                    case "Feet":
                        textBoxValue = $cell.data("priceItem").number;
                        if (textBoxValue === 0) {
                            return;
                        }
                        break;
                    case "Hard Drive":
                    case "Extra Copies":
                        textBoxValue = $cell.data("priceItem").price;
                        break;
                    default:
                        if (ftc_change_price.displayCents($cell.data("priceItem").dataType)) {
                            textBoxValue = Math.round(($cell.data("priceItem").price * 100));
                        } else {
                            textBoxValue = $cell.data("priceItem").price.toFixed(2);
                        }
                }

                var $textBox = $("<input type='text' value='" + textBoxValue + "'/>");
                $cell.html("")
                .append($textBox);
                $textBox.focus().select();

                $textBox.blur(function() { return ftc_change_price.storeTextboxChanges($(this)); })
                .keyup(function(e) {
                    c = e.which ? e.which : e.keyCode;
                    if (c == 13) {
                        ftc_change_price.storeTextboxChanges($(this));
                    }
                    if (c == 27) {
                        ftc_change_price.storeTextboxChanges($(this), true);
                    }
                });
            });
        }
        if ($priceRow !== undefined && $priceRow!=null) {
            $priceRow.append($htmlElement);
        }
    },
    storeTextboxChanges: function($textBox, cancel) {
        if (cancel === undefined) {
            cancel = false;
        }
        var $cell = $textBox.parent();
        var priceItemObject = $cell.data("priceItem");
        var valueDataOld = ftc_change_price.getData(priceItemObject.dataType, priceItemObject.filmType, priceItemObject.subType, priceItemObject.number);
        var value = null;
        var valueName = "price";
        switch (priceItemObject.dataType) {
            case "Feet":
                valueName = "feet number";
                break;
            case "Hard Drive":
                if (priceItemObject.subType == "sizeGB") {
                    valueName = "hard drive size";
                }
                break;
        }
        if (!cancel && isNaN($textBox.val())) {
            ftc_change_price.showError('Please enter correct ' + valueName + '.', $textBox);
        } else {
            if (cancel) {
                value = valueDataOld;
                ftc_change_price.hideError();
            } else {
                value = parseFloat($textBox.val());
                if (ftc_change_price.displayCents(priceItemObject.dataType)) {
                    valueDataOld = Math.round(valueDataOld * 100);
                    value = Math.round(value);
                }
                if (valueDataOld !== value) {
                    var minValue = 0;
                    var maxValue = 100;
                    switch (priceItemObject.dataType) {
                        case "Extra Copies":
                            maxValue = 500;
                            value = Math.floor(value);
                            break;
                        case "Feet":
                            var pricesArray = ftc_pricing.filmTranferPricing[0].storages[0].prices;
                            for (var iPr = 0; iPr < pricesArray.length; iPr++) {
                                if (pricesArray[iPr][0] == valueDataOld) {
                                    if (iPr === 0) {
                                        minValue = 0;
                                    } else {
                                        minValue = pricesArray[iPr - 1][0];
                                    }
                                    if (iPr == pricesArray.length - 1) {
                                        maxValue = 1000000;
                                    } else {
                                        maxValue = pricesArray[iPr + 1][0];
                                    }
                                    break;
                                }
                            }
                            value = Math.floor(value);
                            break;
                        case "Hard Drive":
                            maxValue = 10000;
                            if (priceItemObject.subType == "sizeGB") {
                                for (var iHDPr = 0; iHDPr < ftc_pricing.hardDrivePricing.length; iHDPr++) {
                                    var hdPricing = ftc_pricing.hardDrivePricing[iHDPr];
                                    if (hdPricing.sizeGB == valueDataOld) {
                                        if (iHDPr === 0) {
                                            minValue = 0;
                                        } else {
                                            minValue = ftc_pricing.hardDrivePricing[iHDPr - 1].sizeGB;
                                        }
                                        if (iHDPr == ftc_pricing.hardDrivePricing.length - 1) {
                                            maxValue = 1000000;
                                        } else {
                                            maxValue = ftc_pricing.hardDrivePricing[iHDPr + 1].sizeGB;
                                        }
                                        break;
                                    }
                                }
                            }
                            value = Math.floor(value);
                            break;
                    }
                    if (value <= minValue || value >= maxValue) {
                        ftc_change_price.showError('The ' + valueName + ' should be between ' + minValue + ' and ' + maxValue, $textBox);
                        return false;
                    }
                    ftc_change_price.hideError();

                    if (ftc_change_price.displayCents(priceItemObject.dataType)) {
                        value /= 100;
                    }

                    //change the value
                    ftc_change_price.setData(priceItemObject.dataType, priceItemObject.filmType, priceItemObject.subType, priceItemObject.number, value);
                    var strPriceDataToSubmit = null;
                    try {
                        strPriceDataToSubmit = JSON.stringify(ftc_pricing);
                        var vPriceParsed = $.parseJSON(strPriceDataToSubmit);
                        if (!ftc_obb.compareObjects(ftc_pricing, vPriceParsed)) {
                            throw "Error parsing object to JSON.";
                        }
                    }
                    catch (Error) {
                        ftc_change_price.showError('Error storing pricing data to database: ' + Error);
                        return false;
                    }


                    switch (priceItemObject.dataType) {
                        case "Hard Drive":
                            ftc_change_price.showHardDriveTable();
                            break;
                        case "Feet":
                            ftc_change_price.showFilmTransferTable();
                            break;
                        default:
                            priceItemObject.price = value;
                    }

                    //store to database
                    $("#pricingData").val(strPriceDataToSubmit);
                    $("#changePricingForm").submit();
                } else {
                    //the value has not changed
                    if (ftc_change_price.displayCents(priceItemObject.dataType)) {
                        value /= 100;
                    }
                    ftc_change_price.hideError();
                }
            }
            $cell.html(ftc_change_price.getCellText(value, priceItemObject.dataType, priceItemObject.subType));
        }
    },
    getFootPriceString: function(priceNum) {
        priceNum = ftc_obb.roundPrice(priceNum);
        if (priceNum < 1) {
            return ftc_obb.roundPrice(priceNum * 100) + "¢";
        }
        return "$" + priceNum;
    },
    getCellText: function(value, dataType, subType) {
        switch (dataType) {
            case 'Feet':
                if (value >= 10000) {
                    value += "";
                    value = value.substring(0, value.length - 3) + "," + value.substring(value.length - 3, value.length);
                }
                if (value === 0 && ftc_pricing.filmTranferPricing[0].storages[0].prices.length > 1) {
                    value = "up to " + ftc_pricing.filmTranferPricing[0].storages[0].prices[1][0];
                } else {
                    value += "+";
                }
                break;
            case 'Hard Drive':
                if (subType == 'sizeGB') {
                    if (value < 1000) {
                        value += " GB";
                    } else {
                        value = (value / 1000) + " TB";
                    }
                } else {
                    value = "$" + value.toFixed(0);
                }
                break;
            case 'Extra Copies':
                value = "$" + value.toFixed(0);
                break;
            case 'Film Transfer':
                if (ftc_change_price.percetageDiscount > 0) {
                    var oldPrice = value;
                    var discountedPrice = value * (100 - ftc_change_price.percetageDiscount) / 100;
                    value = "<div class='discountedPrice'>" + ftc_change_price.getFootPriceString(discountedPrice) + "</div>";
                    value += "<div class='oldPrice'>" + ftc_change_price.getFootPriceString(oldPrice) + "</div>";
                } else {
                    value = ftc_change_price.getFootPriceString(value);
                }
                break;
            default:
                value = ftc_change_price.getFootPriceString(value);
        }
        return value;
    },
    showError: function(msgError, $element) {
        if ($element !== undefined) {
            ftc_change_price.$errorControl = $element;
            $element.addClass('input-validation-error').focus().select();
        }
        ftc_change_price.$validationMessage.html('').append("<div>" + msgError + '</div>').slideDown('fast');
    },
    hideError: function() {
        if (ftc_change_price.$validationMessage.is(":visible")) {
            ftc_change_price.$errorControl = null;
            ftc_change_price.$validationMessage.html('').slideUp('fast');
            ftc_change_price.$filmTransferPriceArea.find(".input-validation-error").removeClass("input-validation-error");
        }
    },
    getData: function(dataType, filmType, subType, number) {
        switch (dataType) {
            case 'Feet':
                return number;
            case 'Hard Drive':
                return ftc_change_price.getHardDriveObject(number)[subType];
            case 'Extra Copies':
                return ftc_change_price.getExtraCopiesObject(subType).PricePerHour;
            case 'Sound Transfer':
                return ftc_change_price.getSoundTransferObject(filmType).price;
            default:
                return ftc_change_price.getPriceObject(dataType, filmType, subType, number)[ftc_change_price.getDataKeyName(dataType)];
        }
    },
    setData: function(dataType, filmType, subType, number, newValue) {
        switch (dataType) {
            case 'Feet':
                for (var iTypes = 0; iTypes < ftc_pricing.filmTranferPricing.length; iTypes++) {
                    var filmTypeObject = ftc_pricing.filmTranferPricing[iTypes];
                    for (var iStorage = 0; iStorage < filmTypeObject.storages.length; iStorage++) {
                        var storageObject = filmTypeObject.storages[iStorage];
                        ftc_obb.mySearchObjectInArray(storageObject.prices, 0, number)[0] = newValue;
                    }
                }
                break;
            case 'Hard Drive':
                ftc_change_price.getHardDriveObject(number)[subType] = newValue;
                break;
            case 'Extra Copies':
                ftc_change_price.getExtraCopiesObject(subType).PricePerHour = newValue;
                break;
            case 'Sound Transfer':
                ftc_change_price.getSoundTransferObject(filmType).price = newValue;
                break;
            default:
                ftc_change_price.getPriceObject(dataType, filmType, subType, number)[ftc_change_price.getDataKeyName(dataType)] = newValue;
                if (dataType == 'Film Transfer' && subType == 'DVD') {
                    ftc_change_price.getPriceObject(dataType, filmType, 'Hard Drive', number)[ftc_change_price.getDataKeyName(dataType)] = newValue;
                }
        }
    },
    getSoundTransferObject: function(filmType) {
        return ftc_obb.mySearchObjectInArray(ftc_pricing.transferSoundPricePerFoot, "filmType", filmType);
    },
    getHardDriveObject: function(number) {
        return ftc_obb.mySearchObjectInArray(ftc_pricing.hardDrivePricing, "sizeGB", number);
    },
    getExtraCopiesObject: function(storage) {
        return ftc_obb.mySearchObjectInArray(ftc_pricing.extraCopies, "storage", storage);
    },
    getPriceObject: function(dataType, filmType, subType, number) {
        if (dataType == "Film Transfer") {
            var filmTypeData = ftc_obb.mySearchObjectInArray(ftc_pricing.filmTranferPricing, "filmType", filmType);
            var filmStorageData = ftc_obb.mySearchObjectInArray(filmTypeData.storages, "storage", subType);
            return ftc_obb.mySearchObjectInArray(filmStorageData.prices, 0, number);
        } else {
            return ftc_pricing;
        }
    },
    getDataKeyName: function(dataType) {
        if (dataType == "Film Transfer") {
            return 1;
        } else {
            if (dataType == "Feet") {
                return 0;
            } else {
                return "colorCorrectionPricePerFoot";
            }
        }
    },
    init: function() {
        ftc_change_price.percetageDiscount = ftc_change_price.getDiscountPercent();
        ftc_change_price.$filmTransferPriceArea = $("#filmTransferPriceArea");
        if (ftc_change_price.$filmTransferPriceArea.length > 0) {
            ftc_change_price.$validationMessage = $(".validation-summary-errors");
            ftc_change_price.showFilmTransferTable();
        }
        ftc_change_price.$hardDrivePriceArea = $("#hardDrivePriceArea");
        if (ftc_change_price.$hardDrivePriceArea.length > 0) {
            ftc_change_price.showHardDriveTable();
        }
        ftc_change_price.showExtraCopiesPrices();

        ftc_obb.submitForm("#changePricingForm", function($form, jsonResult) {
            ftc_obb.showPopupMessageNow("Changes Saved");
        });

    }
};

