﻿/* 
* Copyright: Defaqto Ltd
* Website: www.defaqto.com
* Date: 25/11/2008
*/
var comboText;
var alertTimerId = 0;


function DropDown(endPointUrl, containerId, ctrlId, dropDownId, displayConfigurationId, columnIndex, questions, trackingProcessorId, usageTrackWaitMilliseconds, enableOurProductFunctionality, ourProductsArray, competitorProductsArray, ourProductHeaderText, competitorProductHeaderText, defaultHeaderTextValues) {

    this.Questions = questions;
    this.ContainerId = containerId;
    this.GuidValue = document.getElementById(guid).value;
    this.ControlId = ctrlId;
    this.DisplayConfigurationId = displayConfigurationId;
    this.DropDownId = dropDownId;
    this.SelectText = "Please select...";
    this.EndPoint = document.location.protocol + '//' + endPointUrl + "/ajaxEndpoint/";
    this.Index = columnIndex;
    this.TrackingProcessorId = trackingProcessorId;
    this.objControl = document.getElementById(this.ContainerId + "_" + this.ControlId);
    this.EnableOurProductFunctionality = enableOurProductFunctionality.toLowerCase();
    this.OurProductsArray = ourProductsArray;
    this.CompetitorProductsArray = competitorProductsArray;
    this.OurProductHeaderText = ourProductHeaderText;
    this.CompetitorProductHeaderText = competitorProductHeaderText;
    this.OurProductHeaderTextCssClass = "ourProductHeaderText";
    this.CompetitorProductHeaderTextCssClass = "competitorProductHeaderText";
    this.OurProductAnswerCssClass = "ourProductAnswer";
    this.CompetitorProductAnswerCssClass = "competitorProductAnswer";
    this.DefaultHeaderTextValues = defaultHeaderTextValues;

   
  
    //Add trim method to string object
    String.prototype.trim = function() {
        return this.replace(/\,$/, '');
    }

    //Raised when dropdown is changed
    DropDown.prototype.onchange = function(scope) {

        var objControl = scope.objControl;
        var productId = objControl.options[objControl.selectedIndex].value;

        if (productId < 1) {

            //'please select' selected in drop down
            for (var i = 0; i < scope.Questions.length; i++) {
                scope.onChangeEventFlush(scope.Questions[i], scope);

                //reset cells to not print
                var Cell = document.getElementById(scope.ContainerId + "_Cell" + scope.Questions[i] + "-" + scope.Index); //gets cell object
                if (Cell == null) {
                    PopuateFooter(scope.ContainerId, '', scope.Questions[i], '', scope.Index, '',false)
                }
                else 
                {

                    Cell.className = 'productCellHide'; // set cell css to print
                }
            }

            //reset product column header to hide and set the default text
            var headerCell = document.getElementById(scope.ContainerId + "_productColumn" + scope.Index);
            var productTitle = document.getElementById(scope.ContainerId + "_productTitle" + scope.Index);
            var productImage = document.getElementById(scope.ContainerId + "_productImage" + scope.Index);
            var defaultText = scope.DefaultHeaderTextValues[scope.Index];

            if (defaultText.toLowerCase() == 'null') {
                defaultText = '';
            }

            headerCell.className = 'productColumnHide';
            productTitle.innerHTML = defaultText;
            productTitle.style.visibility = 'visible';
            productImage.style.visibility = 'hidden';

            return;
        }
        else {
            for (var i = 0; i < scope.Questions.length; i++) {
                scope.onChangeEventFlush(scope.Questions[i], scope);
            }

            var headerCell = document.getElementById(scope.ContainerId + "_productColumn" + scope.Index);
            headerCell.className = 'productColumn';

            scope.LoadProductHeader(productId, scope);
            scope.LoadAnswers(scope, productId);

            comboText = objControl.value;
            if (alertTimerId != 0) {
                clearTimeout(alertTimerId);

            }
            // call timer to set up usage call if nothing changes for usageTrackWaitMilliseconds period
            alertTimerId = setTimeout(function() { ontimer(objControl.value, scope.TrackingProcessorId) }, usageTrackWaitMilliseconds);

        }
    }

    function ontimer(timedControlValue, trackingProcessorIdentifier) {
        //get the combo box
        if (comboText == timedControlValue) {
			// call the MI tracking function.
            window[trackingProcessorIdentifier.ProductDropDownChanged(trackingProcessorIdentifier)];
        }
        alertTimerId = 0;
    }


    DropDown.prototype.LoadAnswers = function(scope, productId) {
        var xmlHttpObj = CreateXmlHttpRequestObject();
        var cellHasData = false; // used to check if at least one cell has data
        var ddlPlanSelected = $('#' + scope.ContainerId + "_" + scope.ControlId + ' option:selected').text();

        if (xmlHttpObj) {
            var url = scope.EndPoint + "LoadAnswersByQuestionIdsAsJson";
            xmlHttpObj.open("POST", url, true);

            xmlHttpObj.onreadystatechange = function() {
                if (xmlHttpObj.readyState == READYSTATE_COMPLETE) {
                    if (xmlHttpObj.status == HTTPSTATUS_OK) {
                        var result = eval('(' + xmlHttpObj.responseText + ')');
                        result = result.d;
                        if (result != null) {
                            for (var i = 0; i < scope.Questions.length; i++) {

                                var ColumnData = document.getElementById(scope.ContainerId + "_CellData" + scope.Questions[i] + "-" + scope.Index);
                                var ColumnImage = document.getElementById(scope.ContainerId + "_CellImg" + scope.Questions[i] + "-" + scope.Index);

                                var questionDescription = "";
                                var QuestionCell = document.getElementById(scope.ContainerId + "_QuestionCell" + scope.Questions[i]);

                                // if the question it visible in the grid then we can update the answer.
                                if (result[i].VisibleQuestion == true) {

                                    if (QuestionCell != null) {
                                        questionDescription = QuestionCell.innerHTML
                                    }
                                    else {
                                        var QuestionDropDown = document.getElementById(scope.ContainerId + "_ddlQuestion" + scope.Questions[i]);
                                        questionDescription = QuestionDropDown.options[QuestionDropDown.selectedIndex].innerHTML;
                                    }

                                    var answerCellId = scope.ContainerId + "_AnswerCell" + scope.Questions[i];
                                    var answerCell = document.getElementById(answerCellId);

                                    ColumnData.setAttribute("productId", productId);
                                    ColumnImage.setAttribute("productId", productId);
                                }

                                if (result[i].BrochureDisplayType == 1) {

                                    ColumnData.innerHTML = result[i].BrochureText;
                                }
                                else if (result[i].BrochureDisplayType == 2) {

                                    ColumnData.style.cursor = "pointer";
                                    ColumnData.style.color = "#0000FF";
                                    ColumnData.style.textDecoration = "underline";
                                    ColumnData.innerHTML = result[i].DisplayText;

                                    var brochureText = result[i].BrochureText;
                                    var title = questionDescription + " - " + ddlPlanSelected;

                                    ColumnData.onclick = scope.SetBrochureTextPopup(scope, title, brochureText);

                                }
                                else if (result[i].BrochureDisplayType == 3) {

                                    var title = ddlPlanSelected + ' ' + questionDescription;
                                    PopuateFooter(scope.ContainerId, title,result[i].QuestionId, result[i].QuestionTitle, scope.Index, result[i].BrochureText,true)
                                    
                                }
                                else {
                                    ColumnData.innerHTML = result[i].DisplayText;
                                }

                                //check if we have some data for cell - if true set cellHasData true
                                if (result[i].DisplayText != "") {
                                    cellHasData = true;
                                }

                                // if the question it visible in the grid then we can update the answer.
                                if (result[i].VisibleQuestion == true) {

                                    ColumnImage.src = result[i].DisplayImageUrl;
                                    ColumnImage.alt = result[i].DisplayText;
                                    ColumnImage.style.visibility = 'visible';
                                }
                            }

                            // if at least one cell has data loop through cells and set css style to view when printed
                            if (cellHasData) {

                                for (var i = 0; i < scope.Questions.length; i++) {

                                    var Cell = document.getElementById(scope.ContainerId + "_Cell" + scope.Questions[i] + "-" + scope.Index); //gets cell object

                                    if (Cell != null) {

                                        Cell.className = 'productCell';

                                        if (scope.IsProductsOurs(productId, scope)) {
                                            Cell.className += ' ' + scope.OurProductAnswerCssClass;
                                        }
                                        else if (scope.IsProductsCompetitors(productId, scope)) {
                                            Cell.className += ' ' + scope.CompetitorProductAnswerCssClass;
                                        }
                                    }
                                }
                            } // end if cellHasData
                        }
                        else {
                            alert("You do not have permission to use this service method.");
                        }
                    }
                    else {
                        var fault = xmlHttpObj.responseText;
                        alert("Error Occured! \n\n" + fault);
                    }
                }
            }

            var questions = "";

            for (var i = 0; i < scope.Questions.length; i++) {
                var ColumnData = document.getElementById(scope.ContainerId + "_ddlQuestion" + scope.Questions[i]);
                if (ColumnData != null) {
                    questions = questions + ColumnData.options[ColumnData.selectedIndex].value + ",";
                }
                else {
                    questions = questions + scope.Questions[i] + ",";
                }
            }

            var body = '{"sessionToken":"' + scope.GuidValue + '","displayConfigurationId":' + scope.DisplayConfigurationId + ',"productId":' + productId + ',"questionIds":[' + questions.trim() + ']}';
            xmlHttpObj.setRequestHeader("Content-type", "application/json");
            xmlHttpObj.send(body);
        }

    }

    DropDown.prototype.SetBrochureTextPopup = function(scope, title, brochureText) 
    {
        return function()
        {
            ShowHelpDialog(scope.ContainerId, "helpWrapper", "helpTitle", "helpText", brochureText, title, false);
        }
    }
    
    DropDown.prototype.LoadProductHeader = function(productId, scope) {
        var instance = scope;
        if (productId > 0) {

            var xmlHttpObj = CreateXmlHttpRequestObject();
            if (xmlHttpObj) {
                var url = instance.EndPoint + "LoadProductHeader";

                xmlHttpObj.open("POST", url, true);
                xmlHttpObj.onreadystatechange = function() {
                    if (xmlHttpObj.readyState == READYSTATE_COMPLETE) {
                        if (xmlHttpObj.status == HTTPSTATUS_OK) {
                            var result = eval('(' + xmlHttpObj.responseText + ')');
                            result = result.d;
                            if (result != null) {
                                var productTitle = document.getElementById(instance.ContainerId + "_productTitle" + instance.Index);
                                var productImage = document.getElementById(instance.ContainerId + "_productImage" + instance.Index);

                                productTitle.innerHTML = result.DisplayName;

                                if (scope.IsProductsOurs(productId, scope)) {
                                    productTitle.innerHTML += '<span class="' + scope.OurProductHeaderTextCssClass + '">' + scope.OurProductHeaderText + '</span>';
                                }
                                else if (scope.IsProductsCompetitors(productId, scope)) {
                                    productTitle.innerHTML += '<span class="' + scope.CompetitorProductHeaderTextCssClass + '">' + scope.CompetitorProductHeaderText + '</span>';
                                }                                
                                
                                if (result.RatingUrl != "" && result.RatingUrl != null) {
                                    productImage.src = result.RatingUrl;
                                    productImage.style.visibility = 'visible';
                                }
                                else {
                                    productImage.style.visibility = 'hidden';
                                }
                                productTitle.style.visibility = 'visible';

                            }
                            else {
                                alert("You do not have permission to use this service method.");
                            }
                        }
                        else {
                            var fault = xmlHttpObj.responseText;
                            alert("Error Occured! \n\n" + fault);
                        }
                    }
                    
                }
                var body = '{"sessionToken":"' + instance.GuidValue + '","displayConfigurationId":' + instance.DisplayConfigurationId + ',"productId":' + productId + ',"columnNumber":' + instance.Index + '}';
                xmlHttpObj.setRequestHeader("Content-type", "application/json");
                xmlHttpObj.send(body);
            }
        }
    }
    DropDown.prototype.onChangeEventFlush = function(questionId, scope) {

        var ColumnData = document.getElementById(scope.ContainerId + "_CellData" + questionId + "-" + scope.Index);
        var ColumnImage = document.getElementById(scope.ContainerId + "_CellImg" + questionId + "-" + scope.Index);
        var productTitle = document.getElementById(scope.ContainerId + "_productTitle" + scope.Index);
        var productImage = document.getElementById(scope.ContainerId + "_productImage" + scope.Index);
        //There are elements of this function that are commented out due to the monitisedLink not being returned for the licence
        //if required investigation is needed
        //var alink = document.getElementById(scope.ContainerId + "_link" + scope.Index);
        //var imgLink = document.getElementById(scope.ContainerId + "_imgLink" + scope.Index);

        //imgLink.style.visibility = 'hidden';
        productTitle.style.visibility = 'hidden';
        productImage.style.visibility = 'hidden';
        //alink.style.visibility = 'hidden';

        if (ColumnData == null) {
        }
        else {
            ColumnData.setAttribute("productId", "");
            ColumnImage.setAttribute("productId", "");
            ColumnData.innerHTML = '';
            ColumnImage.style.visibility = 'hidden';
        }
    }

    DropDown.prototype.LoadAnswerByQuestionId = function(productId, questionId, scope) {
        var instance = scope;
        var xmlHttpObj = CreateXmlHttpRequestObject();

        if (xmlHttpObj) {
            var url = instance.EndPoint + "LoadAnswerByQuestionIdAsJson";
            xmlHttpObj.open("POST", url, false);

            var body = '{"LoginGuid":"' + instance.GuidValue + '","DisplayConfigurationId":' + instance.DisplayConfigurationId + ',"ProductId":' + productId + ',"QuestionId":' + questionId + '}';
            xmlHttpObj.setRequestHeader("Content-type", "application/json");
            xmlHttpObj.send(body);

            var result = eval('(' + xmlHttpObj.responseText + ')');
            result = result.d;
            if (result) {
                var ColumnData = document.getElementById(instance.ContainerId + "_CellData" + questionId + "-" + instance.Index);
                var ColumnImage = document.getElementById(instance.ContainerId + "_CellImg" + questionId + "-" + instance.Index);

                ColumnData.setAttribute("productId", productId);
                ColumnImage.setAttribute("productId", productId);

                ColumnData.innerHTML = result.DisplayText;
                ColumnImage.src = result.DisplayImageUrl;
                ColumnImage.alt = result.BrochureText;
                ColumnImage.style.visibility = 'visible';
            }
        }
    }

    //Instructs the object to pre-populate a column
    DropDown.prototype.AutoLoad = function() {
        var scope = this;
        var objControl = scope.objControl;

        var productId;
        if (objControl.value != "")
            productId = objControl.value;
        else
            productId = objControl[0].value;

        if (productId < 1) {
            for (var i = 0; i < scope.Questions.length; i++) {
                scope.onChangeEventFlush(scope.Questions[i], scope);
            }
            return;
        }
        else {
            for (var i = 0; i < scope.Questions.length; i++) {
                scope.onChangeEventFlush(scope.Questions[i], scope);
            }

            scope.LoadProductHeader(productId, scope);
            scope.LoadAnswers(scope, productId);

            var headerCell = document.getElementById(scope.ContainerId + "_productColumn" + scope.Index);
            headerCell.className = 'productColumn';
        }
    }

    DropDown.prototype.IsProductsOurs = function(productID, scope) {

        if (scope.EnableOurProductFunctionality == 'false') {
            return false;
        }

        return scope.IsValueInArray(scope.OurProductsArray, productID);
    }

    DropDown.prototype.IsProductsCompetitors = function(productID, scope) {

        if (scope.EnableOurProductFunctionality == 'false') {
            return false;
        }

        return scope.IsValueInArray(scope.CompetitorProductsArray, productID);
    }

    DropDown.prototype.IsValueInArray = function(array, valueToSearchFor) {
    
        for (var i = 0; i < array.length; i++) {
            if (array[i] == valueToSearchFor) {
                return true;
            }
        }

        return false;
    }

    function PopuateFooter(scopeContainerId,productTitle,questionId,questionTitle,ColumnNumber,brochureText,Show) {

     
        var FooterContainer = "#" + scopeContainerId + "_dd" + ColumnNumber + "_" + questionId + "FooterContainer";
        var FooterTitle = "#" + scopeContainerId + "_dd" + ColumnNumber + "_" + questionId + "FooterTitle";
        var FooterContent = "#" + scopeContainerId + "_dd" + ColumnNumber + "_" + questionId + "FooterContent"
        
        var Stars = "";
        
        var checkstars = questionTitle.split('*');
        var CleanedQuestionTitles = questionTitle.replace("*", " ");
        
        if (checkstars.length > 0) {

            for (var j = 0; j < checkstars.length - 1 ; j++) 
            {
                Stars = Stars + "*";
                CleanedQuestionTitles = CleanedQuestionTitles.replace("*", " ");
            }
            
        }
        else {

            
        }
        var title = Stars + productTitle + " " + CleanedQuestionTitles;
        $(FooterTitle).text(title);
        $(FooterContent).html(brochureText);
        if (Show == true) {

            $(FooterContainer).show();
        }
        else {
            $(FooterContainer).hide();
        }
   
    }
    
}

