var TINY={};

function T$(i){return document.getElementById(i);}

TINY.box=function(){
    var p,m,b,fn,ic,iu,iw,ih,ia,f=0;
    return{
        show:function(c,u,w,h,a,t){
            if(!f){
                p=document.createElement('div'); p.id='tinybox';
                m=document.createElement('div'); m.id='tinymask';
                b=document.createElement('div'); b.id='tinycontent';
                document.body.appendChild(m); document.body.appendChild(p); p.appendChild(b);
                m.onclick=TINY.box.hide; window.onresize=TINY.box.resize; f=1
            }
            if(!a&&!u){
                p.style.width=w?w+'px':'auto'; p.style.height=h?h+'px':'auto';
                p.style.backgroundImage='none'; b.innerHTML=c;
            }else{
                b.style.display='none'; p.style.width=p.style.height='100px'
            }
            this.mask();
            ic=c; iu=u; iw=w; ih=h; ia=a; this.alpha(m,1,80,3);
            if(t){setTimeout(function(){TINY.box.hide()},1000*t)}
        },
        fill:function(c,u,w,h,a){
            if(u){
                p.style.backgroundImage='';
                var x=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject('Microsoft.XMLHTTP');
                x.onreadystatechange=function(){
                    if(x.readyState==4&&x.status==200){TINY.box.psh(x.responseText,w,h,a)}
                };
                x.open('GET',c,1); x.send(null)
            }else{
                this.psh(c,w,h,a)
            }
        },
        psh:function(c,w,h,a){
            if(a){
                if(!w||!h){
                    var x=p.style.width, y=p.style.height; b.innerHTML=c;
                    p.style.width=w?w+'px':''; p.style.height=h?h+'px':'';
                    b.style.display='';
                    w=parseInt(b.offsetWidth); h=parseInt(b.offsetHeight);
                    b.style.display='none'; p.style.width=x; p.style.height=y;
                }else{
                    b.innerHTML=c
                }
                this.size(p,w,h)
            }else{
                p.style.backgroundImage='none'
            }
        },
        hide:function(){
            TINY.box.alpha(p,-1,0,3)
        },
        resize:function(){
            TINY.box.pos(); TINY.box.mask()
        },
        mask:function(){
            m.style.height=TINY.page.total(1)+'px';
            m.style.width=''; m.style.width=TINY.page.total(0)+'px'
        },
        pos:function(){
            var t=(TINY.page.height()/2)-(p.offsetHeight/2); t=t<10?10:t;
            p.style.top=(t+TINY.page.top())+'px';
            p.style.left=(TINY.page.width()/2)-(p.offsetWidth/2)+'px'
        },
        alpha:function(e,d,a){
            clearInterval(e.ai);
            if(d==1){
                e.style.opacity=0; e.style.filter='alpha(opacity=0)';
                e.style.display='block'; this.pos()
            }
            e.ai=setInterval(function(){TINY.box.ta(e,a,d)},20)
        },
        ta:function(e,a,d){
            var o=Math.round(e.style.opacity*100);
            if(o==a){
                clearInterval(e.ai);
                if(d==-1){
                    e.style.display='none';
                    e==p?TINY.box.alpha(m,-1,0,2):b.innerHTML=p.style.backgroundImage=''
                }else{
                    e==m?this.alpha(p,1,100):TINY.box.fill(ic,iu,iw,ih,ia)
                }
            }else{
                var n=Math.ceil((o+((a-o)*.5))); n=n==1?0:n;
                e.style.opacity=n/100; e.style.filter='alpha(opacity='+n+')'
            }
        },
        size:function(e,w,h){
            e=typeof e=='object'?e:T$(e); clearInterval(e.si);
            var ow=e.offsetWidth, oh=e.offsetHeight,
            wo=ow-parseInt(e.style.width), ho=oh-parseInt(e.style.height);
            var wd=ow-wo>w?0:1, hd=(oh-ho>h)?0:1;
            e.si=setInterval(function(){TINY.box.ts(e,w,wo,wd,h,ho,hd)},20)
        },
        ts:function(e,w,wo,wd,h,ho,hd){
            var ow=e.offsetWidth-wo, oh=e.offsetHeight-ho;
            if(ow==w&&oh==h){
                clearInterval(e.si); p.style.backgroundImage='none'; b.style.display='block';
            }else{
                if(ow!=w){var n=ow+((w-ow)*.5); e.style.width=wd?Math.ceil(n)+'px':Math.floor(n)+'px'}
                if(oh!=h){var n=oh+((h-oh)*.5); e.style.height=hd?Math.ceil(n)+'px':Math.floor(n)+'px'}
                this.pos()
            }
        }
    }
}();

TINY.page=function(){
    return{
        top:function(){return document.documentElement.scrollTop||document.body.scrollTop},
        width:function(){return self.innerWidth||document.documentElement.clientWidth||document.body.clientWidth},
        height:function(){return self.innerHeight||document.documentElement.clientHeight||document.body.clientHeight},
        total:function(d){
            var b=document.body, e=document.documentElement;
            return d?Math.max(Math.max(b.scrollHeight,e.scrollHeight),Math.max(b.clientHeight,e.clientHeight)):
            Math.max(Math.max(b.scrollWidth,e.scrollWidth),Math.max(b.clientWidth,e.clientWidth))
        }
    }
}();

jQuery(document).ready(function(){
/*    $('#click_buttom').click(function(){alert(1)
       if($('NAME').val().replace(/^\s+/, '') != '')
       {
            $('#add_new_albom').css('display','none');
       } 
    });
*/  
    $('.photo_event img').mouseover(function(){
        $(this).parent().next().css({'color':'#000000','border-color':'#DE1C24'});
        $(this).parent().next().find('a').css({'color':'#000000'});
    });
    $('.photo_event img').mouseout(function(){
        $(this).parent().next().css({'color':'#BEBEBE','border-color':'#F5F5F5'});
        $(this).parent().next().find('a').css({'color':'#BEBEBE'});
    });
    
    $('.event_definition img').mouseover(function(){
        $(this).parent().parent().next().find('div').eq(0).css({'color':'#000000','border-color':'#DE1C24'});
        $(this).parent().parent().next().find('div').eq(0).find('a').css({'color':'#000000'});
    });
    $('.event_definition img').mouseout(function(){
        $(this).parent().parent().next().find('div').eq(0).css({'color':'#BEBEBE','border-color':'#F5F5F5'});
        $(this).parent().parent().next().find('div').eq(0).find('a').css({'color':'#BEBEBE'});
    });
     
    
    
    
    $('.link').mouseover(function(){
        $(this).find('a').css('color','#000000');
    });
    $('.link').mouseout(function(){
        $(this).find('a').css('color','#bebebe');
    });
    
    $('.not_empty').click(function(){
        $('.show_all').css('display','block');
    });
    
    $('#ajax_news_block img').mouseover(function(){
        $(this).parent().next().css({'color':'#000000','border-color':'#DE1C24'});
        $(this).parent().next().find('a').css({'color':'#000000'});
    });
    $('#ajax_news_block img').mouseout(function(){
        $(this).parent().next().css({'color':'#BEBEBE','border-color':'#F5F5F5'});
        $(this).parent().next().find('a').css({'color':'#BEBEBE'});
    });
    
    $('.banner_block').mouseover(function(){
        $(this).next().find('div').eq(0).css({'color':'#000000','border-color':'#DE1C24'});
        $(this).next().find('div').eq(0).find('a').css({'color':'#000000'});
    });
    $('.banner_block').mouseout(function(){
        $(this).next().find('div').eq(0).css({'color':'#BEBEBE','border-color':'#F5F5F5'});
        $(this).next().find('div').eq(0).find('a').css({'color':'#BEBEBE'});
    });
    
    $('.report_list li a').mouseover(function(){
        $(this).next().css({'color':'#000000','border-color':'#DE1C24'});
        $(this).next().find('a').css({'color':'#000000'});
    });
    $('.report_list li a').mouseout(function(){
        $(this).next().css({'color':'#BEBEBE','border-color':'#F5F5F5'});
        $(this).next().find('a').css({'color':'#BEBEBE'});
    });
    
    
    $('.statistica').hover(function () {
            $('#popup_statistica').css({'display':'block','border':'2px solid lightgrey', 'border-radius':'3px 3px 3px 3px', 'margin-top':'-47px', 'padding':'0px 9px'});
        }, function () {
            $('#popup_statistica').css({'display': 'none','border':'2px solid lightgrey', 'border-radius':'3px 3px 3px 3px', 'margin-top':'-47px', 'padding':'0px 9px'});
        }
    );

    
    $('.get_link').hover(function () {
            $('#popup_get_link').css('display', 'block');
        }, function () {
            $('#popup_get_link').css('display', 'none');
        }
    );
    
    $(".main_menu li").hover(function(){
        $(this).find("ul").css("display","block")
    },
    function(){
        $(this).find("ul").css("display","none")
    })

    $(".comments_block input").focus(function(){
        if ($(this).attr("value")==$(this).attr("title"))
            $(this).attr("value"," ")
    })


    $(".comments_block input").blur(function(){
        if ($(this).attr("value")==" ")
            $(this).attr("value",$(this).attr("title"))
    })



    $(".comments_block textarea").focus(function(){
        if ($(this).attr("value")==$(this).attr("title"))
            $(this).attr("value"," ")
    })


    $(".comments_block textarea").blur(function(){
        if ($(this).attr("value")==" ")
            $(this).attr("value",$(this).attr("title"))
    }) 
    
    $('.wrap_img').mouseover(function(){
        $(this).prev().css({
            'border-bottom':'7px solid #ed1c24',
            'margin':'0 0 10px',
            'zoom':'1',
            'color':'#000',
            'position':'relative'
        });
        $(this).prev().find('a').css({
            'color':'#000'
        });
    });
    $('.wrap_img').mouseout(function(){
        $(this).prev().css({
            'border-bottom':'7px solid #f5f5f5',
            'margin':'0 0 10px',
            'zoom':'1',
            'color':'#bebebe',
            'position':'relative'
        });
        $(this).prev().find('a').css({
            'color':'#bebebe'
        });
    });

/*
       $(".news_block .nav .next").bind("click",function(){
    		if($(".news_block #current_page").length)
    			var current_page = parseInt($(".news_block #current_page").attr("value"));
    		else return false;
    		ajaxGetNewsByPage(current_page+1);
    	})

        $(".news_block .nav .prev").bind("click",function(){
    		if($(".news_block #current_page").length)
    			var current_page = parseInt($(".news_block #current_page").attr("value"));
    		else return false;
    		ajaxGetNewsByPage(current_page-1);
    	})
*/
    $('input.event_checkbox[type=checkbox] + label.active').css('background-position', '0px 0');
    $('input.event_checkbox[type=checkbox] + label').click(function(){
        $(this).toggleClass("active");
        $('input.event_checkbox[type=checkbox] + label').css('background-position', '-56px 0');
        $('input.event_checkbox[type=checkbox] + label.active').css('background-position', '0px 0');
    });

})

function ajaxGetNewsByPage(page)
{
	if(parseInt(page) <= 0) return;
	$.post("/ajax/fotose_release_4/main_news_block.php",{"PAGEN_1":page},function(data){
		if(data.length>0)
			$("#ajax_news_block").fadeOut(500,function(){
				$("#ajax_news_block").html(data);
				$("#ajax_news_block").fadeIn(500);
			});
	},"html");
}

function ajaxGetReportsByPage(page)
{
	if(parseInt(page) <= 0) return;
	$.post("/ajax/fotose_release_4/main_reports_block.php",{"PAGEN_1":page},function(data){
		if(data.length>0)
			$("#ajax_reports_block").fadeOut(500,function(){
				$("#ajax_reports_block").html(data);
				$("#ajax_reports_block").fadeIn(500);
			});
	},"html");
}

function ajaxGetContestsByPage(page)
{
	if(parseInt(page) <= 0) return;
	$.post("/ajax/fotose_release_4/main_contests_block.php",{"PAGEN_1":page},function(data){
		if(data.length>0)
			$("#ajax_contests_block").fadeOut(500,function(){
				$("#ajax_contests_block").html(data);
				$("#ajax_contests_block").fadeIn(500);
			});
	},"html");
}


function openInNewWindow(href, mode) {        
    var url;
    switch (mode){
        case 'twitter':
            url = 'http://twitter.com/share?';
        break;
        case 'facebook':
            url = 'http://www.facebook.com/share.php?u=';
        break;
        case 'livejournal':
            url = 'http://www.livejournal.com/update.bml?subject='
        break;
        case 'googlebuzz':
            url = 'http://www.google.com/reader/link?url=';
        break;
        case 'vkontakte':
            url = 'http://vkontakte.ru/share.php?url=';
        break;
        case 'linkedin':
            url = 'http://www.linkedin.com/shareArticle?mini=true&url=';
        break;
    }    

    var newWindow = window.open(url+href, '_blank');
    newWindow.focus();
    return false;
}

function headerUserCreateEvent(link) {
	$("#user_create_popup").css('display', 'none');
	ShowPopUp(link);
	$("#add_news_ex_ajax").html('');
	ajax_update("#add_news_ex_ajax", "/ajax/fotose_release_4/add_event_form.php", "");
	return false;
}

var marker = null;
var ObjMap;
var IsSetMark = false;
var X = 50.45648229878545;
var Y = 30.54410276412966;
var Z = 9;
var begin_pos = new google.maps.LatLng(X, Y);
var begin_zoom = Z;
var lastPosition = null;
function GoogleInitialize(id, x, y, z) {
    if (!!x && !!y && !!z) {
        X = x;
        Y = y;
        Z = z;
        begin_pos = new google.maps.LatLng(X, Y);
        begin_zoom = Z;
        IsSetMark = true;
    }
    
    var mapOptions = {
        zoom: begin_zoom,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: begin_pos
    };

    ObjMap = new google.maps.Map(document.getElementById(id), mapOptions);

    if (!!IsSetMark) {
        marker = new google.maps.Marker({
            position: begin_pos,
            map: ObjMap,
            draggable:false,
            animation: google.maps.Animation.DROP
        }); 
    }

    google.maps.event.addListener(ObjMap, 'click', function(params) {
        lastPosition = params.latLng;
        if (!marker) {    
            marker = new google.maps.Marker({
                position: params.latLng,
                map: ObjMap,
                draggable:false,
                animation: google.maps.Animation.DROP
            }); 
        } else {
            marker.setPosition(params.latLng);
        }

        params = new Object();
        params["x"] = lastPosition.lat();
        params["y"] = lastPosition.lng();
        params["z"] = ObjMap.zoom;
        $('#GOOGLE_MAP_POSITION').val('X='+params.x+';Y='+params.y+';Z='+params.z);
    });  
}


function headerUserCreateReport(link) {
    $("#user_create_popup").css('display', 'none');
    ShowPopUp(link);
    $("#add_news_ex_ajax").html('');
    ajax_update("#add_news_ex_ajax", "/ajax/fotose_release_4/add_report_form.php", "", 
        function(){GoogleInitialize('map_canvas_ajax');}// запускаем google maps
    );
    return false;
}


function headerUserCreateArticle(link) {
    $("#user_create_popup").css('display', 'none');
    ShowPopUp(link);
    $("#add_news_ex_ajax").html('');
    ajax_update("#add_news_ex_ajax", "/ajax/fotose_release_4/add_article_form.php", "");
    return false;
}

function UserEditArticle(link, id) {
    ShowPopUp(link);
    $("#add_news_ex_ajax").html('');
    ajax_update("#add_news_ex_ajax", "/ajax/fotose_release_4/add_article_form.php?id="+id, "");
    return false;
}

function send_mark(id, mark, is_competition, comp_id){
    
    if(parseInt(mark) <= 0 || parseInt(id) <= 0) return;
             
    $.post("/ajax/fotose_release_4/photo_mark.php",{"ID": id, "VOTE": mark, "IS_COMP": is_competition, "COMP_VAL": comp_id},function(data){
        
        if(data.status == "yes"){
            
            if(!is_competition){

            	$("#rate_avg").html(data["rate_avg"]);
            	$("#vote_count").html(data["vote_count"]);
            	$("#rate_sum").html(data["vote_sum"]);
            	$("#sum_mark span").html(data["vote_sum"]);
                
            }
            $("#marks").html(data.message);
            
        }
        else{
            $("#marks").html(data.message);
        }
        
    },"json");
    
}

// для работы с JCrop
function updateCoords(c, code, jcrop_api) {
    var BigImg = document.getElementById('PICTURES_'+code+'_CROP_PIC');
    var intBigImgWidth = $(BigImg).attr('real_width');
    var intBigImgHeight = $(BigImg).attr('real_height');
    
    var intSmallImgWidth = jcrop_api.ui.holder.width();
    var intSmallImgHeight = jcrop_api.ui.holder.height();

    var Ratio = 1;
    if (intBigImgWidth > intBigImgHeight) { // чтоб точнее было...
        Ratio = (intBigImgWidth * 1) / (intSmallImgWidth * 1);
    } else {
        Ratio = (intBigImgHeight * 1) / (intSmallImgHeight * 1);
    }
    $('#'+code+'_x').val(c.x * Ratio);
    $('#'+code+'_y').val(c.y * Ratio);
    $('#'+code+'_w').val(c.w * Ratio);
    $('#'+code+'_h').val(c.h * Ratio);
    if (parseInt(c.w) > 0) {
        var rx = $('#'+code+'_IBLOCK_WIDTH').val() / c.w;
        var ry = $('#'+code+'_IBLOCK_HEIGHT').val() / c.h;

        var bounds = jcrop_api.getBounds();
        boundx = bounds[0];
        boundy = bounds[1];

        $('#PICTURES_'+code+'_CROP_PIC').css({
            width: Math.round(rx * boundx) + 'px',
            height: Math.round(ry * boundy) + 'px',
            marginLeft: '-' + Math.round(rx * c.x) + 'px',
            marginTop: '-' + Math.round(ry * c.y) + 'px'
        });
    }
    $('#'+code+'_get_crop_image').css('display', 'block');

}

function ShowImagePopUp(strImagePath) {
    var intMaxWidth = $(window).width()-100;
    var intMaxHeight = $(window).height()-100;

    var objNewImage = new Image();
    objNewImage.src = strImagePath; 
    //objNewImage.onload = function() {
        var intImageWidth = objNewImage.width;
        var intImageHeight = objNewImage.height;
        var Ratio = 1;
        if (intImageWidth > intMaxWidth) {
            var Ratio = intMaxWidth / intImageWidth;
            intImageWidth = intImageWidth * Ratio;
            intImageHeight = intImageHeight * Ratio;
        }
        if (intImageHeight > intMaxHeight) {
            var Ratio = intMaxHeight / intImageHeight;
            intImageWidth = intImageWidth * Ratio;
            intImageHeight = intImageHeight * Ratio;
        }
        
        var strImgText = "<button onclick='TINY.box.hide()' class='button' style='display: block;height: 23px;margin-left: auto;padding-bottom: 4px;position: absolute;right: 0;text-align: center;top: -30px;width: 99px;'><span class=\"bg\"><span class=\"l\"></span><span class=\"r\"></span><span class=\"icon\"></span><span class=\"text\">Закрыть</span></span></button><img src='"+strImagePath+"' alt='' width='" + intImageWidth + "' height='" + intImageHeight + "'/>";
        TINY.box.show(strImgText,0,0,0,1);
        //$("#tinymask").css({"position":"absolute","background-color":"gray", "top":"0"});
        $("#tinybox").css({"position":"absolute","z-index":99999});
    //}
    return false;
}

function UploadComplite(code, data) {
    if (data.length <= 0) {
        alert(
            "Ошибка загрузки файла!"+
            "\n"+                                     
            "Вы можете загрузить только файлы изображения"+
            "\n"+                                     
            "Размер файла не должен привышать 5 mb"+
            "\n"+                                     
            "Допустимые разрешения gif, jpg, png, ..."
        );
    }
    var uploadBox = $('#PICTURES_'+code+'_FULL');
    var previewBox = $('#PICTURES_'+code+'_CROP');
    var arData = data.split('|');
    uploadBox.html('');
    uploadBox.append('<input type="hidden" name="'+code+'_ajax_upload_image_id" id="'+code+'_ajax_upload_image_id" value="'+arData[0]+'">');
    uploadBox.append('<input type="hidden" name="'+code+'_ajax_upload_image_path" id="'+code+'_ajax_upload_image_path" value="'+arData[1]+'">');
    uploadBox.append('<input type="hidden" name="'+code+'_ajax_upload_image_id_big" id="'+code+'_ajax_upload_image_id_big" value="'+arData[2]+'">');
    uploadBox.append('<input type="hidden" name="'+code+'_ajax_upload_image_path_big" id="'+code+'_ajax_upload_image_path_big" value="'+arData[3]+'">');
    if ($('#'+code+'_cropbox').length > 0) {
        $('#'+code+'_cropbox').remove();
    }
    uploadBox.append('<img id="'+code+'_cropbox" src="'+arData[1]+'">');
    if ($('#PICTURES_'+code+'_CROP_PIC').length > 0) {
        $('#PICTURES_'+code+'_CROP_PIC').remove();
    }
    previewBox.append('<img id="PICTURES_'+code+'_CROP_PIC" src="'+arData[3]+'">');
    var BigImg = document.getElementById('PICTURES_'+code+'_CROP_PIC'); 
    $("<img/>") // Make in memory copy of image to avoid css issues
        .attr("src", $(BigImg).attr("src"))
        .load(function() {
            intBigImgWidth = this.width;   // Note: $(this).width() will not
            intBigImgHeight = this.height; // work for in memory images.
            $(BigImg).attr('real_width', intBigImgWidth);
            $(BigImg).attr('real_height', intBigImgHeight);
            bindCrop(code, data);
    });
    
    
}

function bindCrop(code, data) {
    $('#'+code+'_cropbox').Jcrop({
        aspectRatio: $('#'+code+'_IBLOCK_ASPECT_RATIO').val(),
        onSelect: function(c) { //updateCoords(c, code, data); 
            updateCoords(c, code, jcrop_api); 
        },
        onChange: function(c) {
            updateCoords(c, code, jcrop_api); 
        }
    }, function (){
        var i = 0;
        jcrop_api = this;
        var Photo = $('#'+code+'_cropbox');
        jcrop_api.setSelect([0, 0, Photo.width(), Photo.height()]);
        jcrop_api.animateTo([0, 0, Photo.width(), Photo.height()]);
        var c = jcrop_api.tellSelect();
        updateCoords(c, code, jcrop_api);
    });
}


function CustomAjaxNewsList(pagen_n,page,id){
    
    if(parseInt(page)<0)     return;
    
    var url = "/ajax/fotose_release_4/news_list.php";
    var div = $("#this_ganre_div");
        
    $.post(url,{"PAGEN_1":page,"element_id": id},function(data){
        $("#this_ganre_div").html(data);
    },"html");
    
}

function GetCropImage(code)
{
    $('#'+code+'_get_crop_image').css('display', 'none');
    params = new Object();
    params['x'] = $('#'+code+'_x').val();
    params['y'] = $('#'+code+'_y').val();
    params['w'] = $('#'+code+'_w').val();
    params['h'] = $('#'+code+'_h').val();
    params['id'] = $('#'+code+'_ajax_upload_image_id_big').val();
    params['path'] = $('#'+code+'_ajax_upload_image_path_big').val();
    params['iblock_width'] = $('#'+code+'_IBLOCK_WIDTH').val();
    params['iblock_height'] = $('#'+code+'_IBLOCK_HEIGHT').val();

    $.ajax({  
        type: "POST",
        url: '/ajax/fotose_release_4/ajax.crop.image.php',
        data: params,
        error: function (){
            alert('Ошибка соединения');
        },
        success: function(data) {
            $('#PICTURES_'+code+'_FULL').html('');
            $('#'+code+'_RESULT_IMAGE_PATH').val(data);
            var width = $('#PICTURES_PREVIEW_PICTURE_FULL').width();
            var height = $('#PICTURES_PREVIEW_PICTURE_FULL').height();
            $('#PICTURES_'+code+'_FULL').append('<img src="'+data+'" style="max-width: '+width+'px; max-height: '+height+'px;">');
        }
    }); 
};

function UploadSubmit(code) {
    var uploadBox = $('#PICTURES_'+code+'_FULL');
    $('#'+code+'_get_crop_image').css('display', 'none');
    uploadBox.html('Загрузка файла'); 
}

