$(document).ready(function () {
    //Flag's image change
    var imgFlagSrc;
    $(".flag").hover(
          function () {
            imgFlagSrc=$(this).attr("src");
            $(this).attr({src: imgFlagSrc.replace(/.png/,"_bw.png")});
          }, 
          function () {
            $(this).attr({src: imgFlagSrc});
          }
        );
    
    //Airsoft link animation
    $(".airsoftMenuLink").hover(
        function(){
            $("#pointerBox").animate( { paddingLeft:"7px" }, { duration:500 })
            .animate( { paddingLeft:"0px" }, { duration:500 });
        },
        function () {
            $("#pointerBox").stop();
            $("#pointerBox").css({paddingLeft:"0px"});
          }
    );
    
    //Group toggle
    $(".imgMenu").click(function () {
        var groupId = $(this).attr("groupid");
        
        if ($("#" + groupId).css("display") == "none"){
            $(this).attr({src: "design/minus.png"});
            setCookie(groupId,"show",3);
        }
        else{
            $(this).attr({src: "design/plus.png"});
            setCookie(groupId,"hide",3);
        }
        
        $("#" + groupId).toggle("slow");
    });
    
    $(".imgMenu").each(function (i) {
        var groupId = $(this).attr("groupid");
        if(getCookie(groupId) == "hide"){
            $(this).attr({src: "design/plus.png"});
            $("#" + groupId).css({'display': 'none'});
        }
        else{
            $(this).attr({src: "design/minus.png"});
            $("#" + groupId).css({'display': 'block'});
        }
    });
});

function SubmitGroupOrder (target,groupId,operationType,operationVal){
    var orderValue = $(target).val();
    if(isNaN(orderValue)){
        alert("Можно ввести только число!");
        return false;
    }
    
    $("#groupid").val(groupId);
    $("#sendval").val(orderValue);
    
    $("#groups_change_order").attr({ 
          action: "process/" + operationType + "_a_" + operationVal +".php"
        });

    $("#groups_change_order").submit();
}

function SubmitGroupDelete (groupId,operationType){
    var r = confirm("Вы действительно хотите удалить это?");
    
    if (r){
        $("#groupid").val(groupId);
        
        $("#groups_change_order").attr({ 
              action: "process/" + operationType + "_a_delete.php"
            });
    
        $("#groups_change_order").submit();
    }
}

function PhotoDelete (photoId,photoName){
    var r = confirm("Вы действительно хотите удалить это?");
    
    if (r){
        $("#groupid").val(photoId);
        $("#sendval").val(photoName);
        
        $("#groups_change_order").attr({ 
              action: "process/photos_a_delete.php"
            });
    
        $("#groups_change_order").submit();
    }
}

function setCookie(c_name,value,expiredays){
    var exdate=new Date();
    exdate.setDate(exdate.getDate()+expiredays);
    document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

function getCookie(c_name){
    if (document.cookie.length>0)
      {
      c_start=document.cookie.indexOf(c_name + "=");
      if (c_start!=-1)
        {
        c_start=c_start + c_name.length+1;
        c_end=document.cookie.indexOf(";",c_start);
        if (c_end==-1) c_end=document.cookie.length;
        return unescape(document.cookie.substring(c_start,c_end));
        }
      }
    return "";
}

function GroupFormCheck (target,buttonid,partnerid){
    if ($(target).val() == "" || $("#" + partnerid).val() == ""){
        $("#" + buttonid).attr({ 
          disabled: "disabled"
        });
    }
    else{
        $("#" + buttonid).attr({ 
          disabled: ""
        });
    }
}

//Add row with photo's menu
function AddPhotoLoader (targetInput){
    if ($(targetInput).attr("loadcheck")=='0'){
        $(".loaderrow_small:last").show();
        
        var loaderRow = "<tr class='loaderrow'><td colspan='2'><input name='upload_photo[]' onclick='AddPhotoLoader(this)' type='file' loadcheck='0' /></td></tr>";
        loaderRow += "<tr class='loaderrow_small' style='display:none'><td colspan='2'><input name='upload_photo_small[]' type='file' loadcheck='0' /> - ярлык фотографии<sup>*</sup></td></tr>";
        loaderRow += "<tr class='loaderrow_desc'><td class='photoAddRow'>Описание:</td><td class='photoAddRow'><input name='photo_desc[]' type='text' size='50' maxlenght='255' /></td></tr>";
        $(".loaderrow_desc:last").after(loaderRow);
        $(targetInput).attr({ 
              loadcheck: "1"
        });
        
        $(".loaderrow:odd").css("background-color", "rgb(204,204,204)");
        $(".loaderrow_small:odd").css("background-color", "rgb(204,204,204)");
        $(".loaderrow_desc:odd").css("background-color", "rgb(204,204,204)");
    }
}

function PhotoParentName(parentCont){
    
    var parentName = $("option[parentname]:selected").attr("parentname");
    
   $("#parent_name").val(parentName);
}

function ShowPhotos(parentIdTable){
    var tablePhoto = "";
    
    tablePhoto += "<table>";
    tablePhoto += "<tr>";
    if (isNaN(parentIdTable)){
        tablePhoto += "<td width='100px'></td>";
    }
    else{
        tablePhoto += "<td width='100px'><img src='photos/" + allPhotosGroups[parentIdTable]["photoname"] + "' alt='' id='group_photo' height='50px' /></td>";
    }
    
    tablePhoto += "<td><select id='showengroup' onchange='ShowPhotos(value)'>";
    
    if (isNaN(parentIdTable)){
        for (k=0;k<allPhotosGroupsCount;k++){
            tablePhoto += "<option value='" + k + "'>";
            tablePhoto += allPhotosGroups[k]["name"];
            tablePhoto += "</option>";
        }
        tablePhoto += "<option value='no' parentname='' selected='selected'>(!) Нет родителя</option>";
    }
    else{
        for (k=0;k<allPhotosGroupsCount;k++){
            if (allPhotosGroups[parentIdTable]["id"] == allPhotosGroups[k]["id"]){
                tablePhoto += "<option selected='selected' value='" + k + "'>";
            }
            else{
                tablePhoto += "<option value='" + k + "'>";
            }
            tablePhoto += allPhotosGroups[k]["name"];
            tablePhoto += "</option>";
        }
        tablePhoto += "<option value='no' parentname=''>(!) Нет родителя</option>";
    }
    
    tablePhoto += "</select></td>";
    if (isNaN(parentIdTable)){
        tablePhoto += "<td></td>";
    }
    else{
        tablePhoto += "<td><input type='button' value='Удалить' onclick='SubmitGroupDelete(" + allPhotosGroups[parentIdTable]["id"] + ",\"photogroup\")' id='' /></td>";
    }
    tablePhoto += "</tr>";
    
    if (parentIdTable != "no"){
        for (m=0;m<allPhotosCount;m++){
            if (allPhotos[m]["parentid"] == allPhotosGroups[parentIdTable]["id"]){
                tablePhoto += "<tr>";
                tablePhoto += "<td>" + allPhotos[m]["name"] + "</td>";
                tablePhoto += "<td>";
                tablePhoto += "<select onchange='SubmitGroupOrder(this," + allPhotos[m]["id"] + ",\"gallery\",\"parent\")'>";
                for (n=0;n<allPhotosGroupsCount;n++){
                    if (allPhotos[m]["parentid"] == allPhotosGroups[n]["id"]){
                        tablePhoto += "<option selected='selected' value='" + allPhotosGroups[n]["id"] + "'>";
                    }
                    else{
                        tablePhoto += "<option value='" + allPhotosGroups[n]["id"] + "'>";
                    }
                    tablePhoto += allPhotosGroups[n]["name"];
                    tablePhoto += "</option>";
                }
                tablePhoto += "<option value='0'>(!) Нет родителя</option>";
                tablePhoto += "</select>";
                tablePhoto += "</td>";
                tablePhoto += "<td><form action='process/gallery_a_name.php' method='post'><input type='text' maxlenght='25' name='gallery_name' /><input type='hidden' value='" + allPhotos[m]["id"] + "' name='galleryid' /><input type='submit' value='Изменить' /></form></td>";
                tablePhoto += "<td><input type='button' value='Удалить' onclick='SubmitGroupDelete(" + allPhotos[m]["id"] + ",\"gallery\")' />";
                tablePhoto += "<td>";
                if (allArticles[allPhotos[m]["artid"]]){
                    tablePhoto += allArticles[allPhotos[m]["artid"]];
                }
                else{
                    tablePhoto += "нет статьи";
                }
                tablePhoto += "</td>";
                tablePhoto += "</tr>";
                for (i=0;i<allPhotoCount;i++){
                    if (allPhoto[i]["parentid"] == allPhotos[m]["id"]){
                        tablePhoto += "<tr>";
                        tablePhoto += "<td class='adminMessage'>" + ChangeDate(allPhoto[i]["date"]) + "</td>";
                        tablePhoto += "<td><img src='photos_small/" + SelectPhoto(allPhoto[i]["name"]) + "' alt='" + allPhoto[i]["name"] + "' height='50px' onerror='ChangePhoto(this)' /></td>";
                        tablePhoto += "<td><form action='process/photos_a_name.php' method='post'><input type='text' maxlenght='25' name='photo_name' value='" + allPhoto[i]["description"] + "' /><input type='hidden' value='" + allPhoto[i]["id"] + "' name='photoid' /><input type='submit' value='Изменить' /></form></td>";
                        tablePhoto += "<td><input type='button' value='Удалить' onclick='PhotoDelete(\"" + allPhoto[i]["id"] + "\",\"" + allPhoto[i]["name"] + "\")' /></td>";
                        tablePhoto += "</tr>";
                    }
                }
            }
        }
    }
    else{
        var parentCheck;
        for (i=0;i<allPhotosCount;i++){
            parentCheck = false;
            for (m=0;m<allPhotosGroupsCount;m++){
                if(allPhotos[i]["parentid"] == allPhotosGroups[m]["id"]){
                    parentCheck = true;
                    
                }
            }
            if (!parentCheck){
                tablePhoto += "<tr>";
                tablePhoto += "<td>" + allPhotos[i]["name"] + "</td>";
                tablePhoto += "<td>";
                tablePhoto += "<select onchange='SubmitGroupOrder(this," + allPhotos[i]["id"] + ",\"gallery\",\"parent\")'>";
                tablePhoto += "<option value='0'>(!) Нет родителя</option>";
                for (n=0;n<allPhotosGroupsCount;n++){
                    tablePhoto += "<option value='" + allPhotosGroups[n]["id"] + "'>";
                    tablePhoto += allPhotosGroups[n]["name"];
                    tablePhoto += "</option>";
                }
                tablePhoto += "</select>";
                tablePhoto += "</td>";
                tablePhoto += "<td><form action='process/gallery_a_name.php' method='post'><input type='text' maxlenght='25' name='gallery_name' /><input type='hidden' value='" + allPhotos[i]["id"] + "' name='galleryid' /><input type='submit' value='Изменить' /></form></td>";
                tablePhoto += "<td><input type='button' value='Удалить' id='' /></td>";
                tablePhoto += "</tr>";
                for (k=0;k<allPhotoCount;k++){
                    if (allPhoto[k]["parentid"] == allPhotos[i]["id"]){
                        tablePhoto += "<tr>";
                        tablePhoto += "<td class='adminMessage'>" + ChangeDate(allPhoto[k]["date"]) + "</td>";
                        tablePhoto += "<td><img src='photos_small/" + SelectPhoto(allPhoto[k]["name"]) + "' alt='" + allPhoto[k]["name"] + "' height='50px' onerror='ChangePhoto(this)' /></td>";
                        tablePhoto += "<td><form action='process/photos_a_name.php' method='post'><input type='text' maxlenght='25' name='photo_name' value='" + allPhoto[k]["description"] + "' /><input type='hidden' value='" + allPhoto[k]["id"] + "' name='photoid' /><input type='submit' value='Изменить' /></form></td>";
                        tablePhoto += "<td><input type='button' value='Удалить' onclick='PhotoDelete(\"" + allPhoto[k]["id"] + "\",\"" + allPhoto[k]["name"] + "\")' /></td>";
                        tablePhoto += "</tr>";
                        
                    }
                }
            }
        }
    }

    tablePhoto += "</table>";
    
    $("#photos_cont").html(tablePhoto);
}

function ChangeDate(photoDate){
    var pattern = /(\d+)-(\d+)-(\d+)/;
    var arr=pattern.exec(photoDate)
    return arr[3] + "." + arr[2]+ "." + arr[1];
}

function SelectPhoto(photoName){
    var pattern = /(\S+).jpg/;
    var arr=pattern.exec(photoName);
    return arr[1] + "_small.jpg";
}

function ChangePhoto(target){
    var srcTarget = $(target).attr("src");
    srcTarget = srcTarget.replace(/_small/g,"");

    $(target).attr({ 
          src: srcTarget
        });
}

function AddArticle(){
    
    $(".article_text").each(function (i) {
        var article = $(this).val();
        article = article.replace(/openQuote/gi,"");
        article = article.replace(/endQuote/gi,"");
        article = article.replace(/"([а-яА-Яa-zA-Z]+)/gi,"openQuote$1");
        article = article.replace(/([а-яА-Яa-zA-Z]+)"/gi,"$1endQuote");
        
        if (article.search(/"/)!= -1){
            alert("Поздравляем! Вы мудила, который не умеет расставлять кавычки. Проверте, пожалуйста, не разделены ли кавычки от букв пробелами.");
            return false;
        }
        
        if (article.search(/openQuote/)== -1 || article.search(/endQuote/)== -1){
                if (article.search(/openQuote/)!= -1 || article.search(/endQuote/)!= -1){
                    alert("Поздравляем! Вы мудила, который не умеет расставлять кавычки. Проверте, пожалуйста, нет ли у Вас кавычек без пары.");
                    return false;
                }
        }
        
        if (article.search(/openQuote/)!= -1 && article.search(/endQuote/)!= -1){
            var openQuoteCount = article.match(/openQuote/gi).length;
            var endQuoteCount = article.match(/endQuote/gi).length;
        
            if (openQuoteCount != endQuoteCount){
                alert("Поздравляем! Вы мудила, который не умеет расставлять кавычки. Проверте, пожалуйста, нет ли у Вас кавычек без пары.");
                return false;
            }
        }
    
        article = article.replace(/openQuote(.+)openQuote/gi,"&laquo;$1&bdquo;");
        article = article.replace(/endQuote(.+)endQuote/gi,"&ldquo;$1&raquo;");
        article = article.replace(/openQuote(.+)endQuote/gi,"&laquo;$1&raquo;");
        article = article.replace(/endQuote(.+)openQuote/gi,"bdquo;$1&ldquo;");
    
        $(this).val(article);
    });
    $("#article_form").submit();
}

//Add link to news
function AddLink(targetClass){
    $("." + targetClass).each(function (i) {
       var newsHead = $(this).text().split(" ");
       var newsId = $(this).attr("newsid");
       var newsHeadLength = newsHead.length;
       if (newsHeadLength > 1 ){
            newsHead[newsHeadLength-2] = "<a href='news.php?id=" + newsId + "' class='linkCasual'>" + newsHead[newsHeadLength-2];
       }
       else{
            newsHead[newsHeadLength-1] = "<a href='news.php?id=" + newsId + "' class='linkCasual'>" + newsHead[newsHeadLength-1];
       }
       newsHead[newsHeadLength-2] = "<a href='' class='linkCasual'>" + newsHead[newsHeadLength-2];
       newsHead[newsHeadLength-1] = newsHead[newsHeadLength-1] + "</a>";
       $(this).html(newsHead.join(" "));
    });
}