;(function ($) {
    $.fn.bindImageLoad = function (callback) {
        function isImageLoaded(img) {
            // Во время события load IE и другие браузеры правильно
            // определяют состояние картинки через атрибут complete.
            // Исключение составляют Gecko-based браузеры.
            if (!img.complete) {
                return false;
            }
            // Тем не менее, у них есть два очень полезных свойства: naturalWidth и naturalHeight.
            // Они дают истинный размер изображения. Если какртинка еще не загрузилась,
            // то они должны быть равны нулю.
            if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
                return false;
            }
            // Картинка загружена.
            return true;
        }

        return this.each(function () {
            var ele = $(this);
            if (ele.is("img") && $.isFunction(callback)) {
                ele.one("load", callback);
                if (isImageLoaded(this)) {
                    ele.trigger("load");
                }
            }
        });
    };
})(jQuery);




/**
 * @author Vlad Yakovlev (red.scorpix@gmail.com)
 * @link www.scorpix.ru
 * @requires jQuery
 * @requires jCommon
 * @version 0.1.1
 * @date 2010-02-24
 */

function mainPicture(m, i) {
    /*
    var 
        m   = $q('.main:first .picture');
        i   = $q('.main:first .picture img');
    */
        
        if(m && i){
            m_s = m.width()*m.height(),
            i_s = i.width()*i.height();
            //i.css('visibility','hidden');
            var pr = $q('<div class="ipreload"></div>');
            //$q('.main:first .picture').append(pr);
            iii = new Image();
            $q(iii).load(function(){
                if(i.length > 0){ 
                    i.removeAttr('style');
                    i.css({'width': null, 'height': null});    
                    if(zoomed === true){
                        sizePropt(i,m);
                    }   
                    if(m_s > i_s || zoomed === false){
                        var edge = resizeRatio(m,i);
                        resizeBy(m,i,edge);
                        i.css({'cursor': 'default'});    
                    }
                    var predel = [(m.width()-i.width()), (m.height()-i.height()), 0, 0];
                    i.draggable({
                        containment: predel,
                        disabled: !zoomed 
                    });
                }
                //$q('.main:first .picture .ipreload').remove();
                //$q('.main:first .picture img').css('visibility','visible'); 
                   
            }).attr('src',i.attr('src'));
        }
        
        
}

function sizePropt(i,m){
    if(i.width() < m.width()){
        i.width('100%');
        return false;
    }
    if(i.height() < m.height()){
        i.height('100%');
        return false;
    }    
}

function resizeRatio(m,i){
        var
            m_w = m.width(),
            m_h = m.height(),
            i_w = i.width(),
            i_h = i.height();
        
        w1 = m_w;
        h1 = i_h*m_w/i_w;
        s1 = w1*h1;
        
        w2 = i_w*m_h/i_h;
        h2 = m_h;
        s2 = w2*h2;
        
        if(s1 > s2){
            return 'width';
        }else{
            return 'height';
        }
    }
    
function resizeBy(m,i,e){
        i.removeAttr('style');
        i.css({'width': null, 'height': null});
        switch(e){
            case 'width':
                i.removeAttr('style').width(m.width());
                if(i.attr('rel') === undefined){
                    var top = Math.round((i.height() - m.height())/2);
                    i.css({
                        'left':'0px',
                        //'top':'-'+top+'px'
                        'top':'0px'
                    });
                }else{
                    eval(i.attr('rel'));
                    if(window['style']){
                        i.css(style);    
                    }
                }
            break;
            case 'height':
                i.removeAttr('style').height(m.height());
                if(i.attr('rel') === undefined){
                    var left = Math.round((i.width() - m.width())/2);
                    i.css({
                        'left':'-'+left+'px',
                        'top':'0px'
                    });
                }else{
                    eval(i.attr('rel'));
                    if(window['style']){
                        i.css(style);    
                    }
                }
            break;
        }    
    }
    

function line(rootEl) {
	rootEl = $q(rootEl).first();

	var coords = rootEl.text().split(',');
	rootEl.text('');

	if (coords) {
		var
			width = Math.abs(coords[0] - coords[4]),
			height = Math.abs(coords[1] - coords[5]);

		if ($c.support.svg) {
			createSvg(coords, width, height);
			rootEl.css('display', 'block');
		} else if ($c.support.vml) {
			createVml(coords, width, height);
			rootEl.css('display', 'block');
		}
	}

	function createSvg(coords, width, height) {

		rootEl.css({
			'width': width,
			'height': height
		});

		var svgEl = $c.svg('svg')
			.svgAttr({
				viewBox: [0, 0, width, height].join(' ')
			})
			.svgCss({
				width: width,
				height: height
			})
			.appendTo(rootEl);
		var pathEl = $c.svg('path')
			.svgAttr({
				d: 'M ' + coords[0] + ',' + coords[1] + ' S ' + coords[2] + ',' + coords[3] + ' ' + coords[4] + ',' + coords[5],
				stroke: '#fff',
				strokeWidth: 1,
				fill: 'none',
				opacity: 0.5
			})
			.appendTo(svgEl);
	}

	function createVml(coords, width, height) {
		var vmlEl = $q(document.createElement('v:shape')).attr({
			'coordsize': width + ' ' + height,
			'path': 'm ' + coords[0] + ',' + coords[1] + ' c ' + coords[2] + ',' + coords[3] + ' ' + coords[4] + ',' + coords[5] + ' ' + coords[4] + ',' + coords[5],
			'filled': 'false'
		}).css({
			'width': width,
			'height': height
		}).appendTo(rootEl);
		$q(document.createElement('v:stroke')).attr({
			'opacity': 0.5,
			'color': '#fff'
		}).appendTo(vmlEl);
	}
};

var zoomed = false;
$q(document).ready(function(){ 
    $q('.zoom').live('click',function(){
        $q(this).find('a').toggleClass('in');
        zoomed = !zoomed;
        mainPicture($q('.main:first .picture'), $q('.main:first .picture img')); 
        return false;
    });

    
    var rtime = new Date(1, 1, 2000, 12,00,00);
    var timeout = false;
    var delta = 100;
    function resizeend() {
        if (new Date() - rtime < delta) {
            setTimeout(resizeend, delta);
        } else {
            timeout = false;
            mainPicture($q('.main:first .picture'), $q('.main:first .picture img'));
        }
    }
    
    $q(window).resize(function(){
        rtime = new Date();
        if (timeout === false) {
            timeout = true;
            setTimeout(resizeend, delta);
        }
    });
    
    $q('.main:first .picture img').bindImageLoad(function(){
        mainPicture($q('.main:first .picture'), $q('.main:first .picture img'));
    });
    mainPicture($q('.main:first .picture'), $q('.main:first .picture img'));  
    $q('.main_content .notice .line').each(function() {
		line(this);
	});
    
    
    
});

