﻿var QuoteDAO = (function() {
    function fnQuoteDAOConstructor() {
        /****************************************************/
        /*                                                  */
        /*                                                  */
        /*                 Private Variables                */
        /*                                                  */
        /*                                                  */
        /****************************************************/

        var fnAjaxRequest_onSuccess;

        /****************************************************/
        /*                                                  */
        /*                                                  */
        /*                  Event Handlers                  */
        /*                                                  */
        /*                                                  */
        /****************************************************/

        function ajaxRequest_onSuccess(oResponse) {
            var oQuoteResponse = eval("(" + oResponse.responseText + ")");
            fnAjaxRequest_onSuccess({ sReferenceNumber: oQuoteResponse.sReferenceNumber });
        }

        /****************************************************/
        /*                                                  */
        /*                                                  */
        /*            Class Level Private Methods           */
        /*                                                  */
        /*                                                  */
        /****************************************************/

        function addContactInformationXML(oXML, oContactInformationModel) {
            var oNameNode = oXML.createElement("Name");
            oNameNode.setAttribute("First", oContactInformationModel.getFirstName());
            oNameNode.setAttribute("Last", oContactInformationModel.getLastName());
            oXML.documentElement.appendChild(oNameNode);

            var oCompanyNode = oXML.createElement("Company");
            oCompanyNode.setAttribute("Name", oContactInformationModel.getCompany());
            oXML.documentElement.appendChild(oCompanyNode);

            var oEmailNode = oXML.createElement("Email");
            oEmailNode.setAttribute("Address", oContactInformationModel.getEmailAddress());
            oXML.documentElement.appendChild(oEmailNode);

            var oPhoneNode = oXML.createElement("Phone");
            oPhoneNode.setAttribute("Number", oContactInformationModel.getPhoneNumber());
            oXML.documentElement.appendChild(oPhoneNode);

            var oLocationNode = oXML.createElement("Location");
            var sCountry = oContactInformationModel.getCountry();
            var sProvince = "";
            var sState = "";
            var sPostalCode = "";

            switch (sCountry) {
                case "Canada":
                    sProvince = oContactInformationModel.getProvince();
                    break;
                case "United States":
                    sState = oContactInformationModel.getState();
                    sPostalCode = oContactInformationModel.getPostalCode();
                    break;
            }

            oLocationNode.setAttribute("Country", sCountry);
            oLocationNode.setAttribute("Province", sProvince);
            oLocationNode.setAttribute("State", sState);
            oLocationNode.setAttribute("PostalCode", sPostalCode);
            oXML.documentElement.appendChild(oLocationNode);
        }

        function addLicenseItemXML(oXML, oLicenseItemModel, iCurrency) {
            var oItemsNode = oXML.createElement("Items");
            var oNetSuiteItems = oLicenseItemModel.getNetSuiteItems();
            var oPromotions = oLicenseItemModel.getPromotions();

            oLicenseItemModel.getLicenseItemArray().each(function(oLicenseItem, iIndex) {
                var iId = oLicenseItem.getId();
                var iQuantity = oLicenseItem.getQuantity();
                if (iId && iId.toString().length > 0 && iQuantity && iQuantity > 0) {
                    var oNetSuiteItem = oNetSuiteItems.get(iId);
                    var oItemNode = oXML.createElement("Item");
                    oItemNode.setAttribute("NetSuiteId", iId.toString());
                    oItemNode.setAttribute("Description", oNetSuiteItem.getDescription());
                    //oItemNode.setAttribute("Description", oNetSuiteItem.getShortName() + " " + oNetSuiteItem.getLongName());
                    oItemNode.setAttribute("Quantity", iQuantity.toString());
                    oItemNode.setAttribute("SKU", oNetSuiteItem.getSKU().toString());

                    var oNetSuiteItemPrice = oNetSuiteItem.getPrices().get(iCurrency);
                    oItemNode.setAttribute("BasePrice", oNetSuiteItemPrice.getAmount());

                    var oPromotionsNode = oXML.createElement("Promotions");
                    oNetSuiteItemPrice.getPromotions().each(function(oItemPricePromotion, iIndex) {
                        var oPromotion = oPromotions.get(oItemPricePromotion.getId());
                        var oPromotionNode = oXML.createElement("Promotion");
                        oPromotionNode.setAttribute("Name", oPromotion.getName());
                        //oPromotionNode.setAttribute("StartDate", oPromotion.getStartDate());
                        oPromotionNode.setAttribute("StartDate", "1-1-2009");
                        oPromotionNode.setAttribute("EndDate", getSQLServerDateString(oPromotion.getEndDate()));
                        oPromotionNode.setAttribute("IsPercentage", Number(oPromotion.getIsPercentage()).toString());
                        oPromotionNode.setAttribute("Amount", oPromotion.getAmount().toString());
                        oPromotionsNode.appendChild(oPromotionNode);
                    });

                    oItemNode.appendChild(oPromotionsNode);
                    /*oLicenseItemModel.getNetSuiteItems().get(iId).getPrices().get(iCurrency).getPromotions().each(function(oItemPricePromotion, iIndex) {
	                    
                    });*/
                    oItemsNode.appendChild(oItemNode);
                }
            });

            oXML.documentElement.appendChild(oItemsNode);
        }

        function getSQLServerDateString(oDate) {
            var iMonth = oDate.getMonth() + 1;
            var iDay = oDate.getDate();
            var iYear = oDate.getFullYear();
            return iMonth.toString() + "-" + iDay.toString() + "-" + iYear.toString();
        }
            
          function queryString(parameter) { 
          var loc = location.search.substring(1, location.search.length);
          var param_value = false;

          var params = loc.split("&");
          for (i=0; i<params.length;i++) {
              param_name = params[i].substring(0,params[i].indexOf('='));
              if (param_name.toLowerCase() == parameter.toLowerCase()) {
                  param_value = params[i].substring(params[i].indexOf('=')+1)
              }
          }
          if (param_value) {
              return param_value;
          }
          else {
              return ""; //Here determine return if no parameter is found
          }
        }
        
        function perform_Quote_Save(transport,oContactInformationModel, oLicenseItemModel, fnCallback_onSuccess)
		{
		    var response = eval("("+transport.responseText+")");
		    var region = response.region;
		    
		    // Notify all observers that region has changed!!!
		    oLicenseItemModel.setRegion(region);
		    
            var dCurrentDate = new Date();
            var dExpirationDate = new Date(dCurrentDate.toString());
            dExpirationDate.setDate(dExpirationDate.getDate() + 30);
            var sRegion = oLicenseItemModel.getRegion();
            var oXML = XMLUtilities.createXMLDocumentWithRootNode("Quote", { Region: sRegion, SubmissionDate: getSQLServerDateString(dCurrentDate), ExpirationDate: getSQLServerDateString(dExpirationDate) });
            addContactInformationXML(oXML, oContactInformationModel);
            addLicenseItemXML(oXML, oLicenseItemModel, oLicenseItemModel.getRegionByName(sRegion).getCurrency());
            fnAjaxRequest_onSuccess = fnCallback_onSuccess;
                       
            var siteIdParamValue = "";
            if (queryString("siteId") != "")
                siteIdParamValue = queryString("siteId");
            else if (queryString("siteid") != "")
                siteIdParamValue = queryString("siteid");
            var parameters = {};
            if (siteIdParamValue != "")
            {
                parameters = { quote: XMLUtilities.getXMLString(oXML), siteid: siteIdParamValue };
            }
            else
            {
                parameters = { quote: XMLUtilities.getXMLString(oXML) };
            }
            new Ajax.Request("createquote.aspx", { method: "post", parameters: parameters, onSuccess: ajaxRequest_onSuccess });
		}
        /****************************************************/
        /*                                                  */
        /*                                                  */
        /*          Class Level Priveleged Methods          */
        /*                                                  */
        /*                                                  */
        /****************************************************/
        
        this.saveQuote = function(oContactInformationModel, oLicenseItemModel, fnCallback_onSuccess) {
            var sCountry = oContactInformationModel.getCountry();
            
            var url = "/onlinequote/getregionbycountry.aspx?country=" + unescape(sCountry);
            new Ajax.Request(url, { method: "get", onSuccess: function(transport){
                perform_Quote_Save(transport,oContactInformationModel, oLicenseItemModel, fnCallback_onSuccess);
            } });

        }
    }

    return fnQuoteDAOConstructor;
})();