// Class BkinOptInManager ------------------------------------------------------
function BkinOptInManager(userId)
{
    // Attributes for the Bkin Page
    this.bkinFrameName              = "BkinFrame";
    this.bkinFormName               = "OptInFormForSendingDataToBkin";
    this.urlForSuccessfulNotifications = null;
    this.urlForErrorNotifications = null;
    this.stateScriptUrl = null;
    this.campaignTargetInfo = null;
    this.campaignTargetInfoScriptLoaded = false;
    
    this.SetUrlsForNotifications = function(urlForSuccessfulNotifications, urlForErrorNotifications)
    {
        this.urlForSuccessfulNotifications = urlForSuccessfulNotifications;
        this.urlForErrorNotifications = urlForErrorNotifications;
    }
    
    this.userId = userId;           // The user who logs on the Space, can be the responsible of the item
    this.responsibleId = null;
    this.optinPathPage = null;
    
    this._bkinIframe = null;
        
    // Property for Callback
    this.setCallbackMethod = function(callbackMethod)
    {
    }
    
    // Public Methods
    this.registerFrame = function()
    {
    }
    
    this.setProperty = function(propertyName, propertyValue, isMultivalue)
    {
        isMultivalue = isMultivalue == null ? false : isMultivalue;
        
        this._bkinIframe = this.GetIframeObject();
        
        if(this._bkinIframe == null)
        {
            return;
        }
        
        var control = this.GetControlObject(propertyName, isMultivalue);
        
        if(control != null)
        {
            this.SetValue(control, propertyValue, isMultivalue);
        }
    }
    
    this.SetValue = function(control, propertyValue, isMultivalue)
    {
        propertyValue = propertyValue == null ? '' : propertyValue;
        isMultivalue = isMultivalue == null ? false : isMultivalue;
        
        if(isMultivalue)
        {
            var selectedOption = null;
            
            if(propertyValue == null
                || propertyValue == '')
            {
                propertyValue = '--';
            }
            
            for(var i = 0;i < control.options.length;++i)
            {
                var option = control.options[i];
                
                if(option.text == propertyValue)
                {
                    selectedOption = option;
                    break;
                }
            }
            
            if(selectedOption == null)
            {
                selectedOption = new Option(propertyValue, propertyValue, false, true);
                control.options[control.options.length] = selectedOption;
            }
            else
            {
                selectedOption.selected = "selected";
            }
        }
        else
        {
            control.value = propertyValue;
        }
    }
    
    this.GetControlObject = function(controlName, isMultivalue)
    {
        isMultivalue = isMultivalue == null ? false : isMultivalue;
        
        var control = this._bkinIframe.contentWindow.document.getElementById(controlName);
        var bkinForm = this.GetFormObject();
        
        if(control != null)
        {
            if(isMultivalue)
            {
                if(control.tagName.toLowerCase() == 'select')
                {
                    return control;
                }
                else
                {
                    bkinForm.removeChild(control);
                    
                    control = this._bkinIframe.contentWindow.document.createElement('select');
                    control.id = this.GetControlIdForControlPropertyName(controlName);
                    control.name = control.id;
                    
                    bkinForm.appendChild(control);
                    
                    return control;
                }
            }
            else
            {
                if(control.tagName.toLowerCase() == 'input')
                {
                    return control;
                }
                else
                {
                    bkinForm.removeChild(control);
                    
                    control = this._bkinIframe.contentWindow.document.createElement('input');
                    control.id = this.GetControlIdForControlPropertyName(controlName);
                    control.name = control.id;
                    control.type = 'text';
                    
                    bkinForm.appendChild(control);
                    
                    return control;
                }
            }
        }
        else
        {
            if(isMultivalue)
            {                    
                control = this._bkinIframe.contentWindow.document.createElement('select');
                control.id = this.GetControlIdForControlPropertyName(controlName);
                control.name = control.id;
                
                bkinForm.appendChild(control);
                
                return control;
            }
            else
            {
                control = this._bkinIframe.contentWindow.document.createElement('input');
                control.id = this.GetControlIdForControlPropertyName(controlName);
                control.name = control.id;
                control.type = 'text';
                
                bkinForm.appendChild(control);
                
                return control;
            }
        }
    }
    
    this.submit = function()
    {
        this._bkinIframe = this.GetIframeObject();
        
        if(this._bkinIframe == null)
        {
            return;
        }
        
        var bkinForm = this.GetFormObject();
        
        if(bkinForm != null)
        {
            this.SetHiddenVariables();
            this.SetOptInFormInState('submitted');
            bkinForm.submit();
        }
    }
    
    this.SetOptInFormInState = function(newState)
    {
        this._bkinIframe.contentWindow.document.getElementById('HiddenFormState').value = newState;
    }
    
    this.IsOptInFormInSubmittedState = function()
    {
        return this._bkinIframe.contentWindow.document.getElementById('HiddenFormState').value == 'submitted';
    }
    
    this.GetFormObject = function()
    {
        return this._bkinIframe.contentWindow.document.getElementById(this.bkinFormName);
    }
    
    this.GetIframeObject = function()
    {
        var iframeObject = document.getElementById(this.bkinFrameName);
        
        if(iframeObject != null)
        {
            var isTheSameDomain = null;
            
            try
            {
                isTheSameDomain = document.domain == iframeObject.contentWindow.document.domain;
            }
            catch(e)
            {
                isTheSameDomain = false;
            }
            
            if(isTheSameDomain)
            {
                var optInFormObject = this.GetFormObject();
                
                if(optInFormObject != null
                        && !this.IsOptInFormInSubmittedState())
                {
                        return iframeObject;
                }
                else
                {
                    iframeObject.parentNode.removeChild(iframeObject);
                
                    return this.CreateIframeObject();
                }
            }
            else
            {
                iframeObject.parentNode.removeChild(iframeObject);
                
                return this.CreateIframeObject();
            }
        }
        else
        {
            return this.CreateIframeObject();
        }
    }
    
    this.CreateIframeObject = function()
    {
        var iframeObject = document.createElement('iframe');
        iframeObject.id = this.bkinFrameName;
        iframeObject.style.width = '0';
        iframeObject.style.height = '0';
        
        document.body.appendChild(iframeObject);
                                    
        iframeObject.contentWindow.document.writeln ("<body><form id='" + this.bkinFormName + "' method='post' action='" + this.BuildUrl() +
            "'><input type='hidden' name='__VIEWSTATE' id='__VIEWSTATE' value='' style='display:none' /><input type='hidden' id='HiddenFormState' value='notSubmitted' style='display:none' /></form></body>");
        
        return iframeObject;
    }
    
    this.GetUrlParam = function(paramName)
    {
        if(window.location.search.indexOf('?') < 0)
        {
            return null;
        }
        
        var queryString = window.location.search.substr(1);
        var params = queryString.split('&');
        
        if(params == null
                || params.length == 0)
        {
            return null;
        }
        
        paramName = paramName.toLowerCase();
        
        for(var i = 0;i < params.length;++i)
        {
            var param = params[i].split('=');
            
            if(param != null
                    && param.length > 1)
            {                
                if(param[0].toLowerCase() == paramName)
                {
                    return param[1];
                }
            }
        }
        
        return null;
    }
}
// End class BkinOptInManager --------------------------------------------------


// Class BkinLeadOptInManager --------------------------------------------------
function BkinLeadOptInManager(userId, targetGroupId, campaignId, responsibleId, optinPathPage, stateScriptUrl)
{
    // Attributes
    this.userId = userId;
    this.responsibleId = responsibleId;
    this.optinPathPage = optinPathPage;
    
    this.targetGroupId = targetGroupId;
    this.campaignId = campaignId;
    this.stateScriptUrl = stateScriptUrl;
    
    this.LoadOptInStateScript = function()
    {
        var scriptOptInState = document.getElementById('ScriptOptInState');
        
        if(scriptOptInState == null)
        {
            return;
        }
        
        var urlBKCTID = this.GetUrlParam('BKCTID');
        var urlCId = this.GetUrlParam('CID');
        
        if(urlBKCTID == null
             || urlCId == null)
        {
            return;
        }
        
        var url = this.stateScriptUrl;
        
        if(url.indexOf('?') >= 0)
        {
            url = url + '&';
        }
        else
        {
            url = url + '?';
        }
        
        url = url + 'BKCTID=' + urlBKCTID + '&CID=' + urlCId;
        
        scriptOptInState.src = url;
    }
    
    this.fillProperty = function(propertyName,
        controlId,
        isMultivalue)
    {           
        var theControl = document.getElementById(controlId);
        var scriptOptInState = document.getElementById('ScriptOptInState');
        
        if(theControl == null
            || scriptOptInState == null)
        {
            return;
        }
        
        if(!this.campaignTargetInfoScriptLoaded)
        {
            window.setTimeout("_BkinSpaceOptInManager.fillProperty('" + propertyName + "', '" + controlId + "'," + isMultivalue + ")", 50);
            return;
        }
        
        if(this.campaignTargetInfo == null)
        {
            return;
        }
        
        for(var i = 0;i < this.campaignTargetInfo.length;++i)
        {
            if(this.campaignTargetInfo[i][0] == propertyName)
            {
                this.SetValue(theControl, this.campaignTargetInfo[i][1], isMultivalue);
            }
        }
    }
    
    //this.LoadOptInStateScript();
    
    this.GetControlIdForControlPropertyName = function(propertyName)
    {
        switch(propertyName)
        {
            case "Owner":
                return "DropdownlistOwner";
                
            case "Name":
                return "TextBoxName";
            
            case "LastName":
                return "TextBoxLastName";
            
            case "Company":
                return "TextBoxCompany";
                
            case "Title":
                return "TextBoxTitle";
                
            case "Sector":
                return "DropDownListSector";
            
            case "AnnualRevenue":
                return "TextBoxAnnualRevenue";
                
            case "NumberOfEmployees":
                return "TextBoxNumberOfEmployees";
                
            case "Source":
                return "DropDownListSource";
                
            case "Telephone":
                return "TextBoxTelephone";
            
            case "Cellular":
                return "TextBoxMovil";
            
            case "Fax":
                return "TextboxFax";
            
            case "Email":
                return "TextBoxEmail";
                
            case "WebSite":
                return "TextBoxWebSite";
            
            case "LeadState":
                return "DropdownlistLeadState";
            
            case "RatingState":
                return "DropDownListRatingState";
                
            case "Description":
                return "TextboxDescription";
                
            case "Address1":
                return "TextboxStreet1";
            
            case "Address2":
                return "TextboxStreet2";
                
            case "City":
                return "TextboxCity";
            
            case "StateProvince":
                return "TextboxStateProvince";
            
            case "PostalCode":
                return "TextboxPostalCode";
            
            case "Country":
                return "TextboxCountry";
                
            default:
                return propertyName;
        }
    }
    
    // Set the hidden info when submit
    this.SetHiddenVariables = function()
    {
        this.setProperty("UrlForErrorNotifications", this.urlForErrorNotifications, false);
        this.setProperty("UrlForSuccessfulNotifications", this.urlForSuccessfulNotifications, false);
        this.setProperty("Owner", this.responsibleId, false);
        this.setProperty("TargetGroupId", this.targetGroupId, false);
        this.setProperty("CampaignId", this.campaignId, false);
    }
    
    this.BuildUrl = function()
    {
        var urlBKOID = this.GetUrlParam("BKOID");
        var urlBKTGID = this.GetUrlParam("BKTGID");
        var urlBKCID = this.GetUrlParam("BKCID");
        var urlBKCTID = this.GetUrlParam("BKCTID");
        var urlItemId = this.GetUrlParam("ItemId");
        var url = null;
        
        if(this.optinPathPage.indexOf('?') >= 0)
        {
            url = this.optinPathPage + '&';
        }
        else
        {
            url = this.optinPathPage + '?';
        }
        
        var paramMark = '';
        
        if(this.userId != null
                && this.userId != '')
        {
            paramMark = '&';
            url = url + "TG9nT25Ca2luVXNlcklk=" + this.userId;
        }
        
        if(urlBKOID != null)
        {
            url = url + paramMark + "BKOID=" + urlBKOID;
        }
        else
        {
            url = url + paramMark + "BKOID=" + this.responsibleId;
        }
        
        if(urlBKTGID != null)
        {
            url = url + "&BKTGID=" + urlBKTGID;
        }
        else
        {
            url = url + "&BKTGID=" + this.targetGroupId;
        }
        
        if(urlBKCID != null)
        {
            url = url + "&BKCID=" + urlBKCID;
        }
        else
        {
            url = url + "&BKCID=" + this.campaignId;
        }
        
        if(urlBKCTID != null)
        {
            url = url + "&BKCTID=" + urlBKCTID;
        }
        
        if(urlItemId != null)
        {
            url = url + "&ItemId=" + urlItemId;
        }
        
        return url;
    }
}
BkinLeadOptInManager.prototype = new BkinOptInManager;
// End class BkinLeadOptInManager ----------------------------------------------



// Class BkinCaseOptInManager --------------------------------------------------
function BkinCaseOptInManager(userId, productId, accountId, contactId, responsibleId, optinPathPage)
{
    // Attributes
    this.userId = userId;
    this.responsibleId = responsibleId;
    this.optinPathPage = optinPathPage;
    
    this.productId = productId;
    this.accountId = accountId;
    this.contactId = contactId;
        
    this.GetControlIdForControlPropertyName = function(propertyName)
    {
        switch(propertyName)
        {
            case "Owner":
                return "DropdownlistOwner";
                
            case "Name":
                return  "TextBoxName";
            
            case "Source":
                return "DropDownListSource";
                
            case "CaseType":
                return "DropDownListCaseType";

            case "CaseReason":
                return "DropDownListCaseReason";
            
            case "Priority":
                return "DropDownListPriority";

            case "CaseState":
                return "DropDownListCaseState";
                
            case "PlannedEnd":
                return "TextBoxPlannedEnd";
            
            case "Description":
                return "TextboxDescription";
            
            case "Resolution":
                return "TextboxResolution";
                
            default:
                return propertyName;
        }
    }
        
    this.SetHiddenVariables = function()
    {
        this.setProperty("UrlForErrorNotifications", this.urlForErrorNotifications, false);
        this.setProperty("UrlForSuccessfulNotifications", this.urlForSuccessfulNotifications, false);
        this.setProperty("Owner", this.responsibleId, false);
        this.setProperty("ProductId", this.productId, false);
        this.setProperty("AccountId", this.accountId, false);
        this.setProperty("ContactId", this.contactId, false);
    }
    
    this.BuildUrl = function()
    {
        var urlItemId = this.GetUrlParam("ItemId");
        var url = null;
        
        if(this.optinPathPage.indexOf('?') >= 0)
        {
            url = this.optinPathPage + '&';
        }
        else
        {
            url = this.optinPathPage + '?';
        }
                
        if(this.userId != null
                && this.userId != '')
        {
            url = url + "TG9nT25Ca2luVXNlcklk=" + this.userId;
        }
        
        if(urlItemId != null)
        {
            url = url + "&ItemId=" + urlItemId;
        }
        
        return url;
    }
}
BkinCaseOptInManager.prototype = new BkinOptInManager;
// End class BkinCaseOptInManager ----------------------------------------------

// Validation support methods --------------------------------------------------
        function replace(texto,s1,s2)
        {
	        return texto.split(s1).join(s2);
        }
        
        function validRequiredField (fieldToValidateArrayPosition)
        {   
            if (arrayValidation[requiredPos][fieldToValidateArrayPosition]=='true')
            {
                var valid = (document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]).value != "")
                if (valid)
                {
                  document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]+'ErrorMsg').style.visibility = 'hidden';
                  document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]+'ErrorMsg').innerHTML = '';
                }
                else
                {
                  document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]+'ErrorMsg').style.visibility = 'inherit';
                  document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]+'ErrorMsg').innerHTML = replace ( arrayValidation[requiredErrorMsgPos],
                                                                                                                                       '{fieldName}', 
                                                                                                                                       arrayValidation[labelForFieldIdPos][fieldToValidateArrayPosition]
                                                                                                                                     );//Replace in error message {fieldName with the apropiate label value}  //' &#149; El campo es obligatorio.';
                }
                return valid;
            }
            return true;
        }
        
        function validateWithRegularExpression (fieldToValidateArrayPosition, regularExpression, errorMsg)
        {
            var valid = true;
            if (document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]).value != "")
            {                                     
                valid = regularExpression.test(document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]).value);
            }
            if (valid)
            {
              document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]+'ErrorMsg').style.visibility = 'hidden';
              document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]+'ErrorMsg').innerHTML = '';
            }
            else
            {
              document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]+'ErrorMsg').style.visibility = 'inherit';
              document.getElementById(arrayValidation[fieldsIdPos][fieldToValidateArrayPosition]+'ErrorMsg').innerHTML = replace ( errorMsg,
                                                                                                                                   '{fieldName}', 
                                                                                                                                   arrayValidation[labelForFieldIdPos][fieldToValidateArrayPosition]
                                                                                                                                 );//Replace in error message {fieldName with the apropiate label value}  //' &#149; E-mail no válido.';
            }
            return valid;
        }
        
        function validateFieldsAndSendFormToBkinSpace()
        {
            var valid = true;
            //Fields to validate
            
            for(i=0;i<arrayValidation[fieldsIdPos].length;i++)
            {
                switch( arrayValidation[fieldType][i] )
                {
                    case 'emailType':
                        var regularExpression=/^(([a-zA-Z0-9][A-Za-z0-9#$%*+-\.\/:;=?^_|\&amp;]*[a-zA-Z0-9]@([a-zA-Z0-9][A-Za-z0-9_\-]*[a-zA-Z0-9]\.)+[a-zA-Z][a-zA-Z\.]*[a-zA-Z])+([;.]([a-zA-Z0-9][A-Za-z0-9#$%*+-\.\/:;=?^_|\&amp;]*[a-zA-Z0-9]@([a-zA-Z0-9][A-Za-z0-9_\-]*[a-zA-Z0-9]\.)+[a-zA-Z][a-zA-Z\.]*[a-zA-Z]))*)$/;
                        var errorMsg = arrayValidation[mailErrorMsgPos];
                        valid = validateWithRegularExpression(i, regularExpression, errorMsg) && valid;
                    break;
                    case 'integerType':
                        var regularExpression=/^\d*$/;
                        var errorMsg = arrayValidation[numberErrorMsgPos];
                        valid = validateWithRegularExpression(i, regularExpression, errorMsg) && valid;
                    break;
                    case 'floatType':
                        var regularExpression=/^\d*((\,)\d*)?$/;
                        var errorMsg = arrayValidation[decimalErrorMsgPos];
                        valid = validateWithRegularExpression(i, regularExpression, errorMsg) && valid;
                    break;
                    case 'dateTimeType':
                        var regularExpression;
                        if ((dateFormat != null) && (dateFormat == 'MM/dd/yyyy'))
                        {
                            regularExpression=/^((0?[1-9])|(1[0-2]))(\-|\/|\.)(([0-2]?\d{1})|([3][0,1]{1}))(\-|\/|\.)(1908|1909|([1]{1}[9]{1}[1-9]{1}\d{1})|([2-9]{1}\d{3}))$/;
                        }
                        else //'dd/MM/yyyy'
                        {
                            regularExpression=/^(([0-2]?\d{1})|([3][0,1]{1}))(\-|\/|\.)((0?[1-9])|(1[0-2]))(\-|\/|\.)(1908|1909|([1]{1}[9]{1}[1-9]{1}\d{1})|([2-9]{1}\d{3}))$/;
                        }
                        var errorMsg = arrayValidation[dateErrorMsgPos];
                        valid = validateWithRegularExpression(i, regularExpression, errorMsg) && valid;
                    break;                
                }
                if (valid)
                {
                    valid = validRequiredField(i) && valid;
                }
            }

            if (valid)
            {
              SendFormToBkinSpace();
            }
        }
// End validation support methods ----------------------------------------------