/*global window: false, escape: false, unescape: false, alert: false*/

if (typeof minicrm !== 'object'){
    var minicrm = {
        Version: '2.4.2',
        type: 'MiniCRM',
        ApiURL: 'http://api.minicrm.hu/',
        BackupApiURL: false,
        LoadingImg: 'http://api.minicrm.hu/loading.gif',
        ConnectErrorMessage: 'Connection to server failed. Please try again later.',
        SignupForm: '',
        SignUpType: '',
        TimeoutId: '',
        UrlParams: {},
        Loaded: false,
    
        BackupStatus: false,
        BackupMessage: false,
        Init: function () {
            if (document.location.protocol == "https:") {
                this.ApiURL = 'https://www.minicrm.hu/api/';
                this.BackupApiURL = false;
                this.LoadingImg = 'https://www.minicrm.hu/api/loading.gif';
            }
            try {
                var oldonload = window.onload;
                if (typeof window.onload !== 'function') {
                    window.onload = this.OnLoad;
                } else {
                    window.onload = function () {
                        try {
                            if (oldonload) {
                                try {
                                    oldonload();
                                } catch (e) {}
                            }
                            minicrm.OnLoad();
                        } catch (err) {
                            minicrm.LogError(err);
                        }
                    };
                }
            } catch (err) {
              minicrm.LogError(err);
            }
        },
        
        OnLoad: function () {
            try {
                minicrm.Loaded = true;
                minicrm.SaveReferrer();
                minicrm.ParseQueryString();
                minicrm.FillDefaults();
            } catch (err) {
                minicrm.LogError(err);
            }
        },
        
        GetDomain: function (Url) {
            try {
                matches = String(Url).toLowerCase().match(/:\/\/(www\.)?(.[^\/]+)/i);
                if (matches) {
                    return matches[2];
                }
            } catch (err) {
                minicrm.LogError(err, "Error on GetDomain with url: "+Url);
            }
            return '';
        },
        
        SaveReferrer: function () {
            try {
                if (document.referrer && minicrm.GetDomain(document.location) !== (String(document.referrer) ? minicrm.GetDomain(document.referrer) : '')) {
                    minicrm.SetCookie("minicrm_sr", document.referrer);
                }
                if (/^#[a-zA-Z0-9]{3,17}$/.test(location.hash)) {
                    minicrm.SetCookie("minicrm_pp", location.hash.substring(1));
                }
            } catch (err) {
                minicrm.LogError(err);
            }
        },
    
        SetCookie: function (Name, Value) {
            try {
                var expire = new Date();
                expire.setTime(new Date().getTime() + 31536000000);
                document.cookie = Name + "=" + escape(Value) + "; path=/; expires=" + expire.toGMTString();
            } catch (err) {
                minicrm.LogError(err);
            }
        },
        
        GetCookie: function (Name) {
            try {
                var NameEQ = Name + "=",
                    Cookies = document.cookie.split(';'),
                    Cookie,
                    i;
                
                for (i = 0; i < Cookies.length; i++) {
                    Cookie = Cookies[i];
                    while (Cookie.charAt(0) === ' ') {
                        Cookie = Cookie.substring(1, Cookie.length);
                    }
                    if (Cookie.indexOf(NameEQ) === 0) {
                        return unescape(Cookie.substring(NameEQ.length, Cookie.length));
                    }
                }
                return null;
            } catch (err) {
                minicrm.LogError(err);
            }
        },
        
        SetField: function (Name, Value) {
            try {
                if (!this.SignupForm.elements[Name]) {
                    var input = document.createElement("input");
                    input.setAttribute("type", "hidden");
                    input.setAttribute("name", Name);
                    input.setAttribute("value", Value);
                    this.SignupForm.appendChild(input);
                } else {
                    this.SignupForm.elements[Name].value = Value;
                }
            } catch (err) {
                minicrm.LogError(err);
            }
        },
    
        SetSubmit: function (NewState) {
            try {
                var i, 
                    el;
                
                for (i = 0; i < this.SignupForm.length; i++) {
                    el = this.SignupForm.elements[i];
                    if (el.type.toLowerCase() === "submit" || el.type.toLowerCase() === "reset") {
                        el.disabled = NewState;
                    }
                }
            } catch (err) {
                minicrm.LogError(err);
            }
        }, 
    
        Display: function (Message) {
            try {
                var msgdiv = document.getElementById('MINICRM_Response');
                msgdiv.style.display = 'block';
                msgdiv.innerHTML = Message;
            } catch (err) {
                minicrm.LogError(err);
            }
        }, 
    
        SendRequest: function (url) {
            try {
                var head = document.getElementsByTagName('head').item(0),
                    js = document.createElement('script');
                
                url += "&Version=" + encodeURIComponent(minicrm.Version);
                js.setAttribute('language', 'javascript');
                js.setAttribute('type', 'text/javascript');
                js.setAttribute('src', url);
                head.appendChild(js);
            } catch (err) {
                minicrm.LogError(err);
            }
        },
        
        SendSignupRequest: function (url) {
            try {
                this.TimeoutId  = setTimeout(minicrm.OnRequestFailed, 10000);
                this.SetSubmit(true);
                this.Display("<img src='" + this.LoadingImg + "'>");
                this.SendRequest(url);
            } catch (err) {
                minicrm.LogError(err);
            }
        },
    
        OnRequestFailed: function (url) {
            try {
                if (minicrm.BackupStatus) {
                    minicrm.OnRequestSuccess(minicrm.BackupStatus, 'Backup: ' + minicrm.BackupMessage);
                } else {
                    minicrm.Display(minicrm.ConnectErrorMessage);
                    minicrm.SetSubmit(false);
                }
            } catch (err) {
                minicrm.LogError(err);
            }
        },
        
        OnRequestSuccessBackup: function (status, msg) {
            try {
                minicrm.BackupStatus = status;
                minicrm.BackupMessage = msg;
            } catch (err) {
                minicrm.LogError(err);
            }
        },
        
        OnRequestSuccess: function (status, msg) {
            try {
                clearTimeout(this.TimeoutId);
                minicrm.BackupStatus = false;
                minicrm.BackupMessage = false;
                
                this.Display(msg);
                this.SetSubmit(false);
                
                if (status === 'REDIRECT') {
                    try {
                        top.location.href = msg;
                    }catch(err){
                        location.href = msg;
                    }
                    
                }
                
                if (status === 'OK') {
                    if (this.SignupForm) {
                        var su = this.SignupForm.SuccessUrl;
                        if (su && su.value !== '') {
                            location.href = su.value;
                        }
                    }
                }
            } catch (err) {
                minicrm.LogError(err);
            }
        },
    
        Signup: function (SignupForm) {
            try {
                var geturl,
                    iVal,
                    i,
                    tp;
                if (!minicrm.IsFormObject(SignupForm)) {
                    return;
                }

                
                this.StopRequests();
                
                if (!this.Loaded) {
                    this.OnLoad();
                }
                
                this.SignupForm = SignupForm;
                
                if (this.UrlParams.i) {
                    this.SetField('i', this.UrlParams.i);
                }
                minicrm.SetField("Referrer", minicrm.GetCookie('minicrm_sr'));
                minicrm.SetField("Affiliate", minicrm.GetCookie('minicrm_pp'));
    
                this.SignUpType = '';
                if (SignupForm.SignUpType && SignupForm.SignUpType.value) {
                    this.SignUpType = SignupForm.SignUpType.value;
                }
                
                this.MiniCRM_FormHash = false;
                if (SignupForm.MiniCRM_FormHash && SignupForm.MiniCRM_FormHash.value) {
                    this.MiniCRM_FormHash = SignupForm.MiniCRM_FormHash.value;
                }
                minicrm.CheckResponseDiv(SignupForm);
                if (this.MiniCRM_FormHash) {
                    this.SignUpType = 'Signup';
                }
                    
                geturl = this.SignUpType + '/?1=1';
                iVal = '';
                for (i = 0; i < SignupForm.elements.length; i++) {
                    if (SignupForm.elements[i].disabled) {
                        continue;
                    }
                    tp = SignupForm.elements[i].type;
                    if (tp === 'hidden' || tp === 'text' || tp === 'textarea' || tp === 'select-one' || tp === 'checkbox' || tp === 'radio') {
                        iVal = SignupForm.elements[i].value;
                        if ((tp === 'checkbox' || tp === 'radio') && !SignupForm.elements[i].checked) {
                            iVal = '0';
                        }
                        geturl += '&' + encodeURIComponent(SignupForm.elements[i].name) + "=" + encodeURIComponent(iVal);
                    }
                }
                if ((this.SignUpType === 'Unsubscribe' && this.UrlParams.EmailId) || (this.MiniCRM_FormHash && this.UrlParams.EmailId)) {
                    geturl = geturl + "&EmailId=" + this.UrlParams.EmailId;
                }
                
//				jQuery("body").append(this.ApiURL + '' + geturl);
//				return false;
                this.SendSignupRequest(this.ApiURL + '' + geturl);
                if (this.BackupApiURL) {
                    this.SendRequest(this.BackupApiURL + '' + geturl);
                }
                
                return false;
            } catch (err) {
                minicrm.LogError(err);return false;
            }
        },
        
        ParseQueryString: function () {
            try {
                var tokens,
                    idx,
                    nvpairs = window.location.search.substring(1).split("&");
                
                if (nvpairs.toString() === '') {
                    return false;
                }
                for (idx = 0; idx < nvpairs.length; idx++) { 
                    tokens = nvpairs[idx].split("=");
                    this.UrlParams[unescape(tokens[0])] = tokens.length === 2 ? unescape(tokens[1]) : undefined;
                }
                return true;
            } catch (err) {
                minicrm.LogError(err);
            }
        },
        
        CheckResponseDiv: function (Form) {
            try {
                if (!minicrm.IsFormObject(Form)) {
                    return;
                }
                var msgdiv = document.getElementById('MINICRM_Response');
                
                if (!msgdiv) {
                    msgdiv = document.createElement("span");
                    msgdiv.setAttribute("id", "MINICRM_Response");
                    msgdiv.style.display = 'none';
                    msgdiv.style.borderColor = '#ccc';
                    msgdiv.style.borderStyle = 'solid';
                    msgdiv.style.borderWidth = '1px';
                    msgdiv.style.textAlign = 'center';
                    msgdiv.style.padding = '10px';
                    msgdiv.style.margin = '10px';
                    Form.insertBefore(msgdiv, Form.firstChild);
                }
            } catch (err) {
                minicrm.LogError(err);
            }
        },
        
        SetFormOnSubmit: function (Form) {
            try {
                var oldOnSubmit = typeof Form.onsubmit === 'function' ? Form.onsubmit : false;
                Form.onsubmit = function () {
                    try {
                        if (oldOnSubmit) {
                            if (oldOnSubmit() === false) {
                               return false;
                            }
                        }
                        minicrm.CheckResponseDiv(this);
                        minicrm.Signup(this);
                        return false;
                    } catch (err) {
                        minicrm.LogError(err);
                    }
                };
            } catch (err) {
                minicrm.LogError(err);
            }

        },
        
        FillDefaults: function () {
            try {
                var i,
                    Forms = [],
                    Form,
                    FormName,
                    nr = 0,
                    AutoSubmitForm,
                    paramKey,
                    tp;
                
                if (this.UrlParams.FormName) {
                    FormName = this.UrlParams.FormName;
                    if (document.forms[FormName]) {
                        Forms[nr++] = document.forms[FormName];
                    }
                }
            
                if (!Forms.length) {
                    for (i in document.forms) {
                        if ((document.forms[i].SignUpType && document.forms[i].SystemId) || document.forms[i].MiniCRM_FormHash) {
                            if (document.forms[i].AutoSubmit) {
                                AutoSubmitForm = document.forms[i];
                            }
                            Forms[nr++] = document.forms[i];
                        }
                    }
                }
    
                if (!Forms.length) {
                    return false;
                }
    
                for (Form in Forms) {
                    if (Forms[Form].MiniCRM_FormHash) {
                        this.SetFormOnSubmit(Forms[Form]);
                    }
                    
                    for (paramKey in this.UrlParams) {
                        for (i = 0; i < Forms[Form].length; i++) {
                            if (Forms[Form][i] === undefined) {
                                continue;
                            }
                            
                            tp = Forms[Form][i].type;
                            if (Forms[Form][i].name === paramKey) {
                                if (tp === 'checkbox' || tp === 'radio') {
                                    Forms[Form][i].checked = this.UrlParams[paramKey] ? true : false;
                                } else {
                                    Forms[Form][i].value = this.UrlParams[paramKey];
                                }
                            }
                        }
                    }
                }
                if (AutoSubmitForm) {
                    minicrm.CheckResponseDiv(AutoSubmitForm);
                    minicrm.Signup(AutoSubmitForm);
                }
            } catch (err) {
                minicrm.LogError(err);
            }
        },
        
        LogError: function (e, CustomMsg) {
            var msg,
                errorUrl;
            
            msg = 'Line: ' + e.lineNumber + ', Name: ' + e.name + ', Error: ' + e.message+ ', Page: '+window.location;
            if (CustomMsg) {
                msg += ', Message: ' + CustomMsg;
            }
            msg += ', Browser: ' + navigator.userAgent;
            if (document.location.protocol == "https:") {
                this.ApiURL = 'https://www.minicrm.hu/api/';
            }
            errorUrl = this.ApiURL + 'LogError/?s=1&type=signup&message=' + encodeURIComponent(msg);
            this.SendRequest(errorUrl);
        },
        
        IsFormObject : function (Form) {
            try {
                if (typeof Form.constructor == 'object') {
                    ret = (Form.constructor.toString().indexOf("HTMLFormElement")) > -1 ? true : false;
                } else {
                    ret = (Form.nodeName == 'FORM') ? true : false;
                }
            } catch (err) {
                ret = (Form.nodeName == 'FORM') ? true : false;
            }
            return ret;
        },

        StopRequests : function() {
            if (window.stop !== undefined) {
                window.stop() ;
            } else if (document.execCommand !== undefined) {
                document.execCommand("Stop", false) ;
            }
        }
    };
    
    try {
        

minicrm.ApiURL = 'http://api.minicrm.hu/';
minicrm.BackupApiURL = false;
minicrm.LoadingImg = 'http://api.minicrm.hu/loading.gif';
minicrm.Init();

    } catch (err) {
        minicrm.LogError(err);
    }
}

