﻿function past_special( u ) {
    u = u.replace( /add-loc=loc/g, 'add-loc=' + encodeURIComponent( window.location.href ) );
    return u;
}

function get_opt_param( s, key, suf, def ) {
    var r = s.split( key + '=' );
    if( r.length > 1 ) {r = r[1].split( '&' );r = r[0] + suf;}else {r = def;}
    return r;
}

function findPos( obj ){
        if( !obj ) obj = document.getElementById( obj );
        if( !obj ) return [0,0];
	var curleft=0;
	var curtop=0;
	if(obj.offsetParent){
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while(obj = obj.offsetParent){
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [parseInt(curleft,10),parseInt(curtop,10)];
}

function get_kstr( n ){
    var s = 'abcdefghijklmnopqrstuvwxyz1234567890ABSDEFGHIJKLMNOPQRSTUVWXYZ';
    var r = '';
    for( var i = 0; i < n; i++ ) r += s.charAt( parseInt( Math.random() * ( s.length - 1 ), 10 ) );
    return r;
}

function simple_center_div(id){
    var sx = parseInt( document.body.clientWidth, 10 );
    var sy = parseInt( (document.documentElement.clientHeight && document.compatMode=='CSS1Compat' && !window.opera) ? document.documentElement.clientHeight : document.body.clientHeight, 10 );
    var ox = $( document ).scrollLeft();
    var oy = $( document ).scrollTop();
    var dx = $( document ).width();
    var dy = $( document ).height();
    var ax = $( id ).width();
    var ay = $( id ).height();

    var x = ox + sx / 2 - ax / 2;
    if ( x < 0 ) x = 0;
    if ( x + ax > dx ) x = dx - ax - 10;

    var y = oy + sy / 2 - ay / 2;
    if ( y < 10 ) y = 10;
    if ( y + ay > dy ) y = dy - ay - 10;

    $( id ).css( 'top', y + 'px');
    $( id ).css( 'left', x + 'px' );
}
//clone of modal_screen() from ajaxdialog.js
function simple_modal_screen() {
    $( '<div id="simple_modal_body"><div id="simple_modal_block"></div></div>' ).appendTo( 'body' );
    $( "#simple_modal_block" ).click( function () {
//        var o = document.getElementById( "simple_box" );
//        if( o ) o.focus();
//        var o = $("#simple_box_content input");
//        if( o && o[0] ) {o[0].focus();}
        close_simple_box();
        return false;
    } );
    simple_modal_resize();
}
//clone of modal_resize() from ajaxdialog.js
function simple_modal_resize() {
    if ( $( '#simple_modal_block' ).css( 'display' ) != 'block' ) return false;
    simple_center_div( '#simple_box' );
    $( '#simple_modal_block' ).css( 'width', $( document ).width() );
    $( '#simple_modal_block' ).css( 'height', $( document ).height() );
    /*IE7 problem with this:
    document.body.style.overflowX = "hidden";
    */
}

function show_simple_box( x, y, width, height ) {
    if(!width){
        width=$( document ).width();
        $( '#simple_box' ).css( 'text-align', 'center' );
    }
    width = parseInt( width, 10 );
	height = parseInt( height, 10 );
//    if( size < 300 ) {size = 300;}
    //$( '#simple_box' ).css( 'top', y + 'px');
    //$( '#simple_box' ).css( 'left', x + 'px' );
    $( '#simple_box' ).css( 'width', width + 'px' );
	if(height) $( '#simple_box' ).css( 'height', height + 'px' );
	
    // show;
    simple_modal_screen();
    $( '#simple_box,#simple_modal_body' ).show();

    // focus;
//    var o = document.getElementById( "simple_box" );
//    if( o ) {o.focus();}
//    var o = $("#simple_box_content input");
//    if( o && o[0] ) {o[0].focus();}
}

function save_cache( inner, holder ) {
    if ( holder != '' ) {
        $( '#' + holder ).remove();
        $( '<div id="' + holder + '" style="display:none;"></div>' ).appendTo( 'body' );
        var o = document.getElementById( holder );
        if ( o ) {o.innerHTML = escape(inner);}
    }
}

function load_cache( holder ) {
    if ( holder != '' ) {
        var a = document.getElementById( holder );
        var o = $( '<div id="simple_box_content"></div>' ).appendTo( document.getElementById('simple_box') );
        if( o && a ) {o.html(unescape(a.innerHTML));}
    }
}

function close_simple_box() {
    $( '#simple_box,#simple_modal_body' ).hide();
    document.body.style.overflowX = '';
    $( '#simple_box,#simple_modal_body' ).remove();
}

$(function(){
    $( ".simplebox" ).unbind( 'click' );

    var imgArr=[];
    $( ".simplebox" ).each(function(){
        var index=-1;
	for(var i=0; i<imgArr.length; i++){
            if(imgArr[i].href==this.href){
                index=i;
                break;
            }
        }
	if(index<0){
		imgArr.push(this);
		index=imgArr.length-1;
	}
	$(this).click( function () {
        var url = this.href.split( '#' );
        url = past_special( url[ 1 ] );
        var objPos = findPos( this );
		var imglink="";
		var single=false;
		var noclose=false;

		if($(this).hasClass("imglink")){
			if($(this).hasClass("single")) single=true;
			if($(this).hasClass("noclose")) noclose=true;

			imglink=url;
			var content="<a href='#' onclick='close_simple_box();return false;'><img src='"+url+"' id='simple_content_img' border='0' /></a>";
			if(!noclose) content+="<a href='#' onclick='close_simple_box();return false;' class='cls'>Закрыть</a>";
			content+="<div class='png dsp_n' id='simplebox_larr'></div>";
			content+="<div class='png dsp_n' id='simplebox_rarr'></div>";
		}
		else {
			var ido = get_opt_param( url, 'id', '', '' );
			var id = this.id || ido;

			var size = get_opt_param( url, 'width', '', 0 );
			var holder = get_opt_param( url, 'holder', '', '' );
		}

		$( '#simple_box,#_modal_body' ).remove();
		var simple_box = $( '<div id="simple_box" style="display:none"></div>' ).appendTo( 'body' );

		simple_box.keydown( function( event ) {
			if ( event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) {
				close_simple_box();
				event.preventDefault();
			}
		});

        var c = holder && document.getElementById( holder );
        if(content){
            var o = $( '<div id="simple_box_content"></div>' ).appendTo( document.getElementById('simple_box') );
			if(imglink){
                var o0=objPos[0];
                var o1=objPos[1];
                var img=new Image();
                img.src=imglink;
				var onImgReady=function(image){
					o.html(content);
					show_simple_box( o0, o1, image.width, image.height);
					$("#simplebox_larr").css("top", (image.height/2)-17).ifixpng().click(
						function(){
							close_simple_box();
							if(index==0) $(imgArr[imgArr.length-1]).trigger("click");
							else $(imgArr[index-1]).trigger("click");
						}
					);
					$("#simplebox_rarr").css("top", (image.height/2)-17).ifixpng().click(
						function(){
							close_simple_box();
							if(index==imgArr.length-1) $(imgArr[0]).trigger("click");
							else $(imgArr[index+1]).trigger("click");
						}
					);
					simple_box.hover(function(){
						if(imgArr.length>1 && !single) $("#simplebox_larr, #simplebox_rarr").removeClass("dsp_n");
					},
					function(){
						if(imgArr.length>1 && !single) $("#simplebox_larr, #simplebox_rarr").addClass("dsp_n");
					});
				};
				if(img.complete || img.readyState===4){
					onImgReady(img);
				}
				else {
					img.onload=function(){
						onImgReady(img);
					};
				}
            }
            else {
                o.html(content);
                show_simple_box( objPos[0], objPos[1], size );
            }
		}
        else if ( c ) {
            load_cache(holder);
            show_simple_box( objPos[0], objPos[1], size );
        } else {
            var simple_box_content = $( '<div id="simple_box_content"></div>' ).appendTo( simple_box );
            simple_box_content.html( '<center><br/><img src="/images/indicator.gif"/></center>' );
            show_simple_box( objPos[0], objPos[1], size );
            if( url.indexOf( '?' ) != -1 ) url += '&'; else url += '?';
            url += 'kstr=' + get_kstr( 64 );
            simple_box_content.load( url, {},
                function ( responseText, textStatus, XMLHttpRequest ) {
                    var o = document.getElementById( "simple_box_content" );
                    var inner = o ? o.innerHTML : '';
                    if ( holder ){
                        save_cache( inner, holder );
                    }
                    show_simple_box( objPos[0], objPos[1], size );
                }
            );
        }
        return false;
    });
  });
});
