﻿TextKing.SearchBox = function () {
    var that = {};

    that.GetSelectedQualityLevel = function () {
        return $('#SearchBox .quality-selection input[name=QualityLevelPK][type=radio]:checked').val();
    };

    return that;
} ();

// #### MG: Enums
var SourceTextInputMethodEnum = { "Text": 0, "File": 1, "WordCount": 2 };

// #### MG: Variables
var FirstLoadCompleted = false;
var UseExistingOrder = false;
var IsLandingpage = false;
var GlobalOrderPK = "";
var GlobalOrderStatusPK = "";
var GlobalSourceTextInputMethod = null;
var GlobalSourceText = "";
var GlobalFileUpload = false;
var GlobalFilePK = "";
var GlobalFileName = "";
var GlobalFileWordCount = 0;
var GlobalWordCount = 0;
var GlobalSourceLanguage = "";
var GlobalTargetLanguage = "";
var GlobalCategory = "49353AB0-FDBF-4E1C-A063-CDF4AAD98782";
var GlobalTextType = "9B8A64B0-14A7-4F2F-802A-3F775FFC63D6";
var GlobalCurrency = "FA1A805F-1126-40A2-AC5A-AE46160EE51A";
var GlobalResTextTargetLanguageSelectFirst = "--> [T]Bitte zuerst Ausgangssprache wählen";
var GlobalResTextCategorySelectFirst = "--> [T]Bitte zuerst Zielsprache wählen";
var GlobalResTextTextTypeSelectFirst = "--> [T]Bitte zuerst Zielsprache wählen";
var GlobalResTextInfo = "Bitte laden Sie eine Datei hoch, geben Sie die Anzahl Wörter ein oder schreiben Sie Ihren Text in das vorliegende Textfeld.";
var GlobalResTextPriceTotalPostfix = "";
var GlobalResTextPricePerWordPostfix = "";
var GlobalResTextTopicMissing = "";
var GlobalResTextSourceTextMissing = "";
var GlobalResTextWordCountMissing = "";
var GlobalResTextSourceDocMissing = "";
var GlobalResTextLanguageMissing = "";
var GlobalResTextFileNoWordCount = "";
var GlobalResTextFileNoWordCountTitle = "";
var GlobalResTextEnterText = "";
var GlobalResTextUploadFile = "";
var GlobalResTextWords = "";
var GlobalResTextDay = "";
var GlobalResTextDays = "";
var GlobalResTextUploadFileError = "";

// #### MG: Controls
var ControlSourceTextMethodText = "#RadioSourceTextMethod1";
var ControlSourceTextMethodFile = "#RadioSourceTextMethod2";
var ControlSourceTextMethodWordCount = "#RadioSourceTextMethod3";
var ControlSourceTextText = "#taTextToTranslate";
var ControlSourceTextFile = "";
var ControlSourceTextWordCount = "#TextBoxWordCount";
var ControlSourceLanguage = "#SourceLanguageLCID";
var ControlTargetLanguage = "#DestLanguageLCID";
var ControlCategory = "#CategoryPK";
var ControlTextType = "#TextTypePK";
var ControlResultPanelDefault = ".Step3View1";
var ControlResultPanelPrices = ".Step3View2";
var ControlResultPanelNoData = ".Step3View3";
var ControlSourceFileUploadButtonPanel = "#SourceFileUploadButtonPanel";
var ControlSourceFileUploadButton = "#SourceFileUploadButton";
var ControlSourceFileUploadLoading = "#SourceFileUploadLoading";
var ControlSourceFileUploadStatus = "#SourceFileUploadStatus";
var ControlButtonRefresh = "#ButtonRefresh";
var GlobalAlternativePageName = "A";

function SearchBox_Load() {
    // #### MG: Handling history.back()
    if (HasValidValue(GetHiddenOPK())) {
        window.location.href = "?orderPK=" + GetHiddenOPK();
    }

    AjaxLoader_Init();

    ControlsSourceTextMethod_Init();
    ControlsLanguageAndCategory_Init();
    ControlsQualityLevels_Init();

    IsLandingpage_Init();
    UseExistingOrder_Init();

    var refreshButtons = $('.btn-refresh');
    $.each(refreshButtons, function () {
        var button = $(this);
        var ajaxLoader = button.parent().find('.refresh-ajax-loader');
        button.unbind('click');
        button.click(function () {
            if (_gaq) {
                _gaq.push(['_trackEvent', 'Suchbox_B', 'Refresh_Button_Klick']);
            }
            button.hide();
            ajaxLoader.show();

            ExecuteSearch(
                function () {
                    button.show();
                    ajaxLoader.hide();
                },
                true
            );

        });
    });


    $(ControlButtonRefresh).click(function () {
        if (_gaq) {
            _gaq.push(['_trackEvent', 'Suchbox_B', 'Preis_Berechnen_Klick']);
        }

        ExecuteSearch(null, true);
    });

    $('#SearchBox .quality-selection input[name=QualityLevelPK][type=radio]').change(function () {
        GetPricePerWord(GlobalSourceLanguage, GlobalTargetLanguage, GlobalCategory, TextKing.SearchBox.GetSelectedQualityLevel());
        ExecuteSearch();
    });

    GetPricePerWord(null, null, null, null);
}

function GetPricePerWord(srcLCID, dstLCID, categoryPK, qualityPK) {
    TextKing.InlineListing.disableControls();
    $.ajax(
        {
            type: "POST",
            url: '/Search/GetPricePerWord',
            dataType: "json",
            data: { sourceLanguageLCID: srcLCID, destLanguageLCID: dstLCID, categoryPK: categoryPK, qualityPK: qualityPK },
            success: function (data) {
                if (!CheckProvidedUserInput(false)) {
                    var pPW = data.PricePerWord + " " + GlobalResTextPricePerWordPostfix;
                    $("#price-footer").empty();
                    $("#price-text").empty();
                    $("#price-text").append(pPW);
                }
            }
        });
}

function IsLandingpage_Init() {
    if (IsLandingpage) {
        try {
            if (GlobalSourceLanguage != 0 && GlobalSourceLanguage != null) {
                $(ControlSourceLanguage).val(GlobalSourceLanguage);
                $(ControlSourceLanguage).trigger("change");
            }
        }
        catch (ex) {
            ThrowException(ex.Description);
        }
    }
}

function UseExistingOrder_Init() {
    // #### MG: Load existing data if available
    if (UseExistingOrder) {

        try {
            SetHiddenOPK(GlobalOrderPK);

            // #### MG: Step 1
            if (GlobalSourceTextInputMethod == SourceTextInputMethodEnum.Text) {
                $(ControlSourceTextMethodText).trigger("click");
                ShowWordCount(GlobalWordCount);
            }
            else if (GlobalSourceTextInputMethod == SourceTextInputMethodEnum.File) {
                $(ControlSourceTextMethodFile).trigger("click");
                GlobalFileUpload = true;
                SourceFileUpload_Success(GlobalFilePK, GlobalFileName);
            }
            else if (GlobalSourceTextInputMethod == SourceTextInputMethodEnum.WordCount) {
                $(ControlSourceTextMethodWordCount).trigger("click");
                $(ControlSourceTextWordCount).val(GlobalWordCount);
            }
            else {
                ThrowException("SourceTextMethod not supported!");
            }

            // #### MG: Step 2
            $(ControlSourceLanguage).val(GlobalSourceLanguage);
            $(ControlSourceLanguage).trigger("change");
        }
        catch (ex) {
            ThrowException(ex.Description);
        }
    }
    else {
        // #### MG: Set OrderStatusPK to "InSearchBox"
        GlobalOrderStatusPK = "F0A3A257-AA71-4010-9131-BC5940B7FEAB";
        $(ControlSourceTextText).val(GlobalResTextInfo);
        $(ControlSourceTextMethodText).attr("checked", "checked");
    }
}

function ControlsSourceTextMethod_Init() {

    // #### MG: Supported text methods are: Text / File / WordCount

    // #### MG: Hide all source text method panels
    $("div.PanelSourceTextMethod").hide();

    // #### MG: Show only text input method
    $(".PanelSourceTextMethodText").show();

    // #### MG: Show appropriate panel on click
    $("input[name=\"RadioSourceTextMethod\"]:radio").click(function () {

        // #### MG: Hide all source text method panels
        $("div.PanelSourceTextMethod").hide();

        // #### MG: Show appropriate panel
        $(".PanelSourceTextMethod" + $(this).val()).show();
    });

    // start B version

    $('.toggle-upload-link').unbind('click');
    $('.toggle-upload-link').click(function () {
        if ($('.PanelSourceTextMethod.PanelSourceTextMethodText').is(':hidden')) {
            $('.PanelSourceTextMethod.PanelSourceTextMethodFile').hide();
            $('.PanelSourceTextMethod.PanelSourceTextMethodText').show();
            $(this).html(GlobalResTextUploadFile);
        } else {

            $('.PanelSourceTextMethod.PanelSourceTextMethodText').hide();
            $('.PanelSourceTextMethod.PanelSourceTextMethodFile').show();
            $(this).html(GlobalResTextEnterText);
        }

        return false;
    });

    // end B version

    ControlSourceTextMethodText_Init();
    ControlSourceTextMethodFile_Init();
    ControlSourceTextMethodWordCount_Init();
}

function ControlSourceTextMethodText_Init() {
    $(ControlSourceTextText).focus(function () {
        if ($(ControlSourceTextText).val() == GlobalResTextInfo) {
            $(ControlSourceTextText).val("");
        }
    });

    $(ControlSourceTextText).focusout(function () {

        if ($(ControlSourceTextText).val() == GlobalResTextInfo) {
            return;
        }

        if ($(ControlSourceTextText).val() == "") {
            $(ControlSourceTextText).val(GlobalResTextInfo);
            GlobalSourceText = "";
            ResetResultPanel();
            GetPricePerWord(GlobalSourceLanguage, GlobalTargetLanguage, GlobalCategory, TextKing.SearchBox.GetSelectedQualityLevel());
            return;
        }

        GlobalSourceTextInputMethod = SourceTextInputMethodEnum.Text;
        GlobalSourceText = $(ControlSourceTextText).val();

        $.ajax(
        {
            type: "POST",
            url: '/Search/HandleDataInputMethodText',
            dataType: "json",
            data: "orderPK=" + GetHiddenOPK() + "&text=" + encodeURIComponent(GlobalSourceText),
            success: function (data) {
                if (data.ErrorCode == 0) {
                    GlobalWordCount = data.WordCount;
                    SetHiddenOPK(data.OrderPK);
                    ShowWordCount(GlobalWordCount);

                    // #### MG: Execute search
                    ExecuteSearch();
                }
                else {
                    ThrowException("Error from ControlSourceTextMethodText_Init() = " + data.ErrorMessage);
                }
            }
        });
    });

    $(ControlSourceTextMethodText).change(function () {
        if (GetHiddenOPK() != null && $(ControlSourceTextText).val() != GlobalResTextInfo && $(ControlSourceTextText).val().length > 0) {
            $.ajax(
            {
                type: "POST",
                url: '/Search/HandleDataInputMethodSwitchToText',
                dataType: "json",
                data: "orderPK=" + GetHiddenOPK(),
                success: function (data) {
                    if (data.ErrorCode == 0) {
                        GlobalWordCount = data.WordCount;
                        ShowWordCount(GlobalWordCount);

                        // #### MG: Execute search
                        ExecuteSearch();
                    }
                    else {
                        ThrowException("Error switching DataInputMethod. " + data.ErrorMessage);
                    }
                }
            });
        }
        else {
            ResetResultPanel();
        }
    });
}

function ControlSourceTextMethodFile_Init() {
    new AjaxUpload(ControlSourceFileUploadButton, {
        action: '/Search/HandleDataInputMethodFile',
        name: 'file',
        data: { orderPK: GetHiddenOPK() },
        onSubmit: function (file, extension) {
            this.setData({ orderPK: GetHiddenOPK() });
            SourceFileUpload_Go(file);
        },
        onComplete: function (file, response, data) {
            try {
                var data = Sys.Serialization.JavaScriptSerializer.deserialize(response);

                GlobalFileName = data.DocumentName;
                GlobalFilePK = data.DocumentPK;
                GlobalFileWordCount = data.WordCount;
                GlobalFileUpload = true;

                SetHiddenOPK(data.OrderPK);
                GlobalSourceTextInputMethod = SourceTextInputMethodEnum.File;
                GlobalWordCount = data.WordCount;

                if (GlobalWordCount > 0) {
                    SourceFileUpload_Success(data.DocumentPK, data.DocumentName);
                }
                else {
                    SourceFileUpload_Failure(GlobalResTextFileNoWordCount);
                }

                ExecuteSearch();
            }
            catch (ex) {
                SourceFileUpload_Failure(GlobalResTextUploadFileError);
                ThrowException("Exception: " + ex.Description);
            }
        }
    });

    $(ControlSourceTextMethodFile).change(function () {
        if (GetHiddenOPK() != null && $(ControlSourceFileUploadStatus + " > a").length > 0) {
            $.ajax(
            {
                type: "POST",
                url: '/Search/HandleDataInputMethodSwitchToFile',
                dataType: "json",
                data: "orderPK=" + GetHiddenOPK(),
                success: function (data) {
                    if (data.ErrorCode == 0) {
                        GlobalWordCount = data.WordCount;

                        ExecuteSearch();
                    }
                    else {
                        ThrowException("Error switching DataInputMethod. " + data.ErrorMessage);
                    }
                }
            });
        }
        else {
            ResetResultPanel();
        }
    });
}

function SourceFileUpload_Go(filename) {
    $(ControlSourceFileUploadButtonPanel).hide();
    $(ControlSourceFileUploadStatus).hide();
    $(ControlSourceFileUploadStatus).empty();
    $(ControlSourceFileUploadLoading).show();
    //$(ControlSourceFileUploadStatus).append("<img src=\"/Content/Style/images/ajax-loader.gif\" alt=\"\" />");
};

function SourceFileUpload_Success(filePK, filename) {
    if (filename.length >= 30) {
        var part1 = filename.substr(0, 25);
        var part2 = filename.substr(filename.length - 5, 5);
        filename = part1 + part2;
    }

    $(ControlSourceFileUploadButtonPanel).show();
    $(ControlSourceFileUploadLoading).hide();
    $(ControlSourceFileUploadStatus).empty();
    $(ControlSourceFileUploadStatus).append("<a href='/Order/DownloadTranslationDocument?translationDocumentPK=" + filePK + "'>" + filename + "</a>");
    $(ControlSourceFileUploadStatus).show();
};

function SourceFileUpload_Failure(message) {
    $.ajax({
        type: "GET",
        url: "/Search/ZeroWordCountDocumentNotice",
        cache: true,
        data: {},
        success: function (data) {
            var windowElement = $.telerik.window.create({
                title: GlobalResTextFileNoWordCountTitle,
                name: "file-zero-word-count-notice",
                html: data,
                width: "455",
                height: "270",
                modal: true,
                resizable: false,
                draggable: false,
                scrollable: false
            });

            windowElement.data('tWindow').center().open();
            $(windowElement).find('.btn-rounded-yellow').click(function () {
                windowElement.data('tWindow').close();
            });

            $(ControlSourceFileUploadButtonPanel).show();
            $(ControlSourceFileUploadLoading).hide();
            $(ControlSourceFileUploadStatus).empty();
            $(ControlSourceFileUploadStatus).append(message);
            $(ControlSourceFileUploadStatus).show();
        }
    });
};

function ControlSourceTextMethodWordCount_Init() {
    $(ControlSourceTextWordCount).focusout(function () {
        GlobalSourceTextInputMethod = SourceTextInputMethodEnum.WordCount;
        GlobalWordCount = $(this).val();

        if (HasValidValue(GlobalWordCount)) {
            $.ajax(
            {
                type: "POST",
                url: '/Search/HandleDataInputMethodWordCount',
                dataType: "json",
                data: "orderPK=" + GetHiddenOPK() + "&wordCount=" + GlobalWordCount,
                success: function (data) {
                    if (data.ErrorCode == 0) {
                        SetHiddenOPK(data.OrderPK);

                        // #### MG: Execute search
                        ExecuteSearch();
                    }
                    else {
                        alert(data.ErrorMessage);
                    }
                }
            });
        }
        else {
            ResetResultPanel();
        }
    });

    $(ControlSourceTextMethodWordCount).change(function () {
        if (GetHiddenOPK() != null && $(ControlSourceTextWordCount).val().length > 0) {
            $.ajax(
            {
                type: "POST",
                url: '/Search/HandleDataInputMethodSwitchToWordCount',
                dataType: "json",
                data: "orderPK=" + GetHiddenOPK(),
                success: function (data) {
                    if (data.ErrorCode == 0) {
                        GlobalWordCount = data.WordCount;

                        // #### MG: Execute search
                        ExecuteSearch();
                    }
                    else {
                        ThrowException("Error switching DataInputMethod. " + data.ErrorMessage);
                    }
                }
            });
        }
        else {
            ResetResultPanel();
        }
    });
}

function ControlsLanguageAndCategory_Init() {

    ControlSourceLanguage_Init();
    ControlTargetLanguage_Init();
    ControlCategory_Init();
}

function ControlSourceLanguage_Init() {
    $(ControlSourceLanguage).change(function () {

        GlobalSourceLanguage = $(ControlSourceLanguage + " :selected").val();

        if (FirstLoadCompleted) {
            GlobalTargetLanguage = null;
            ResetCategories();
            ResetResultPanel();
        }
        GetPricePerWord(GlobalSourceLanguage, GlobalTargetLanguage, GlobalCategory, TextKing.SearchBox.GetSelectedQualityLevel());

        if (GlobalSourceLanguage != "") {

            // start B
            $('#SourceLanguageNotSelected').hide();
            $(ControlTargetLanguage).hide();

            $('#TargetLanguageLoading').show();
            // end B

            $.ajax({
                type: "POST",
                url: '/Search/GetDestLanguagesB',
                dataType: "json",
                data: { sourceLanguageLCID: GlobalSourceLanguage },
                success: function (data) {

                    // start B
                    $(ControlTargetLanguage).show();
                    $('#SourceLanguageNotSelected').hide();
                    $('#TargetLanguageLoading').hide();

                    // end B
                    // #### MG: Remove all options but first
                    var firstOption = $(ControlTargetLanguage).find("option:first");
                    $(ControlTargetLanguage).empty();
                    $(ControlTargetLanguage).append(firstOption);
                    //$(ControlTargetLanguage).remove("option:not(:first)");

                    if (data.length < 1) {
                        ThrowException("NO DATA");
                        return;
                    }
                    else { // #### MG: Select first target language and fire target language changed event
                        $.each(data, function (index, optionData) {
                            var option = '<option value="' + optionData.LCID + '">' + optionData.LanguageName + '</option>';
                            $(ControlTargetLanguage).append(option);
                        });

                        if (UseExistingOrder || IsLandingpage) {
                            $(ControlTargetLanguage).val(GlobalTargetLanguage);
                            $(ControlTargetLanguage).trigger('change');
                        }
                        else {
                            if (data.length == 1) {
                                $(ControlTargetLanguage).get(0).selectedIndex = 1;
                                $(ControlTargetLanguage).trigger('change');
                            }
                            else {
                                // #### MG: Reset categories
                                GlobalTargetLanguage = null;
                                ResetCategories();
                            }
                        }
                    }
                }
            });
        }
        else {
            $(ControlTargetLanguage).val(0);
            $(ControlTargetLanguage).trigger('change');
            $(ControlTargetLanguage).hide();
            $('#SourceLanguageNotSelected').show();
            $('#TargetLanguageLoading').hide();
        }
    });
}

function ControlTargetLanguage_Init() {

    $(ControlTargetLanguage).change(function () {

        GlobalTargetLanguage = $(ControlTargetLanguage + " :selected").val();

        if (GlobalTargetLanguage != '') {
            GetPricePerWord(GlobalSourceLanguage, GlobalTargetLanguage, GlobalCategory, TextKing.SearchBox.GetSelectedQualityLevel());
            ExecuteSearch();
            LoadCategories();
        }
        else {
            $(ControlCategory).val(0);
            $('#LanguagesNotSelected').show();
            $(ControlCategory).hide();
            $('#TextTypesLoading').hide();
        }
    });

    $(ControlTargetLanguage).click(function () {
        if ($(ControlTargetLanguage + " option").length <= 1) {
            $(ControlTargetLanguage).append("<option value=\"\">" + GlobalResTextTargetLanguageSelectFirst + "</option>");
        }
    });
}

function ControlCategory_Init() {
    $(ControlCategory).change(function () {
        GlobalCategory = $(ControlCategory + " :selected").val();
        GetPricePerWord(GlobalSourceLanguage, GlobalTargetLanguage, GlobalCategory, TextKing.SearchBox.GetSelectedQualityLevel());
        // #### MG: Execute search
        ExecuteSearch();
    });

    $(ControlCategory).click(function () {
        if ($(ControlCategory + " option").length <= 1) {
            $(ControlCategory).append("<option value=\"\">" + GlobalResTextCategorySelectFirst + "</option>");
        }
    });
}

// #### MG: Load categories
function LoadCategories(caller) {
    if (GlobalTargetLanguage != "") {
        var button = $('#categories-refresh-button');
        var ajaxLoader = button.parent().find('.refresh-ajax-loader');

        //  start B
        $('#LanguagesNotSelected').hide();
        $(ControlCategory).hide();
        $('#TopicAreasLoading').show();
		// end B

        button.hide();
        ajaxLoader.show();
        $.ajax({
            type: "POST",
            url: '/Search/GetCoveredCategories',
            data: { sourceLanguageLCID: GlobalSourceLanguage, destinationLanguageLCID: GlobalTargetLanguage },
            success: function (data) {

                //  start B
                $('#LanguagesNotSelected').hide();
                $('#TopicAreasLoading').hide();
                $(ControlCategory).show();
                // end B

                ajaxLoader.hide();
                button.show();

                $('#category-ajax-loader').hide();

                // #### MG: Remove all options but first
                var firstOption = $(ControlCategory).find("option:first");
                $(ControlCategory).empty();
                $(ControlCategory).append(firstOption);

                if (data.length < 1) {
                    ThrowException("NO DATA");
                    return;
                }
                else { // #### MG: Select first option and fire changed event
                    $.each(data, function (index, optionData) {
                        var option = '<option value="' + optionData.CategoryPK + '">' + optionData.CategoryName + '</option>';
                        $(ControlCategory).append(option);
                    });

                    if (UseExistingOrder) {
                        $(ControlCategory).val(GlobalCategory);
                        $(ControlCategory).trigger('change');
                    }
                    else {
                        if (data.length >= 1) {
                            $(ControlCategory).get(0).selectedIndex = 1;
                            $(ControlCategory).trigger('change');
                        }
                        else {
                            $(ControlCategory).get(0).selectedIndex = 0;
                        }
                    }
                }
            }
        });
    }
}

// #### MG: Reset categories
function ResetCategories() {
    GlobalCategory = null;
    var firstOption = $(ControlCategory).find("option:first");
    $(ControlCategory).empty();
    $(ControlCategory).append(firstOption);
}

// #### MG: Reset Price-Panel
function ResetResultPanel() {
    $(ControlResultPanelDefault).show();
    $(ControlResultPanelPrices).hide();
    $(ControlResultPanelNoData).hide();
}

function ShowWordCount(words) {
    $("#divWordCount").empty().append(words);
}

function GetHiddenOPK() {
    return $("#hiddenOPK").val();
}

function SetHiddenOPK(val) {
    $("#hiddenOPK").val(val);
    GlobalOrderPK = val;
}

function ControlsQualityLevels_Init() {
    $("div.QualityLevelCollapsiblePanel").hide();

    var pan1 = "QualityLevel1CollapsiblePanel";
    var pan2 = "QualityLevel2CollapsiblePanel";
    var pan3 = "QualityLevel3CollapsiblePanel";
    var pan4 = "QualityLevel4CollapsiblePanel";
    var pan1trigger = "." + pan1 + "Trigger";
    var pan2trigger = "." + pan2 + "Trigger";
    var pan3trigger = "." + pan3 + "Trigger";
    var pan4trigger = "." + pan4 + "Trigger";
    var imgOpen = "/Content/Style/images/open_icon.gif";
    var imgClose = "/Content/Style/images/close_icon.gif";

    $(pan1trigger).toggle(function () { $(this).children("img").attr("src", imgClose); },
        function () { $(this).children("img").attr("src", imgOpen); });

    $(pan2trigger).toggle(function () { $(this).children("img").attr("src", imgClose); },
        function () { $(this).children("img").attr("src", imgOpen); });

    $(pan3trigger).toggle(function () { $(this).children("img").attr("src", imgClose); },
        function () { $(this).children("img").attr("src", imgOpen); });

    $(pan4trigger).toggle(function () { $(this).children("img").attr("src", imgClose); },
        function () { $(this).children("img").attr("src", imgOpen); });

    $(pan1trigger).click(function () {
        //QualityLevelsCollapsiblePanels_Close();
        $("#" + pan1).slideToggle("fast");
    });

    $(pan2trigger).click(function () {
        //QualityLevelsCollapsiblePanels_Close();
        $("#" + pan2).slideToggle("fast");
    });

    $(pan3trigger).click(function () {
        //QualityLevelsCollapsiblePanels_Close();
        $("#" + pan3).slideToggle("fast");
    });

    $(pan4trigger).click(function () {
        //QualityLevelsCollapsiblePanels_Close();
        $("#" + pan4).slideToggle("fast");
    });
}

function QualityLevelsCollapsiblePanels_Close() {
    var pan1 = "#QualityLevel1CollapsiblePanel";
    var pan2 = "#QualityLevel2CollapsiblePanel";
    var pan3 = "#QualityLevel3CollapsiblePanel";
    var pan4 = "#QualityLevel4CollapsiblePanel";

    $(pan1).slideUp("fast");
    $(pan2).slideUp("fast");
    $(pan3).slideUp("fast");
    $(pan4).slideUp("fast");
}

function ExecuteSearch(callback, showAlert) {
    TextKing.InlineListing.disableControls();
    
    if (!CheckProvidedUserInput(showAlert)) {
        // #### MG: User input is not complete (required input is outstanding) - DO NOTHING;
        ResetResultPanel();
        if (callback != null) {
            callback(false);
        }
        return;
    }
    else {
        // #### MG: User input is complete - EXECUTE THE SEARCH        
        opk = GetHiddenOPK();

        if (opk == "" || opk == undefined) {
            if (callback != null) {
                callback(false);
            }
            // ThrowException("OPK is empty!");
            return;
        }

        if (!HasValidValue(GlobalOrderStatusPK)) {
            GlobalOrderStatusPK = "A17A3854-AC0C-47B5-93DB-1C7AD897822A";
        }

        if (!HasValidValue(GlobalCategory)) {
            GlobalCategory = "11111111-1111-1111-1111-111111111111";
        }

//        if (!HasValidValue(GlobalTextType)) {
//            GlobalTextType = "00000000-0000-0000-0000-000000000000";
//        }

        $('#price-text').hide();
        $('#processing-text').hide();
        $('#price-loading').show();
        
        // #### MG: Show resultset
        $.ajax(
            {
                type: "POST",
                url: '/Search/GetPrice',
                data: "sourceLanguageLCID=" + GlobalSourceLanguage + "&destLanguageLCID=" + GlobalTargetLanguage
                    + "&categoryPK=" + GlobalCategory + "&hiddenOPK=" + opk + "&orderStatusPK=" + GlobalOrderStatusPK
                    + "&currencyPK=" + GlobalCurrency + "&documentUploaded=" + GlobalFileUpload + "&textTypePK=" + GlobalTextType
                    + "&qualityPK=" + TextKing.SearchBox.GetSelectedQualityLevel(),
                success: function (data) {

                    $('#price-loading').hide();
                    $('#processing-text').show();
                    //  $("#price-footer").show();
                    $('#price-text').show();

                    if (callback != null) {
                        callback(true);
                    }
                    if (data.ErrorMessage != null) {
                        ThrowException(data.ErrorMessage);
                        ResetResultPanel();
                        return;
                    }
                    else {
                        if (_gaq) {
                            _gaq.push(['_trackPageview', 'Search/GetPrice_B']);
                        }

                        var dataAvailable = false;

                        if (data.QualityLevel3Available) {
                            dataAvailable = true;

                            var wordCount = 0;
                            if (GlobalSourceTextInputMethod == SourceTextInputMethodEnum.File) {
                                wordCount = GlobalFileWordCount;
                            }
                            else if (GlobalSourceTextInputMethod == SourceTextInputMethodEnum.Text) {
                                wordCount = GlobalWordCount;
                            }

                            var selectedCategoryPK = TextKing.SearchBox.GetSelectedQualityLevel();
                            var qualityPrice = 0;
                            var qualityPriceString = "";

                            switch (selectedCategoryPK) {
                                case data.QualityLevel1PK:
                                    qualityPrice = data.QualityLevel1Price;
                                    qualityPriceString = data.QualityLevel1PriceString
                                    break;

                                case data.QualityLevel2PK:
                                    qualityPrice = data.QualityLevel2Price;
                                    qualityPriceString = data.QualityLevel2PriceString
                                    break;

                                case data.QualityLevel3PK:
                                    qualityPrice = data.QualityLevel3Price;
                                    qualityPriceString = data.QualityLevel3PriceString
                                    break;

                                case data.QualityLevel4PK:
                                    qualityPrice = data.QualityLevel4Price;
                                    qualityPriceString = data.QualityLevel4PriceString
                                    break;
                            }

                            var pricePerWord = (qualityPrice / wordCount).toFixed(2);

                            $("#price-footer").empty();
                            $("#price-text").empty();
                            $("#price-footer").append(wordCount + " " + GlobalResTextWords + ", " + pricePerWord + " \u20ac " + GlobalResTextPricePerWordPostfix);
                            $("#price-text").append(qualityPriceString);
                        }

                        $('#processing-time').empty();

                        var processingTimeStr = data.ProcessingTime + " " + GlobalResTextDay;
                        if (data.ProcessingTime > 1) {
                            processingTimeStr = data.ProcessingTime + " " + GlobalResTextDays;
                        }

                        $('#processing-time').append(processingTimeStr);
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    ThrowException("ERROR: " + xhr.responseText);
                }
            });

        FirstLoadCompleted = true;
    }
}


function CheckProvidedUserInput(showAlert) {
    var result = false;
    var errorMessage = '';

    if (!CheckLanguagesAndTopicArea(showAlert)) {
        result = false;
    }
    else if (!HasValidValue(GlobalSourceTextInputMethod)) {
        errorMessage = GlobalResTextSourceTextMissing;
        result = false;
    }
    else {
        switch (GlobalSourceTextInputMethod) {
            case SourceTextInputMethodEnum.Text:
                result = HasValidValue(GlobalSourceText);
                break;
            case SourceTextInputMethodEnum.File:
                result = GlobalFileUpload;
                break;
            case SourceTextInputMethodEnum.WordCount:
                result = true;
                break;
        }

        if (!result || GlobalWordCount == 0) {
            errorMessage = GlobalResTextSourceTextMissing;
            result = false;
        }
        else {
            result = true;
        }
    }

    if (!result) {
        if (showAlert && errorMessage != '') {
            alert(errorMessage);
        }
        return false;
    }
    else {
        return true;
    }
}


function CheckLanguagesAndTopicArea(showAlert) {
    if (!HasValidValue(GlobalSourceLanguage)) {
        if (showAlert) {
            alert(GlobalResTextLanguageMissing);
        }
        return false;
    }
    else if (!HasValidValue(GlobalTargetLanguage)) {
        if (showAlert) {
            alert(GlobalResTextLanguageMissing);
        }
        return false;
    }
    else if (!HasValidValue(GlobalCategory)) {
        if (showAlert) {
            alert(GlobalResTextTopicMissing);
        }
        return false;
    }
    else {
        return true;
    }
//    else if (!HasValidValue(GlobalTextType)) {
//        if (showAlert) {
//            alert(GlobalResTextTopicMissing);
//        }
//        return false;
}


function AjaxLoader_Init() {
    $("#loading").ajaxStart(function () {
        $(this).show();
    });
    $("#loading").ajaxStop(function () {
        $(this).hide();
    });
}

function HasValidValue(val) {
    return (val != null && val.toString().length > 0);
}

function ThrowException(msg) {
    if (window.location.hostname.indexOf(".dev") > -1) {
        // alert(msg);
		throw msg;
    }
    else {
        //throw msg;
    }
}

