var cookie_user = "mainsourceuser";
function init_thinks_tasks_task()
{
    $(document).ready(function()
    {
        var hide_answer = $("#hide_answer");
        var show_answer = $("#show_answer");
        var answer_div = $("#answer_div");
        hide_answer.hide();
        answer_div.hide();
        var show = false;
        $("#answer_but").click(function()
        {
            var status_answer1 = show ? hide_answer : show_answer;
            var status_answer2 = show ? show_answer : hide_answer;
            show = !show;
            if(show) answer_div.slideDown("fast"); else answer_div.slideUp("fast");
            status_answer1.hide("fast");
            status_answer2.show("fast");
        });
    });
}

function init_about_employees()
{
    $(document).ready(function()
    {
        $("#employees tr td:odd").each(function()
        {
            var m = $(this).parent().attr("id") + "@" + "mainsource.ru";
            $(this).html($(this).html()+"<br/><a href=\"ma"+"ilto:"+m+"\">"+m+"</a>");
        });


    });
}

function init_about()
{
    $(document).ready(function()
    {
        setPhotosGallery("doc-registration");
    });
}

function init_main()
{
    $(document).ready(function()
    {
        $("#projects_accrodeon").accordion({
            fillSpace:true
            , autoHeight:true
        });
    });
}

function init_main_lead()
{
    $(document).ready(function()
    {
        function changeLeadView(hideDiv, showDiv)
        {
            hideDiv.fadeOut("fast", function(){
                showDiv.fadeIn("fast");
            });    
        }
        var leadList = $("#lead-list");
        $(".lead").click(function(){
            changeLeadView(leadList, $("#lead-"+$(this).attr("lead")));
        });
        $(".lead-list").click(function(){
            changeLeadView($("#lead-"+$(this).attr("lead")), leadList);
        });
    });
}

function init_main_sites(projectsArray)
{
    function getProjectsSrc(name){return "/images/project/sites/"+name+"/preview.png";}
    var imagesContent = "";
    for(var i=0; i<projectsArray.length; i++){
        var projectSrc = getProjectsSrc(projectsArray[i][0]);
        imagesContent += "<img width=\"250\" height=\"250\" src=\"" + projectSrc + "\" alt=\"" + projectsArray[i][0] + "\" sitename=\"" + projectsArray[i][1] + "\" sitepage=\"" + projectsArray[i][0] + "\"/>";
        preloadImage(projectSrc);
    }
    $(document).ready(function()
    {
        var slider = $('#sites-slider');
        slider.html(imagesContent);
        var linkWrap = $(".sites-slider-name");
        var link = $(".sites-slider-name a");
        slider.cycle({
              fx: 'zoom' // choose your transition type, ex: turnDown, fade, scrollUp, shuffle, etc...
            , easing: 'bouncein'
            , before: function(){
                linkWrap.fadeTo(400, 0.1);
            }
            , after: function(){
                var project = $(this);
                link.attr("href", "/projects/sites/" + project.attr("sitepage"));
                link.html(project.attr("sitename"));
                linkWrap.fadeTo(400, 1);
            }
        });
    });
}

function init_about_vacancy_student()
{
    $(document).ready(function()
    {
        $("#webmasterBut").click(function()
        {
            var key = prompt("Введите ключ к информации ftp-подключения", "");
            if(key != null)
            {
                if(key != '')
                {
                    var params = new Object();
                    params[$(this).attr("vacancy")] = "";
                    params[$(this).attr("param")] = key;
                    $.post("webmaster-ftp.vacancy", params, function(data)
                    {
                        if(data != "false")
                        {
                            var ftp = eval(data);
                            alert("Параметры FTP-подключения:\n\n>> Хост: " + ftp[0] + "\n>> Логин: " + ftp[1] + "\n>> Пароль: " + ftp[2]);
                        }
                        else
                            alert("Ошибка! Неверный ключ.");
                    });
                }
                else
                    alert("Ошибка! Вы не ввели ключ.");
            }
        });
    });
}

function init_projects_main()
{
    $(document).ready(function()
    {
        function setLinkStyle(link, hover){
            $(link.parents("li")[0]).removeClass(hover?"m_out":"m_over").addClass(hover?"m_over":"m_out");
        }
        $(".projects-types a")
                .mouseout(function(){setLinkStyle($(this), false);})
                .mouseover(function(){setLinkStyle($(this), true);});
    });
}

function init_projects()
{
    $(document).ready(function()
    {
        function changePreviewBlock(link, hover){
            link.parents("td.project_preview").removeClass("project_preview_b"+(!hover?"-hover":""))
                                              .addClass("project_preview_b"+(hover?"-hover":""));
        }
        $(".projects_table td.project_preview a").mouseover(function(){changePreviewBlock($(this), true);})
                                                 .mouseout(function(){changePreviewBlock($(this), false);});


    });
}

function init_editProjects(){
    
}

function init_editProject(){   
    $(document).ready(function()
    {
        $("#editProject-date").datepicker({
            dateFormat: "dd.mm.yy"
        });                      
        $("#editProject-but").click(function(){
            var thisbut = $(this);
            $(this).hide();
            var indikator = $(this).prev(".editProject-indikator");
            indikator.show();
            var params = createParamsObject();
            var curPrrojectId = $("#editProject-id");
            var update = curPrrojectId.val() != "";
            var curProjectPsevdoLink = $("#editProject-psevdoLink");
            putInputParamToParamsObject(params, curPrrojectId);
            putInputParamToParamsObject(params, $("#editProject-rubric"));
            putInputParamToParamsObject(params, curProjectPsevdoLink);
            putInputParamToParamsObject(params, $("#editProject-title"));
            putInputParamToParamsObject(params, $("#editProject-date"));
            putInputParamToParamsObject(params, $("#editProject-link"));
            putInputParamToParamsObject(params, $("#editProject-customer"));
            putInputParamToParamsObject(params, $("#editProject-customerLink"));
            putInputParamToParamsObject(params, $("#editProject-timing"));
            putInputParamToParamsObject(params, $("#editProject-cost"));
            putInputParamToParamsObject(params, $("#editProject-description"));
            putInputParamToParamsObject(params, $("#editProject-capabilities"));
            putInputParamToParamsObject(params, $("#editProject-screens"));
            putInputParamToParamsObject(params, $(".editProject-projectType"));
            putInputParamToParamsObject(params, $(".editProject-tool"));
            putInputParamToParamsObject(params, $("#editProject-cms"));
            putInputParamToParamsObject(params, $("#editProject-useMainPage"));

            function endInicator(){indikator.hide();thisbut.show();}
            sendRequest($(this).attr("op"), params, function(response){
                if(update){
                    alert("Успешно обновлено");
                    setTimeout(endInicator, 200);
                }
                else
                    window.location = "/projects/sites/edit/" + curProjectPsevdoLink.val();

            },function(){
                endInicator();
                alert("Ошибка");
            });
        });
    });

}

function init_projects_site()
{
    $(document).ready(function()
    {
        var screenimg = $(".screen-box img");
        var screenimgSrc = screenimg.attr("src");
        var screenimgPath = screenimgSrc.substring(0, screenimgSrc.lastIndexOf("/")+1);
        var screenimgExt = screenimgSrc.substring(screenimgSrc.lastIndexOf("."));
        function changeScreen(screen){
            screenimg.attr("src", screenimgPath + screen.attr("screen") + screenimgExt);
        }
        var screens = $(".screen-select-box td");
        var i = 0;
        screens.each(function(){
            setClickableHoverElement($(this), "screen-select", changeScreen, "state", (i++)==0?1:0, screens);
        });


    });
}

function init_balances()
{
    $(document).ready(function(){
        $(".balance-month").click(function(){
            $(this).parent().parent().next().toggle();
        });
    });
}

function init_editBalances()
{
    $(document).ready(function()
    {
        $(".editBalance-date").datepicker({
            dateFormat: "dd.mm.yy"
        });
        $(".editBalance-but").click(function(){
            var thisbut = $(this);
            $(this).hide();
            var indikator = $(this).prev(".editBalance-indikator");
            indikator.show();
            var tds = $(this).parent().siblings();
            var params = createParamsObject();
            var curBalanceId = tds.children(".editBalance-id");
            var update = curBalanceId.val() != "";
            putInputParamToParamsObject(params, curBalanceId);
            putInputParamToParamsObject(params, tds.children(".editBalance-date"));
            putInputParamToParamsObject(params, tds.children(".editBalance-debit"));
            putInputParamToParamsObject(params, tds.children(".editBalance-balance"));
            putInputParamToParamsObject(params, tds.children(".editBalance-partner"));
            putInputParamToParamsObject(params, tds.children(".editBalance-message"));

            function endInicator(){indikator.hide();thisbut.show();}
            sendRequest($(this).attr("op"), params, function(response){
                if(update)
                    setTimeout(endInicator, 200);
                else
                    window.location.reload(true);

            },function(){
                endInicator();
                alert("Ошибка");
            });
        });


    });
}

function init_editTools()
{
    $(document).ready(function()
    {
        $(".changeTool-but").click(function(){
            var thisbut = $(this);
            $(this).hide();
            var indikator = $(this).prev(".changeTool-indikator");
            indikator.show();
            var tds = $(this).parent().siblings();
            var params = createParamsObject();
            var curToolId = tds.children(".changeTool-id");
            var update = curToolId.val() != "";
            putInputParamToParamsObject(params, curToolId);
            putInputParamToParamsObject(params, tds.children(".changeTool-title"));
            putInputParamToParamsObject(params, tds.children(".changeTool-name"));
            putInputParamToParamsObject(params, tds.children(".changeTool-vendor"));
            putInputParamToParamsObject(params, tds.children(".changeTool-message"));
            putInputParamToParamsObject(params, tds.children(".changeTool-category"));
            function endInicator(){indikator.hide();thisbut.show();}
            sendRequest($(this).attr("op"), params, function(response){
                if(update)
                    setTimeout(endInicator, 200);
                else
                    window.location.reload(true);

            },function(){
                endInicator();
                alert("Ошибка");
            });
        });


    });
}

function init_commentsBlock(show)
{
    $(document).ready(function()
    {
        var blockTo = $("#comment-block-to");
        var block = $("#comment-block");
        var url = location+"";
        var commentIdIndex = url.indexOf("#comment-");
        if(show || commentIdIndex != -1)
        {
            blockTo.hide();
            block.show();
        }
        else
            block.hide();
        init_addComment();
        init_commentsList(commentIdIndex != -1 ? url.substr(commentIdIndex+1) : false);
        blockTo.children("a").click(function(){
            blockTo.hide();
            block.slideDown();
        });
    });
}

function init_commentsList(commentId)
{
    $(document).ready(function()
    {
        if(commentId)
            blinkComment(commentId);
    });
}
function blinkComment(commentId, callback)
{
    $("#"+commentId).addClass("curComment").fadeTo(1000, 0.1, function(){
        $(this).removeClass("curComment");
        $(this).fadeTo(1000, 1, function(){
            if(callback != undefined)
                callback();
        });
    });
}
function init_addComment()
{
    $(document).ready(function()
    {
        var user = $('#addComment-user');
        var username = $.cookie(cookie_user);
        if(username)
            user.val(username);
        $('#addComment-text').wysiwyg({
            controls : {
                insertImage : {visible : false},
                bold          : { visible : true, tags : ['b', 'strong'], css : { fontWeight : 'bold' } },
                italic        : { visible : true, tags : ['i', 'em'], css : { fontStyle : 'italic' } },
                strikeThrough : { visible :  true },
                underline     : { visible :  true },

                separator00 : { visible :  false },

                justifyLeft   : { visible :  false },
                justifyCenter : { visible :  false },
                justifyRight  : { visible :  false},
                justifyFull   : { visible :  false },

                separator01 : { visible :  false},


                indent  : { visible :  false },
                outdent : { visible :  false },

                //separator02 : { visible :  true },

                subscript   : { visible :  false },
                superscript : { visible :  false},

                separator02 : { visible :  false },

                undo : { visible :  false },
                redo : { visible :  false },

                separator03 : { visible :  false },


                h1mozilla  : { visible :  false },
                h2mozilla  : { visible :  false },
                h3mozilla  : { visible :  false },
                h1  : { visible :  false },
                h2  : { visible :  false },
                h3  : { visible :  false },

                increaseFontSize  : { visible :  false },
                decreaseFontSize  : { visible :  false },

                insertOrderedList    : { visible :  false },
                insertUnorderedList  : { visible :  false },
                insertHorizontalRule : { visible :  false },
                separator04 : { visible : false },
                separator05 : { visible : true},
                separator06 : { visible : true},
                separator07 : { visible : false},
                separator08 : { visible : false},
                separator09 : { visible : false},
                removeFormat : { visible : false}

                //cut   : { visible : true },
                //copy  : { visible : true},
                //paste : { visible : true }
                //html : {visible : true}
                /*,alert : {
                    visible   : true,
                    exec      : function() { alert('Hello World'); },
                    className : 'alert'
                }*/
            }
           // , messages: {nonSelection : 'выделите текст, который вы хотите разместить как ссылку2'}
        });
        $("#addComment-form").show();
        $("#addComment-but").click(function(){
            username = user.val();
            if(username == '' && confirm("Вы не заполнили поле с Вашим именем.\nЖелаете представиться?")){
                username = prompt("Введите Ваше имя", "");
                if(username == null) return;
                user.val(username);
            }
            $(this).hide();
            $("#addComment-indikator").show();
            $.cookie(cookie_user, user.val());
            var params = createParamsObject();
            putInputParamToParamsObject(params, $('#addComment-parentId'));
            putInputParamToParamsObject(params, $('#addComment-parentType'));
            putInputParamToParamsObject(params, $('#addComment-parentUri'));
            putInputParamToParamsObject(params, $('#addComment-text'));
            putInputParamToParamsObject(params, $('#addComment-user'));
            function endInicator(){$("#addComment-indikator").hide();$("#addComment-but").show();}
            sendRequest($(this).attr("op"), params, function(response){
                $('#addComment-text').wysiwyg('clear');
                var commentId = response["id"];
                var commentHtml = response["html"];
                $("#comments-list").append(commentHtml);
                blinkComment(commentId);
                scrollToElement("end-comments-list");
                setTimeout(endInicator, 100);
            },function(){
                endInicator();
                alert("Ошибка");
            });
        });
    });
}

function init_content()
{
    $(document).ready(function()
    {
        init_newItFact();
        function setContentBlock(blockLink, blockFlag)
        {
            var aBlockLink = $(blockLink.parents("a")[0]);
            var otherBlockLink = aBlockLink.children(".admin-content-block-"+blockFlag);
            var block = $($(aBlockLink.parents()[0]).next("div.admin-content-block")[0]);
            blockLink.hide();
            otherBlockLink.show();
            if(blockFlag) block.slideDown();
            else block.slideUp();
        }
        $(".admin-content-block-0").click(function(){setContentBlock($(this), 1);});
        $(".admin-content-block-1").click(function(){setContentBlock($(this), 0);});
    });
}

function init_newArticle()
{
    $(document).ready(function()
    {
        var descriptionBlock = $("#article-description-block");
        var controlDescriptionPattern = $("#article-contorol-description-pattern").html();
        function addNewControlPanel(afterElement){
            var newControlPanel = null;
            if(afterElement)
            {
                afterElement.after(controlDescriptionPattern);
                newControlPanel = $(afterElement.next()[0]);
            }
            else
            {
                descriptionBlock.append(controlDescriptionPattern);
                newControlPanel = $(descriptionBlock.children()[0]);
            }
            function createImageUploader(but)
            {
                var butimg = but.children("img");
                var imageUploader = but.upload({
                    name: 'file',
                    method: 'post',
                    enctype: 'multipart/form-data',
                    action: 'photo.upload?'+"id"+'='+"1",
                    onSelect: function(){
                        var accept = acceptImage(imageUploader.filename());
                        if(!accept) alert("Ошибка! Недопустимый тип файла");
                        return accept;
                    },
                    onSubmit: function(){
                        but.attr("disabled", true);
                        butimg.attr("src", "/images/indicator.gif");
                    },
                    onComplete: function(data){
                        butimg.attr("src", "/images/add.gif");
                        but.attr("disabled", false);
                        if(data == "false")
                            alert("Ошибка при добавлении!");
                        else
                            addImageToPanel("imageId", eval(data), "", false);
                    }
                });
                function addImageToPanel(){}
            }
            function addNewElement(control, elementClass, code){
                var controlPanel = $(control.parents("div")[0]);
                controlPanel.after("<div><fieldset><legend align='right'><a href='javascript:void(0);'>Удалить</a></legend>" +
                                   "<div class='"+elementClass+" desc-el'>"+code+"</div>" +
                                   "</fieldset></div>");
                var newElement = $(controlPanel.next()[0]);
                addNewControlPanel(newElement);
                return newElement;
            }
            newControlPanel.children(".control-paragraph").click(function(){
                addNewElement($(this), "new-article-description-paragraph", "<textarea rows='4' cols='60'></textarea>");
            });
            newControlPanel.children(".control-img").click(function(){
                var newElement = addNewElement($(this), "new-article-description-img",
                                                      "<input type='hidden' name='' value=''>" +
                                                      "<div class='uploadImgBut' onclick='return false;' align='center' style='width:36px;'>[<img border='0' src='/images/add.gif' style='vertical-align:middle;' title='Добавить картинку'/>]</div>" +
                                                      "<input size='60' type='text'> (подсказка)" +
                                                      "<br/><input size='60' type='text'> (описание)");
                createImageUploader($(newElement.find(".uploadImgBut")[0]));
            });
            newControlPanel.children(".control-code").click(function(){
                addNewElement($(this), "new-article-description-code", "<textarea rows='4' cols='60'></textarea>");
            });
        }
        addNewControlPanel();
        $("#saveArticle").click(function(){
            var articleText = "";
            descriptionBlock.children(".desc-el").each(function(){

                articleText += $(this).html();
            });
            alert(articleText);
        });
    });
}

function init_newItFact()
{
    $(document).ready(function()
    {
        var user = $('#addItFact-user');
        var username = $.cookie(cookie_user);
        if(username)
            user.val(username);
         $("#addIdFact-but").click(function(){
            username = user.val();
            if(username == '' && confirm("Вы не заполнили поле с Вашим именем.\nЖелаете представиться?")){
                username = prompt("Введите Ваше имя", "");
                if(username == null) return;
                user.val(username);
            }
             $(this).attr("disabled", true);
            //$(this).attr("src","/images/indicator.gif");
            $.cookie(cookie_user, user.val());
            var params = createParamsObject();
            putInputParamToParamsObject(params, $('#addItFact-text'));
            putInputParamToParamsObject(params, $('#addItFact-user'));
            function endInicator(){$("#addIdFact-but").attr("disabled", false);}
            sendRequest($(this).attr("op"), params, function(response){
                var itFactId = response["id"];
                var itFactHtml = response["html"];
                setItFact(itFactId, itFactHtml);
                endInicator();
            },function(){
                endInicator();
                alert("Ошибка");
            });
        });
    });
}

function init_footer()
{
    $(document).ready(function()
    {
        init_itFacts();
        init_controlButs();
        init_flash();
    });
}

function init_controlButs()
{
    $(document).ready(function()
    {
        $("img.controlbut").mouseover(function(){$(this).attr("src", "/images/"+$(this).attr("name")+"-hover.png");})
                           .mouseout(function(){$(this).attr("src", "/images/"+$(this).attr("name")+".png");});
    });
}

function init_flash()
{
    $(document).ready(function()
    {
        $('.flash-ban').each(function(){
            var props = createParamsObject();
            putParamToParamsObject(props, "src", $(this).attr("fsrc"));
            putParamToParamsObject(props, "width", parseInt($(this).attr("fwidth")));
            putParamToParamsObject(props, "height", parseInt($(this).attr("fheight")));
            putParamToParamsObject(props, "wmode", "transparent");
            $(this).flash(props,{version: 8});
        });
    });
}

function setItFact(itFactId, itFactHtml){ $("#itFact-curId").val(itFactId);$("#fact-content").html(itFactHtml); }

function init_itFacts()
{
    $(document).ready(function()
    {
        var cookie_fact = "mainsourcefact";
        var factBox = $("#fact-box");
        var factLink = $("#fact-link");
        var newFactLink = $("#new-fact-link");
        var newFactLinkWrap = $("#new-fact-link-wrap");
        var newFactProgress = $("#new-fact-progress");
        function showFact(fast){
            function afterShow(noCookies){
                factLink.hide();
                newFactLinkWrap.show();
                if(noCookies == undefined || !noCookies){
                    $.cookie(cookie_fact, null, {path:"/"});
                    $.cookie(cookie_fact, "1", {path:"/"});
                }
            }
            if(fast){factBox.show();afterShow(true);}
            else factBox.show("slow", afterShow);
        }
        function hideFact(fast){
            newFactLinkWrap.hide();
            factLink.show();
            $.cookie(cookie_fact, null, {path:"/"});
            $.cookie(cookie_fact, "0", {path:"/"});
            factBox.hide(fast?0:"slow");
        }
        factLink.click(function(){showFact(false);});
        $("#fact-link-hide").click(function(){hideFact(false);});
        newFactLink.click(function(){
            newFactLinkWrap.hide();
            newFactProgress.show();
            var params = createParamsObject();
            putInputParamToParamsObject(params, $('#itFact-curId'));
            function endInicator(){newFactProgress.hide();newFactLinkWrap.show();}
            sendRequest(newFactLink.attr("op"), params, function(response){
                setTimeout(function(){
                    var itFactId = response["id"];
                    var itFactHtml = response["html"];
                    setItFact(itFactId, itFactHtml);
                    endInicator();
                }, 300);
            },function(){
                endInicator();
                alert("Ошибка");
            });
        });

        var cookie_status = $.cookie(cookie_fact);
        if(cookie_status != null && parseInt(cookie_status))
            showFact(true);
    });
}

function setPhotosGallery(galleryId)
{
    $("#"+galleryId+" a").fancybox({
            hideOnContentClick: true,
            overlayShow: true,
            overlayOpacity: 0.5
        });
}

function acceptImage(filename)
{
    if(filename != null && filename != undefined && filename != '')
    {
        var imageTypes = ['.png', '.jpg', '.jpeg', '.gif'];
        for(var i=0; i < imageTypes.length; i++)
            if(filename.toLowerCase().indexOf(imageTypes[i]) != -1)
                return true;
    }
    return false;
}

function scrollToElement(elementId){window.scrollTo(1, document.getElementById(elementId).offsetTop);}

function createParamsObject(){return {};}
function putParamToParamsObject(paramsObject, key, value){paramsObject[key] = value;}
function putInputParamToParamsObject(paramsObject, input){
    var values = [];
    input.each(function(){
        if($(this).attr("type") != "checkbox" || this.checked)
            values[values.length] = $(this).val();
            //paramsObject[$(this).attr("name")] = $(this).val();
    });
    if(values.length != 0) {paramsObject[input.attr("name")] = values.length == 1 ? values[0] : values;}
}
function checkParam(param){return param != undefined && param != "";}
function sendRequest(operation, paramsObject, successCallback, errorCallback){
    $.post("/"+operation + ".usjs", paramsObject, function(data){  
        var response = eval("(" + data + ")");
        if (response != false && successCallback)
            successCallback(response);
        if (response == false && errorCallback)
            errorCallback();
    });
}

function setClickableHoverElement(element, elementClass, callback, stateName, state, groups){
    var useState = stateName != "" && stateName != null && stateName != undefined;
    function changeHover(state){
        if(useState){
            var curState = element.attr(stateName);
            if(curState=="1") return;
        }
        element.removeClass(elementClass+(!state?"-hover":"")).addClass(elementClass+(state?"-hover":""));
    }
    element.mouseover(function(){changeHover(true);}).mouseout(function(){changeHover(false);})
           .click(function(){
                if(useState){
                    var curState = element.attr(stateName);
                    if(curState=="1") return;
                    if(groups){
                        groups.attr(stateName, "0").trigger("mouseout");
                    }
                    element.trigger("mouseover");
                    element.attr(stateName, "1");
                }
                if(callback) callback($(this));
            });
    if(useState){
        element.trigger(state?"mouseover":"mouseout");
        element.attr(stateName, state?"1":"0");

    }
}

function preloadImage(imgSrc){
    var img = new Image();
    img.src = imgSrc;
}

