var minicrm = {
    type: 'MiniCRM',
    ApiURL:'http://api.minicrm.hu/',
    LoadingImg: 'http://api.minicrm.hu/loading.gif',
    ConnectErrorMessage: 'Kapcsolódás a szerverhez sikertelen. Próbálja meg később.',
    SignupForm: '',
    SignUpType: '',
    TimeoutId: '',
    UrlParams: new Object(),
    Loaded: false,

    Init: function () {
        try{
            var oldonload = window.onload;
            if (typeof window.onload != 'function') {
                window.onload = this.OnLoad;
            } else {
                window.onload = function(){
                    if(oldonload) { oldonload(); }
                    minicrm.OnLoad();
                }
            }
        }catch(err){}
    },
    
    OnLoad: function() {
        try{
            minicrm.Loaded = true;
            minicrm.CheckApiURL();
            minicrm.SaveReferrer();
            minicrm.ParseQueryString();
            minicrm.FillDefaults();
        }catch(err){}
    },
    
    GetDomain: function (Url) {
        try{
            return String(Url).toLowerCase().match(/:\/\/(www\.)?(.[^/]+)/i)[2];
        }catch(err){}
        return '';
    },
    
    SaveReferrer: function () {
        try{
            if (top.document.referrer && minicrm.GetDomain(top.document.location) != (String(top.document.referrer) ? minicrm.GetDomain(top.document.referrer) : '')){
                minicrm.SetCookie("minicrm_sr", top.document.referrer)
            }

            if(/^#[-_a-zA-Z0-9]{3,17}$/.test(location.hash)) {
                minicrm.SetCookie("minicrm_pp", location.hash.substring(1));
            }
        } catch(err){}
    },

    SetCookie: function(Name, Value) {
        var expire = new Date();
        expire.setTime(new Date().getTime()+31536000000);
        document.cookie = Name + "=" + escape(Value) + "; path=/; expires=" + expire.toGMTString();
    },
    
    GetCookie: function(Name) {
          var NameEQ = Name + "=";
          var Cookies = document.cookie.split(';');
          for(var i=0; i < Cookies.length; i++) {
                var 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;
    },
    
    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) {}
    },

    SetSubmit: function(NewState) {
        return;
        try{
            for (i=0; i<this.SignupForm.length; i++) {
                var el = this.SignupForm.elements[i];
                if (el.type.toLowerCase() == "submit" || el.type.toLowerCase() == "reset") {
                    el.disabled = NewState;
                }
            }
        }catch(err){}
    }, 

    Display: function(Message) {
        try{
            var msgdiv = document.getElementById('MINICRM_Response');
            msgdiv.style.display = 'block';
            msgdiv.innerHTML = Message;
        }catch(err){}
    }, 

    SendRequest: function (url) {
        try{
            this.SetSubmit(true);
            this.Display("<img src='"+this.LoadingImg+"'>");
            this.TimeoutId  = setTimeout(this.OnRequestFailed, 10000);

            var head = document.getElementsByTagName('head').item(0);
            var js = document.createElement('script');
            js.setAttribute('language', 'javascript');
            js.setAttribute('type', 'text/javascript');
            js.setAttribute('src', url);
            head.appendChild(js);
        }catch(err){}
    },

    OnRequestFailed: function (url) {
        try{
            this.Display(this.ConnectErrorMessage);
            this.SetSubmit(false);
        }catch(err){}
    },

    OnRequestSuccess: function (status, msg) {
        try{
            clearTimeout(this.TimeoutId);
            this.Display(msg);
            this.SetSubmit(false);

            if (status=='OK'){
                if (this.SignupForm){
                    var su = this.SignupForm['SuccessUrl'];
                    if (su && su.value!='') location.href = su.value;
                }
            }
        }catch(err){}
    },

    Signup: function(SignupForm) {
        try{
            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;
            var geturl = this.ApiURL+''+this.SignUpType+'/?1=1';
            var 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 = '';
                    geturl +='&'+encodeURIComponent(SignupForm.elements[i].name)+"="+encodeURIComponent(iVal);
                }
            }
            if (this.SignUpType == 'Unsubscribe' && this.UrlParams['EmailId']) geturl = geturl + "&EmailId="+this.UrlParams['EmailId'];
            
            this.SendRequest(geturl);
            
            return false;
        } catch(err){}
    },
    
    ParseQueryString: function() {
        try{
            var nvpairs = window.location.search.substring(1).split("&");
            if (nvpairs == '') return false;
            for (var idx = 0; idx < nvpairs.length; idx++){ 
                var tokens = nvpairs[idx].split("=");
                this.UrlParams[unescape(tokens[0])] = tokens.length == 2 ? unescape(tokens[1]) : undefined;
            }
            return true;
        }catch(err){}
    },
    
    CheckApiURL: function() {
        var ApiDomain = minicrm.GetDomain(minicrm.ApiURL);
        if (ApiDomain != 'api.minicrm.hu') return;
        var JsDomain = '';
        var tt = document.getElementsByTagName('script');
        for (var i = 0;i<tt.length; i++){
            if (tt[i].type.toLowerCase().indexOf('javascript')>=0 && tt[i].src.toLowerCase().indexOf('minicrm.js')>=0 ){
                JsDomain = minicrm.GetDomain(tt[i].src);
            }
        }
        if (JsDomain == 'api.crmdevel.flb.ro' || JsDomain == 'api.crmdevel2.flb.ro' || JsDomain == 'api.local.minicrm.hu' || JsDomain == 'bapi.minicrm.hu'){
            minicrm.ApiURL = 'http://'+JsDomain+'/';
        }
    },
    
    FillDefaults: function() {
        try{
            var i;

            var Forms = new Array();
            var Form;
            var nr = 0;
            if (this.UrlParams['FormName']){
                var FormName = this.UrlParams['FormName'];
                if (document.forms[FormName]) Forms[nr++] = document.forms[FormName];
            }
        
            if (Forms.length == 0){
                for (i in document.forms) if (document.forms[i].SignUpType && document.forms[i].SystemId){
                    if (document.forms[i].AutoSubmit) var AutoSubmitForm = document.forms[i];
                    Forms[nr++] = document.forms[i];
                }
            }

            if (Forms.length == 0) return false;

            for (Form in Forms){
                for (var 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.Signup(AutoSubmitForm);
        }catch(err){}
    }
}

try{
    minicrm.Init();
}catch(err){}
