/*********************************************
 * Class TwDate
 * Класс Дата. Предназначен для работы с датами
 */
var TwDate = new Class({
    initialize: function(dd_mm_yyyy) {
        if (dd_mm_yyyy) {
            this.year = dd_mm_yyyy.substring(6, 10);
            this.month = dd_mm_yyyy.substring(3, 5);
            this.day = dd_mm_yyyy.substring(0, 2);
            this.setup = true;
        } else {
            var dt = new Date();
            this.year = dt.getFullYear();
            this.month = lpad(dt.getMonth() + 1 + '', 2, '0');
            this.day = lpad(dt.getDate() + '', 2, '0');
            this.setup = false;
        }
    },

    getYear: function() {
        return this.year;
    },

    getMonth: function() {
        return this.month;
    },

    getDay: function() {
        return this.day;
    },

    isSetup: function() {
        return this.setup;
    },

    getDD_MM_YYYY: function() {
        return this.day + "." + this.month + "." + this.year;
    },

    getDate: function() {
        var dt = new Date();
        dt.setFullYear(this.year);
        dt.setMonth(this.month - 1);
        dt.setDate(this.day);
        return dt;
    }
});

/*********************************************
 * Class TwMonth
 * Класс Месяц. Предназначен для работы с месяцами
 */
var TwMonth = new Class({
    initialize: function(month, year) {
        if (month && year) {
            this.month = lpad(month, 2, '0');
            this.year = year;
            this.setup = true;
        } else {
            var dt = new Date();
            this.year = dt.getFullYear();
            this.month = lpad(dt.getMonth() + 1, 2, '0');
            this.setup = false;
        }
    },

    getYear: function() {
        return this.year;
    },

    getMonth: function() {
        return this.month;
    },

    isSetup: function() {
        return this.setup;
    },

    getMonthName: function() {
        switch (this.month) {
            case '01': return "январь";
            case '02': return "февраль";
            case '03': return "март";
            case '04': return "апрель";
            case '05': return "май";
            case '06': return "июнь";
            case '07': return "июль";
            case '08': return "август";
            case '09': return "сентябрь";
            case '10': return "октябрь";
            case '11': return "ноябрь";
            case '12': return "декабрь";
        }
    },

    // переход к следующему месяцу
    inc: function() {
        var m = parseInt(this.month, 10);
        if (m < 12) {
            this.month = lpad(m + 1, 2, '0');
        } else {
            this.month = '01';
            this.year = (parseInt(this.year, 10) + 1) + '';
        }
    },

    // переход к предыдущему месяцу
    decr: function() {
        var m = parseInt(this.month, 10);
        if (m > 1) {
            this.month = lpad(m - 1, 2, '0');
        } else {
            this.month = '12';
            this.year = (parseInt(this.year, 10) - 1) + '';
        }
    }
});

/*********************************************
 * Class WebDocView
 * Представление опубликованного документа
 */
var WebDocView = new Class({
    initialize: function(format, docUrl) {
        this.format = format;                   // формат представления
        this.docUrl = docUrl;                   // URL представления
    }
});

/*********************************************
 * Class WebDoc
 * Опубликованный документ
 */
var WebDoc = new Class({
    initialize: function(baseUrl, docid, views) {
        this.baseUrl = baseUrl;                 // базовый URL документа
        this.docid = docid;                     // ID документа
        this.views = views;                     // представления документа
    },

    // возвращает представление документа заданного формата
    getView: function(format) {
        var view;
        for (j = 0; j < this.views.length; j++) {
            var v = this.views[j];
            if (v.format == format) {
                view = v;
                break;
            }
        }
        return view;
    },

    loadView: function(format, onCompleteFunction, onFailureFunction, args) {
        //alert("loadView: " + format);
        var view = this.getView(format);
        if (view) {
            var myAjax = new Ajax(this.baseUrl + "/" + this.docid + "/" + view.docUrl + "?ts=" + (new Date()).getTime(), {method: 'get', postFunction: onCompleteFunction, postFailFunction: onFailureFunction, src: this, args: args});
            myAjax.addEvent('onComplete', this.processView);
            myAjax.addEvent('onFailure', this.processViewFailure);
            myAjax.request();
        } else {
            onFailureFunction(null, this, args);
        }
    },

    processView: function(doc) {
        if (this.options.postFunction) {
            this.options.postFunction(doc, this.options.src, this.options.args);
        }
    },

    processViewFailure: function(doc) {
        if (this.options.postFailFunction) {
            this.options.postFailFunction(doc, this.options.src, this.options.args);
        }
    },

    loadPres: function() {
        this.loadView("pres", this.processPres, this.oops);
    },

    loadHotWantedMan: function() {
        this.loadView("hot", this.processHotWantedMan, this.oops);
    },

    loadPresNd: function() {
        this.loadView("pres", this.processHotNd, this.oops);
    },

    loadShort: function(sep, format) {
        if (!format) format = "short";
        this.loadView(format, this.processShort, this.oops, {sep: sep});
    },

    oops: function() {
        //alert("Oops");
    },

    processPres: function(doc, src, args) {
        var console = document.getElementById("presentation");
        console.innerHTML = console.innerHTML + "<div>" + doc + "</div><hr noshade color='#01193c' size='1'/>";

        var presImgId = 'presImg_' + src.docid;
        if ($(presImgId)) {
            var presImgSrc = getBaseName($(presImgId).src);

            new Asset.image(src.baseUrl + "/" + src.docid + "/" + presImgSrc, {id: presImgId,
                onload: function() {
                    var koeff = $(presImgId).width / this.width;
                    this.width = $(presImgId).width;
                    this.height = koeff * this.height;

                    this.className = 'presPhoto';

                    $(presImgId).replaceWith(this);
                }});
        }
    },

    processHotWantedMan: function(doc, src, args) {
        $(hotWantedMan).innerHTML = doc;
    },

    processHotNd: function(doc, src, args) {
        $(ndAdditionallInfo).innerHTML = $(ndAdditionallInfo).innerHTML + "<li class=lik2>" + doc;
    },

    processShort: function(doc, src, args) {
        var console = document.getElementById("lenta");
        var sep = "";
        if ((args) && (args.sep)) {
            sep = args.sep;
        }
        console.innerHTML = console.innerHTML + "<div>" + doc + "</div>" + sep;
    }
});


    function loadDocument(webDoc, format, displayQueue, position) {
        var view = webDoc.getView(format);
        var myAjax = new Ajax(webDoc.baseUrl + "/" + webDoc.docid + "/" + view.docUrl + "?ts=" + (new Date()).getTime(), {method: 'get', displayQueue: displayQueue, position: position});
        myAjax.addEvent('onComplete', loadDocumentComplete);
        myAjax.addEvent('onFailure', loadDocumentFailure);
        myAjax.request();
    }

    function loadDocumentComplete(doc) {
        this.options.displayQueue.put(doc, this.options.position);
    }

    function loadDocumentFailure() {
        this.options.displayQueue.skip(this.options.position);
    }

    // Очередь отображения документов
    var DisplayQueue = new Class({
        initialize: function(length, targetDisplay, sep) {
            this.docsToDisplay = new Array(length);
            this.docsToSkip = new Array(length);
            this.cursor = 0;
            this.targetDisplay = targetDisplay;
            this.sep = sep;
        },
        put: function(doc, position) {
            this.docsToDisplay[position] = doc;
            this.tryDisplay();
        },
        skip: function(position) {
            this.docsToSkip[position] = 1;
            this.tryDisplay();
        },
        tryDisplay: function() {
            if (this.docsToDisplay[this.cursor] != null) {
                this.display();
                this.next();
            }
            if (this.docsToSkip[this.cursor] == 1) {
                this.next();
            }
        },
        next: function() {
            this.cursor++;
            if (this.cursor < this.docsToDisplay.length) {
                this.tryDisplay();
            }
        },
        display: function() {
            this.targetDisplay.innerHTML = this.targetDisplay.innerHTML + "<div>" + this.docsToDisplay[this.cursor]  + "</div>" + this.sep;
        }
    });

/*********************************************
 * Class RegionLogo
 */
var RegionLogo = new Class({
    initialize: function(region) {
        this.region = region;
    },
    load: function() {
        new Asset.image("/img/" + this.region + "/img/mh01.jpg", {id: "mh01", onload: this.finish});
        new Asset.image("/img/" + this.region + "/img/mh02.jpg", {id: "mh02", onload: this.finish});
        new Asset.image("/img/" + this.region + "/img/mh04.jpg", {id: "mh04", onload: this.finish});
        new Asset.image("/img/" + this.region + "/img/mh09.jpg", {id: "mh09", onload: this.finish});
    },
    finish: function() {
        $(this.id).replaceWith(this);
    }
});

/*********************************************
 * Functions
 */
function onRegionChanged(selRegion) {
    var oRegion = selRegion.options[selRegion.selectedIndex];
    var region = oRegion.value;
    Cookie.set('region', region, {duration: 10, path:'/'});
    setRegionLogo(region);
    refreshService();
}

function onVedomstvoChanged(selVedomstvo) {
    var oVedomstvo = selVedomstvo.options[selVedomstvo.selectedIndex];
    var vedomstvo = oVedomstvo.value;
    Cookie.set('vedomstvo', vedomstvo, {duration: 10, path:'/'});
    setVedomstvoLogo(vedomstvo);
    refreshService();
}

function refreshService() {
}

function getVedomstvoSite(vedomstvo) {
    switch (vedomstvo) {
        case "01": return "http://www.mvd.ru";
        case "02": return "http://www.fms.gov.ru";
        case "04": return "http://www.fsb.ru/ ";
        case "05": return "http://www.customs.ru";
        case "06": return "http://www.minjust.ru/";
        case "07": return "http://www.genproc.gov.ru";
        case "08": return "http://www.mchs.gov.ru";
        case "09": return "http://www.fskn.gov.ru";
    }
    return "#";
}

function onInit() {
    populateDictionaries();
    initRegion();
    initVedomstvo();
    var visibility = true;
    initService(visibility);
}

function initRegion() {
    var region = getRegion();
    setRegionCombo(region);
    setRegionLogo(region);
}

function initVedomstvo() {
    var vedomstvo = getVedomstvo();
    setVedomstvoCombo(vedomstvo);
    setVedomstvoLogo(vedomstvo);
}

function getRegion() {
    var region = Cookie.get('region');
    if (!region) {
        region = "00";
    }
    return region;
}

function getVedomstvo() {
    var vedomstvo = Cookie.get('vedomstvo');
    if (!vedomstvo) {
        vedomstvo = "00";
    }
    return vedomstvo;
}

function setRegionLogo(region) {
    var logo = new RegionLogo(region);
    logo.load();
}

function setRegionCombo(region) {    
    var o = $('sr' + region);
    o.selected = true;
}

function setVedomstvoCombo(vedomstvo) {
    var o = $('sv' + vedomstvo);
    o.selected = true;
}

function setVedomstvoLogo(vedomstvo) {
    if (vedomstvo == "00") {
        $(vedlogocnt).style.display = "none";
    } else {
        $('vedlogo').src = "/img/ved" + vedomstvo + ".jpg";
        ;
        var vedlink = getVedomstvoSite(vedomstvo);
        $(vedhref).href = vedlink;
        $(vedlogocnt).style.display = '';
    }
}

function getXMLDOM(xml) {
    var d;
    if (window.ie) {
        d = new ActiveXObject("Microsoft.XMLDOM");
        d.loadXML(xml);
        return d;
    } else {
        var parser = new DOMParser();
        d = parser.parseFromString(xml, "text/xml");
        return d;
    }
}

function loadContents(contentsUrl, format, postFunction, failFunction) {
    if (!format) format = "short";
    var myAjax = new Ajax(contentsUrl + "?ts=" + (new Date()).getTime(), {method: 'get', format: format, postFunction: postFunction});
    myAjax.addEvent('onComplete', processContents);
    if (failFunction) {
        myAjax.addEvent('onFailure', failFunction);
    }
    myAjax.request();
}

function processContents(contentsDoc) {
    var xmlDoc = getXMLDOM(contentsDoc);

    var elemContents = xmlDoc.getElementsByTagName("contents")[0];
    var baseUrl = elemContents.getAttribute("baseURL");

    var nsDocs = xmlDoc.getElementsByTagName("doc");

    var webDocs = new Array(nsDocs.length);

    var j = 0;
    for (j = 0; j < nsDocs.length; j++) {
        var doc = nsDocs[j];
        var docid = doc.getAttribute("id");
        var nsViews = doc.getElementsByTagName("view");
        var k = 0;
        var views = new Array(nsViews.length);
        for (k = 0; k < nsViews.length; k++) {
            var view = nsViews[k];
            views[k] = new WebDocView(view.getAttribute("format"), view.getAttribute("file"));
        }
        webDocs[j] = new WebDoc(baseUrl, docid, views);
    }
    if (this.options.postFunction) {
        this.options.postFunction(webDocs);
    } else {

    }
}

function getBaseName(url) {
    var indx = url.lastIndexOf("/");
    if (indx > 0) {
        url = url.substring(indx + 1);
    }
    return url;
}

function showDoc(options) {
    var u = GL_BASE_URL + "/" + options.objectid + "/" + options.docname + "?ts=" + (new Date()).getTime();
    window.location = u;
}

function showDocHot(options) {
    var u = GL_BASE_URL_HOT + "/" + options.objectid + "/" + options.docname + "?ts=" + (new Date()).getTime();
    window.location = u;
}

function showNdDoc(options) {
    var u = GL_BASE_URL_ND + "/" + options.objectid + "/" + options.docname;
    window.location = u;
}

function listLoaded(webDocs) {
    $(lenta).innerHTML = '';
    $(lenta).style.display = '';
    var published = false;
    if (webDocs) {
        for (i = 0; i < webDocs.length; i++) {
            published = true;
            webDocs[i].loadShort('<hr noshade color="#dce6f4" size="1" class="hr2"/>');
        }
    }
    if (!published) {
        nothingFind();
    }
}

function nothingFind() {
    $(lenta).innerHTML = "Нет опубликованных материалов";
    $(lenta).style.display = '';
}

function getFullView(doc) {
    var res = '';
    var ns = doc.getElementsByTagName("view");
    var i = 0;
    for (i = 0; i < ns.length; i++) {
        var e = ns[i];
        if (e.getAttribute("format") == 'full') {
            res = doc.getAttribute("id") + "/" + e.getAttribute("file");
        }
    }
    return res;
}

function lpad(s, len, ch) {
    var str = s + '';
    while (str.length < len) {
        str = ch + str;
    }
    return str;
}

function getURLParam(strParamName) {
    var strReturn = "";
    var strHref = window.location.href;
    if (strHref.indexOf("?") > -1) {
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for (var iParam = 0; iParam < aQueryString.length; iParam++) {
            if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1) {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
}

function replaceURLParam(initURL, strParamName, strNewValue) {
    var strReturn = "";
    var strHref = initURL;
    var pi = strHref.indexOf("?");
    if (pi > -1) {
        var found = false;
        var strBaseUrl = strHref.substring(0, pi + 1);
        strReturn = strBaseUrl;
        var strQueryString = strHref.substr(pi + 1).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for (var iParam = 0; iParam < aQueryString.length; iParam++) {
            if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1) {
                strReturn += "&" + strParamName + "=" + escape(strNewValue);
                found = true;
            } else if (aQueryString[iParam] != '') {
                strReturn += "&" + aQueryString[iParam];
            }
        }
        if (!found) {
            strReturn += "&" + strParamName + "=" + escape(strNewValue);
        }
    } else {
        strReturn = strHref + "?" + strParamName + "=" + escape(strNewValue);
    }
    return unescape(strReturn);
}

var GL_ACTIVE_MONTH = new TwMonth(getURLParam("tbSelMonth"), getURLParam("tbSelYear"));
if (GL_ACTIVE_MONTH.isSetup()) {
    var GL_ACTIVE_DATE = new TwDate("01." + GL_ACTIVE_MONTH.getMonth() + "." + GL_ACTIVE_MONTH.getYear());
} else {
    var GL_ACTIVE_DATE = new TwDate(getURLParam("date"));
}
var GL_BASE_URL = "";
var GL_BASE_URL_HOT = "";
var GL_BASE_URL_ND = "";