function loadSettingsList() {
    dwrSetService.getUsersSettings(function (res) {
        showSettingsList(res);
    });
}

var inProgressPicture = '<img src="static/img/progress.gif" alt="'+tr.progress+'"/>';
//        var prevId;

function errHandler(msg, n) {
    if (n && n.javaClassName && n.javaClassName == 'java.lang.SecurityException') {
        //                alert("you are not logged in ="+msg);
        //                prevId = getActiveModalWindow();
        showModal('loginWindow');
    } else {
       // alert(Object.toJSON(n)); //todo
    }
}

function getWordsArray(){
   var string = jQ("#words").val();
    jQ("#words").val("");
    string = string.toLowerCase();
    string = string.replace(/[^a-zA-Z0-9]/g, ' ');
    return string.split(' ');
}

function addWordsToBox() {
    var arr=getWordsArray();
    var words = getWords();
    //    alert(Object.toJSON(words));
    for (var i = 0; i < arr.length; i++) {
        var ss = trim(arr[i]);
        if (ss && ss.length > 0) {
            var b = true;
            for (var j = 0; j < words.length; j++) {
                if (words[j] == ss) {
                    b = false;
                    break;
                }
            }
            if (b) {
                words.push(ss);
            }
        }
    }
    fromArrToBox(words);
}

function deleteWord(w) {
    jQ("#wordsDiv .word").each(function() {
        var e = jQ(this);
        if (e.attr("word") == w) {
            e.remove();
        }
    });
}

function fromArrToBox(words) {
    jQ("#wordsDiv .word").remove();
    var box = jQ("#wordsDiv");
    for (var i = 0; i < words.length; i++) {
        box.append('<div word="' + words[i] + '" class="word"><span class="uw">' + words[i] + '</span><span> <input type="button" class="minusButton" onclick="deleteWord(\'' + words[i] + '\')"/></span></div>');
    }
}

function makeSetting() {
    addWordsToBox();
    var con = new Object();
    con.id = curId;
    con.userId = uId;
    con.title = jQ("#title").val();

    con.userWord = new Object();
    con.userWord.elements = getWords();
    //        alert(Object.toJSON(con));
    con.useDelimeter = jQ("#useDelim").val();

    con.zone = getSelectedZones();
    con.maxUserWords = jQ('#numWords').val();

    con.dictionaire = jQ("#dictionnaire").val();
    con.maxDomainLength = jQ("#maxDomainLength").val();
    //            alert(Object.toJSON(con));
    return con;
}

function getSelectedZones() {
    var zone = new Object();
    var zones = new Array();
    jQ("#zones .zone:checked").each(function() {
        zones.push(jQ(this).attr('id'));
    });
    zone.elements = zones;
    return zone;
}

function checkSetting(con) {
    if (con.zone.elements.length < 1) {
        writeWornMessage('settingMessage', tr.wornZones);
        return false;
    }
    if (con.userWord.elements.length < 1) {
        writeWornMessage('settingMessage', tr.wornWords); 
        return false;
    }
    return true;
}

function getWords() {
    var w = new Array();
    jQ("#wordsDiv .uw").each(function() {
        w.push(jQ(this).text());
    });
    return w;
}

function loadSetting(res) {
    uId = res.userId;
    changeEditor(res.id);
    jQ("#title").val(res.title);
    jQ("#numWords").val(res.maxUserWords);
    //    alert(Object.toJSON(res));
    fromArrToBox(res.userWord.elements);
    jQ("#words").val("").focus();

    jQ("#dictionnaire").val(res.dictionaire);
    jQ("#maxDomainLength").val(res.maxDomainLength);
    jQ('#useDelim').val("" + res.useDelimeter);


    var z = res.zone.elements;
    jQ('.zone').each(function () {
        this.checked = false;
    });

    for (i = 0; i < z.length; i++) {
        jQ('#zones .zone').each(function() {
            if (this.id == z[i]) {
                this.checked = true;
            }
        });
    }
//    if (curId > 0) {
//        writeMessage('settingMessage', 'Set Setting has been loaded');
//    }
}

function showSettingsList(res) {
    jQ("#settingsList table tr:gt(0)").remove();
    var sList = jQ("#settingsList table");
    jQ(".notLogin").hide();
    if (res instanceof Array) {
        for (var i = 0; i < res.length; i++) {
            var setting = res[i];
            var editStr = '<a href="edit.jsp?id=' + setting.id + '">'+tr.edit+'</a>';
            if (setting.importList){
                editStr="";
            }
            //            if (setting.inProgress){ todo
            //                editStr=inProgressPicture;
            //            }
            var s = '<tr id="s_' + setting.id + '"><td class="title"><a href="set.jsp?id=' + setting.id + '">' + setting.title + '</a></td><td>' + editStr + '</td><td><a href="javascript:deleteSetting(' + setting.id + ');">'+tr.del+'</a></td></tr>';
            sList.append(s);
        }
        jQ("#settingsList").show();
    } else {
        jQ("#settingsList").hide();
        jQ(".notLogin").show();
    }
}

//var activ = jQuery("<div class='activeQ'></div>").hover(function() {
//                    jQuery(this).addClass('pretty-hover');
//                }, function() {
//                    jQuery(this).removeClass('pretty-hover');
//                });


var dId = 0;

function deleteSetting(id) {
    dId = id;
    showModal("deleteConfurm");
}

function realyDeleteSetting() {
    dwrSetService.deleteSetting(dId);
    jQ("#settingsList table #s_" + dId).remove();
    dId = 0;
    hideModal();
}

function writeMessage(id, message) {
    jQ('#' + id).empty().addClass('msgCompl').removeClass("msgWarn").append(message).show().fadeOut(25000);
}

function showMessage(id) {
    jQ('#' + id).addClass('msgCompl').removeClass("msgWarn").show().fadeOut(25000);
}

function writeWornMessage(id, message) {
    jQ('#' + id).empty().addClass('msgWarn').removeClass("msgCompl").append(message).show();
}

function hideMessage() {
    jQ('#message').hide();
}

function getDummyValue() {
    var random = Math.random();
    var retval = new Date().getTime() / (random != 0 ? random : 1);

    return Math.round(retval);
}

function log(s) {
    if (console) console.debug(s); else document.write(s);
}

function random() {
    return Math.floor(Math.random() * 1000000);
}

function comparePasswords(pas1, pas2) {
    if (pas1 != pas2) {
        alert(tr.passNotSame);
        return false;
    }

    if (pas1.length < 5) {
        alert(tr.passMoThen);
        return false;
    }
    return true;
}

function checkemail(str) {
    var filterEmail = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9_\.\-])+\.)+([a-zA-Z]{2,4})+$/;
    return filterEmail.test(str);
}

function trim(str) {
    return str.replace(/^\s+|\s+$/g, '');
}

function hideModal() {
    var id = getActiveModalWindow();
    if (id) {
        jQ('#' + id).hide();
        jQ('#modalWindowBg').hide();
    }
}

function getActiveModalWindow() {
    return jQ('#modalWindowBg').attr('modalW');
}

function showModal(id) {
    hideModal();
    var _docHeight = Math.max(document.documentElement.clientHeight, document.documentElement.scrollHeight);
    var _docWidth = (document.width !== undefined) ? document.width : document.body.offsetWidth;
    if (window.innerHeight > _docHeight) {
        _docHeight = window.innerHeight;
    }
    if (jQ('#modalWindowBg').length <= 0) {
        jQ('body').append('<div id="modalWindowBg"></div>');
    }
    jQ('#modalWindowBg').height(_docHeight).width(_docWidth).attr('modalW', id).show();
    var win = jQ("#" + id)[0];
    var vscroll = (document.all ? document.documentElement.scrollTop : window.pageYOffset);
    var clientHeight = (document.all ? document.documentElement.clientHeight : window.innerHeight);
    winH = jQ("#" + id).height();
    winW = jQ("#" + id).width();
    if (winH + 10 > _docHeight) {
        jQ('#modalWindowBg').height(winH + 10);
    }
    var h = (clientHeight - winH) / 2;
    if (h < 0) h = 10;
    win.style.top = (h + vscroll) + "px";
    win.style.left = ((_docWidth - winW) / 2) + "px";
    win.style.display = 'block';
}

function createCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function logOff() {
    dwrService.logOff(function () {
        deleteCookie("has");
        if (doAfterLogout()) return;
        doneLogin();
    });
}

function deleteCookie(name) {
    document.cookie = name + "=; path=/; expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function createUser() {
    jQ('#newUserWindow #loginEmailExist, #newUserWindow #loginEmailEr1, #newUserWindow #loginPassEr1').hide();
    var email = jQ('#newUserWindow #email').val();
    if (!checkemail(email)) {
        jQ('#newUserWindow #loginEmailEr1').show();
        return;
    }
    var pas1 = jQ('#newUserWindow #password1').val();
    var pas2 = jQ('#newUserWindow #password2').val();
    if (!comparePasswords(pas1, pas2)) {
        jQ('#newUserWindow #loginPassEr1').show();
        return;
    }
    var rem = jQ("#newUserWindow #rememberMe1").attr("checked");
    var lang=jQ("#newUserLang").val();
    dwrService.createUser(email, pas1, 'default',rem,lang, function (res) {
        if (res && res.correct) {
            if (res.us) {
                addUsersCookie(res.us, res.has);
            }
            if (doAfterLogin()) return;
            doneLogin(res.login);
            hideModal();
        } else {
            jQ('#newUserWindow #loginEmailExist').show();
        }
    });
}

function doneLogin(login) {
    if (login && login.length > 0) {
        doOnLogin();

        jQ(".notLogin").hide();
        jQ(".userLogin").empty().append(login);
        jQ(".loggedIn").show();
        jQ("#feedEmail").val(login);
    } else {
        doOnLogout();

        jQ(".notLogin").show();
        jQ(".loggedIn").hide();
        jQ(".userLogin").empty();
    }
}

function testPassword() {
    //    hideMessage();
    jQ('#loginWindow #loginEr, #loginWindow #loginEmailEr, #loginWindow #loginPassEr').hide();
    var l = jQ("#loginWindow #login").val();
    var p = jQ("#loginWindow #password").val();

    if (!l || l.length == 0) {
        jQ('#loginWindow #loginEmailEr').show();
        return;
    }

    if (!p || p.length == 0) {
        jQ('#loginWindow #loginPassEr').show();
        return;
    }
    var rem = jQ("#loginWindow #rememberMe").attr("checked");
    dwrService.checkLogin(l, p, rem, function (res) {
        if (res && res.correct) {
            if (res.us) {
                addUsersCookie(res.us, res.has)
            }
            if (doAfterLogin()) return;
            doneLogin(res.login);
            hideModal();
        } else {
            jQ('#loginEr').show();
        }
    });
}

function addUsersCookie(us, has) {
    createCookie("us", us, 365);
    createCookie("has", has, 365);
}

function submitFeedBack() {
    var eMail = jQ("#feedBackWindow #feedEmail").val();
    var message = jQ("#feedBackWindow #ftext").val();
    dwrService.writeFeedBack(eMail, message, function (res) {
        if (res) {
            writeMessage('feedMessage', tr.feedbackSaved);
            jQ("#feedBackWindow #messForm").hide();
        } else {
            writeWornMessage('feedMessage', tr.errorSave);
        }
    });
}

function cleanChangePassForm(){
    jQ("#wrongPass, #notSamePass").hide();
}

function changePassword() {
    cleanChangePassForm();
    if (!comparePasswords(jQ('#Cpassword').val(), jQ('#Cpassword1').val())) {
        return;
    }
    dwrService.changeUserPassword(jQ('#oldPassword').val(), jQ('#Cpassword').val(), function (res) {
        if (res) {
            showMessage('changePassMessage');
            hideModal();
        } else {
            jQ("#wrongPass").show();
        }
    });

}
function hideChangePassword() {
    jQ("#changePass").hide();
    jQ("#changePasButton, changePassButton1").show();
    jQ('#oldPassword, #Cpassword, #Cpassword1').val("");
}

function showChangePassword() {
    jQ("#changePasButton, changePassButton1").hide();
    jQ("#changePass").show();
}

function requestPassword() {
    jQ('#loginEmailEr2').hide();

    var email = jQ('#restoreLogin').val();
    if (!checkemail(email)) {
        jQ('#loginEmailEr2').show();
        return;
    }

    dwrService.requestPassword(email, function (res) {
        if (res) {
            writeMessage('resPassMessage', tr.requestPassInfo);
        } else {
            writeWornMessage('resPassMessage', tr.wrongMail);
        }
    });
}

function gotoList() {
    location.href = "list.jsp";
}

function gotoResult(id) {
    location.href = "set.jsp?id=" + id;
}


function changeEditor(id) {
    curId = id;
    if (curId != 0) {
        jQ("#openResult").show();
    } else {
        jQ("#openResult").hide();
    }

    //        if (curId != id) {
    //            if (curId == 0 || id == 0) {
    //                curId = id;
    //                jQ('#settingsBody').slideUp(800, changeText).slideDown(800);
    //                jQ("#openResult").hide();
    //            } else {
    //                curId = id;
    //                changeText();
    //                jQ("#openResult").show();
    //            }
    //        }
}

//    function changeText() {
//        if (curId != 0) {
//            jQ("#settingsHead h1").text("Editing Set settings");
//            jQ("#saveSettBut").text("Save & Check");
//        } else {
//            jQ("#settingsHead h1").text("New Set settings");
//            jQ("#saveSettBut").text("Create & Check");
//        }
//    }

function openSetting(id) {
    dwrSetService.getSetting(id, function (res) {
        loadSetting(res);
    });
}

function makeSaveSetting(check) {
    var con = makeSetting();
    if (checkSetting(con)) {
        dwrSetService.saveSetting(con, check, function (res) {
            writeMessage('settingMessage', tr.setSaved);
            //        curId = res.id;
            uId = res.userId;
            changeEditor(res.id);
            if (check) {
                gotoResult(curId);
            }
        });
    }
}


function loadDomainList(page) {
    if (!page || page <= 0) {
        page = curPage; //refresh current
    }

    var proper = new Object();
    proper.ordering = jQ("#setOrder").val();
    proper.filter = jQ("#setFilter").val();
    proper.page = page;
    jQ("#setInProgress, #setIsEmpty").hide();
    dwrDomService.getDomains(setId, proper, function(res) {
        //            log(Object.toJSON(res));
        curPage = res.page;
        if (res.inProgress) {
            jQ("#setInProgress").show();
        } else if (res.allQuantity == 0) {
            jQ("#setIsEmpty").show();
        }
        jQ("#setSize").empty().append(res.quantity);
        jQ("#setAllSize").empty().append(res.allQuantity);
        cleanTable();
        var hasInProgress = fillTable(res.domains);
        if (hasInProgress){
            jQ(".refreshButton").show();
        } else {
            jQ(".refreshButton").hide();
        }
        makePageControls(res.pagesCount, res.page);
    });
}

function makePageControls(pages, current) {
    var pc = jQ(".pageControl").empty();
    if (pages == 1) return;
    var wr = false;
    for (i = 1; i <= pages; i++) {
        if (i < 5 || (pages - i < 4 && pages - i >= 0) || Math.abs(i - current) < 6) {
            var classs = "";
            if (i == current) {
                classs = "class='activePage'";
            }
            pc.append("<span><a href='javascript:loadDomainList(" + i + ");' " + classs + ">" + i + "</a></span> ");
            wr = true;
        } else {
            if (wr) {
                pc.append("...");
            }
            wr = false;
        }
    }
}

function cleanTable(){
    jQ("#domainsTable tr:gt(0)").remove();
}

function fillTable(mas) {
    var hasInProgress=false;
    var t = jQ("#domainsTable");
    for (var i = 0; i < mas.length; i++) {
        var a = mas[i];
        t.append(createDomainHTML(a));

        // if (i==16 || i==33){
        //                t.append("<tr><td colspan='6'><iframe class='cpFrame' height='30px' width='500' src='baner.jsp'></iframe></td></tr>");
        //            }
    }
    return hasInProgress;
}

function createDomainHTML(a) {
    var status = "";
    var progr = "";
    if (a.sh && a.sh == 'a') {
        status = '<img src="static/img/avaliable.gif" alt="'+tr.avaliable+'"/> <a href="http://www.omnis.com/tracker/affiliates.php?name=mkuchin;adid=nameschecker" target="_blank">'+tr.buy+'</a>';
    } else if (a.sh && a.sh == "pr") {
        status = inProgressPicture;
        progr = "progress";
        hasInProgress = true;
    } else {
        //todo not avaliable
    }
    var aa = "";
    if (a.favorite) {
        aa = "active";
    }
    var active = '<input type="button" class="' + aa + '" onclick="javascript:changeFavorite(\'' + a.title + '\', this);" alt="Favorite"/>';
            // <td>' + a.lastUpdateString + '</td>

    var s = '<tr ta="' + a.title + '" class="' + progr + '" ><td class="favorite">' + active + '</td><td>' + a.title + '</td><td>' + status + '</td></tr>';
    return s;
}

function changeFavorite(title, inp) {
    var el = jQ(inp);
    var active = el.hasClass("active");
    //           alert(active);
    var a = !active;
    el.toggleClass("active");
    var titles = new Array();
    titles.push(title);
    dwrDomService.setFavoriteDomains(setId, titles, a);
}

function startAnonimus() {
    dwrService.loginAnonimus(function (res) {
        addUsersCookie(res.us, res.has);
        if (doAfterLogin()) return;
        doneLogin(res.login);
        hideModal();
    });
}

function changeSessionLanguage(lang){
    dwrService.changeSessionLanguage(lang, function(){
        location.href="";
    });
}