var favicon = {
    // -- "PUBLIC" ----------------------------------------------------------------
    defaultPause: 2000,
    change: function(iconURL, optionalDocTitle) {
        clearTimeout(this.loopTimer);
        if (optionalDocTitle) {
            document.title = optionalDocTitle;
        }
        this.addLink(iconURL, true);
    },
    animate: function(iconSequence, optionalDelay) {
        this.preloadIcons(iconSequence);
        this.iconSequence = iconSequence;
        this.sequencePause = (optionalDelay) ?  optionalDelay : this.defaultPause;
        favicon.index = 0;
        favicon.change(iconSequence[0]);
        this.loopTimer = setInterval(function() {
            favicon.index = (favicon.index+1) % favicon.iconSequence.length;
            favicon.addLink(favicon.iconSequence[favicon.index], false);
        }, favicon.sequencePause);
    },
    // -- "PRIVATE" ---------------------------------------------------------------
    loopTimer: null,
    preloadIcons: function(iconSequence) {
        var dummyImageForPreloading = document.createElement("img");
        for (var i=0; i<iconSequence.length; i++) {
            dummyImageForPreloading.src = iconSequence[i];
        }
    },
    addLink: function(iconURL) {
        var link = document.createElement("link");
        link.type = "image/x-icon";
        link.rel = "shortcut icon";
        link.href = iconURL;
        this.removeLinkIfExists();
        this.docHead.appendChild(link);
    },
    removeLinkIfExists: function() {
        var links = this.docHead.getElementsByTagName("link");
        for (var i=0; i<links.length; i++) {
            var link = links[i];
            if (link.type=="image/x-icon" && link.rel=="shortcut icon") {
                this.docHead.removeChild(link);
                return; // Assuming only one match at most.
            }
        }
    },
    docHead:document.getElementsByTagName("head")[0]
}

// Define logo constants
LOGO = { w: 235, h: 72 }
// Define bg constants
PICTURE = { w: 960, h: 600}
// Define constants
var win, blockWrap, blockHead, blockMenu, blockLogo, blockFooter, blockContent, blockPortfolio, blockCarusel, selectTeam, propMenu, scrollBlock, caruselBlock;
var tHeight = 115, pWidth = 960, pHeight = 585, pcWidth = 330, isOpen = false;

// Define window params
function Window(){
    var max = 1400,
        min = 1280;
    
    this.constant = 1.6;
    
    this.w = $(window).width();
    this.h = $(window).height();
    
    this.ratio = function(){ return this.w/this.h };
    this.scale = function(){ return (this.w > max || this.w < min) ? this.w/min : 1; }
};

// Define blocks
function Block(id){
	this.id = id;
	this.w = $('#' + this.id).width();
	this.h = $('#' + this.id).height();
	this.set = function(width, height, left, top){
		$('#' + this.id).css({
			'width': width,
			'height': height,
			'left': left,
			'top': top,
			'margin': 0 
		});
	}
};

// Define menu & lang params
function Menu(id, k, width){

    var size = 41.61,       // textsize ul li
        sizeSub = 18,       // textsize ul li ul li
        height = 52,        // height ul li
        heightSub = 26,     // height ul li ul li
        padding = 8,        
        paddingSub = 4,        
        //right = 79,       // lang space
        right = 0,         
        arrowWidth = 19,    
        arrowHeight = 19,   
        langWidth = 58;     
    
    var menu = $('#' + id),
        submenu = menu.find('.submenu'),
        lang = menu.next();
        
    this.left = 350;
    this.width = 9999;
    
    // menu
    menu.css({
        'font-size': size * k
    });
    // menu li
    menu.find('li')
        .css({
            'padding': '0 ' + padding * k + 'px',
            'height': height * k 
        });
    // menu li a
    menu.find('li')
        .find('a')
        .css({
            'position':'relative',
            'top': Math.floor( ( ( height - size ) * k)/2 )
        });
    if (!($.browser.msie && $.browser.version < 9)){
        menu.find('li a').addClass('opacity');
    }
    // submenu
    submenu.css({
        'width': width - ( this.left + right ) * k,
        'top': height * k,
        'height': 'auto'
    });
    // submenu li
    submenu.find('li')
           .css({
                'font-size':sizeSub * k,
                'padding': paddingSub * k + 'px ' + padding * k + 'px',
                'height': sizeSub * k,
                'line-height':'1%'
            });
        if (submenu.find('li').hasClass('back')){
            submenu.find('li.back')
                   .css({
                        'padding': paddingSub * k + 'px ' + padding * k + 'px ' + paddingSub * k + 'px 0' + 10 * k + 'px',
                        'margin-left': -5
                    });
            submenu.find('li.back')
                   .find('img')
                   .css({
                        'width': 7 * k,
                        'height': 10 * k,
                        'margin-right':  7 * k
                   });
        }
    // submenu li a
    submenu.find('li')
           .find('a')
           .css({
                'position':'relative',
                top:0
            });
    // submenu li span
    submenu.find('li')
           .find('span')
           .css({
                'width': arrowWidth * k,
                'height': arrowHeight * k,
                'bottom': -( arrowHeight * k ),
                'margin-left': -(arrowWidth * k)/2
            });
    // lang
    /*lang.css({
			'width': langWidth * k,
			//'height': heightSub * k - Math.floor( ( ( heightSub - sizeSub) * k )/2 ),
			'font-size':sizeSub * k,
            'padding': paddingSub * k + 'px ' + padding * k + 'px',
            'height': sizeSub * k,
            'line-height':'70%',
            'top': $('#' + id).find('li').innerHeight()
		});*/
    Cufon.replace('#menu li, #lang', { hover: true });
}

// Define team selection
function Team(id, k){
    var posLeftTop,
        posRightBottom,
        selectWidth,
        selectHeight;
        
    var member = $('#' + id).find('div.member');
    
    member.each(function(i){
        posLeftTop = $(this).attr("pos_lt").split(', ');
        posRightBottom = $(this).attr("pos_rb").split(', ');
        selectWidth = posRightBottom[0] - posLeftTop[0];
        selectHeight = posRightBottom[1] - posLeftTop[1];
        $(this).css({
            'left': posLeftTop[0]*k,
            'top': posLeftTop[1]*k,
            'width': selectWidth*k,
            'height': selectHeight*k
        });
    });
}

function Carusel(id){

    var elemWidth = 145,
        elemPadding = 30,
		rememberPos;
    
    var self = this,
        carusel = $('#' + this.id);
    
    this.id = id;
    this.stop = [false, false];
    this.elem = $('#' + this.id).find('li');
    this.prev = $('#' + this.id).find('a.prev');
    this.next = $('#' + this.id).find('a.next');
    this.count = this.elem.length;
    this.frameWidth = $('#' + this.id).width();
    this.caruselWidth = this.count*elemWidth + elemPadding;
    
    this.setCarusel = function(n){
		
        if (n > 0){
            this.elem.removeClass('last').css('padding-right','10px');
			this.frameWidth = $('#' + this.id).width();
            this.caruselWidth = n*elemWidth + elemPadding;
            $('#' + this.id).find('li.active').eq(n - 1).addClass('last').css('padding-right',0);
            $('#' + this.id).find('ul').width(this.caruselWidth);

			rememberPos = parseInt($('#' + this.id).find('ul').css("left"));
			
			if (this.caruselWidth < this.frameWidth) {
                this.prev.hide();
                this.next.hide();
            } else {
                ( rememberPos < 0 ) ? this.prev.show() : this.prev.hide();
				if ( rememberPos <= this.frameWidth - this.caruselWidth ){
					this.next.hide();
					$('#' + this.id).find('ul').css('left', this.frameWidth - this.caruselWidth);
				} else {
					this.next.show();
				}
            }
        }
        
        this.elem.each(function(i){
            if ($(this).next().length == 0)
                $(this).css('padding-right', 0);
        });
		
		this.getFrameWidth = function(){
			this.frameWidth = $('#' + this.id).width();
			return this.frameWidth;
		}
		this.getWidth = function(){
			this.caruselWidth = n*elemWidth + elemPadding;
			return this.caruselWidth;
		}
		this.getCount = function(){
			return this.count;
		}
		
    }

}

// Define functions
initAll = function(){
	Cufon.replace('h2, div.navigation span.page', { fontFamily: 'hcr' }, { hover: true });
	Cufon.replace('#menu a, #lang, h1, .wt, #content .blog_list p.title, div.navigation span.page strong', { fontFamily: 'HeliosCond' }, { hover: true });

    var self, page, bgColor = ['#eeeeee', 'none'];

        $('#content .navigation a.next, #content .navigation a.prev').hover(function(){
            self = $(this);
            page = self.parent().find('span.page');
            (!self.hasClass('na'))? page.css('background', bgColor[0]) : page.css('background', bgColor[1]);
        }, function(){
            $(this).parent().find('span.page').css('background', bgColor[1]);
        });       
}

initMemberTooltip = function(){
	var member = $('#team div.member'),
        memberContent = [],
		memberTooltipLeftPos = [],
		memberTooltipTopPos = [],
		memberLeftPos = [],
		memberTopPos = [],
		mainWrapWidth = $('#main_wrap').width();
        
        member.each(function(i){
            memberContent[i] = $(this).find('div.text').html();
			memberLeftPos[i] = $(this).offset().left;
			memberTopPos[i] = $(this).offset().top;
			memberTooltipLeftPos[i] = memberLeftPos[i] + parseInt($(this).width()/2 - 120);
			memberTooltipTopPos[i] = memberTopPos[i] + $(this).height() - 5;
        });
	
		$('div.tm').remove();
		
        member.wTooltip({
            className: 'tm',
            callBefore: function() { 
                var iMember;
				var tm = $('div.tm');
                member.live('mouseover', function(){
					iMember = member.index(this);
						tm.show();
						if (memberTooltipLeftPos[iMember] < 0){
							tm.css({
								'left':0,
								'top':memberTooltipTopPos[iMember]
							}).html(memberContent[iMember]);
							tm.find('span.arr').css({
								'margin-left': (memberTooltipLeftPos[iMember] - 9 > -111) ? memberTooltipLeftPos[iMember] - 9 : -111
							});
						}
						if (memberTooltipLeftPos[iMember] > 0) {
							tm.css({
								'left':memberTooltipLeftPos[iMember],
								'top':memberTooltipTopPos[iMember]
							}).html(memberContent[iMember]);
						}
						if ( memberTooltipLeftPos[iMember] + 222 > mainWrapWidth){
							tm.css({
								'left':mainWrapWidth - 222,
								'top':memberTooltipTopPos[iMember]
							}).html(memberContent[iMember]);
							tm.find('span.arr').css({
								'left':0,
								'margin-left': (memberLeftPos[iMember] - mainWrapWidth + 222 + ($(this).width())/2 - 9 < 200) ? memberLeftPos[iMember] - mainWrapWidth + 222 + ($(this).width())/2 - 9 : 200
							});
						}
						Cufon.replace('div.tm p.name, div.tm h1', { fontFamily: 'HeliosCond' }, { hover: true });
				});
				tm.mouseover(function(){
					$(this).show();
				});
				member.mouseout(function(){
					tm.hide();
				})
            },
            track: false
        });
}

initMenu = function(){
	$('#menu li:has(ul li.active)').addClass('active');
	$('.submenu').not('.submenu:has(li.active)').hide();
    $('#menu li.active .submenu').show();
}

initProduction = function(){
    var self;
	$('#footer a.production').hover(function(){
        self = $(this);
		self.find('img.s').hide();
		self.find('img.b').show();
		self.find('span.icon').stop().animate({'width':90, 'height': 90, 'margin-top': -44}, 150);
	}, function(){
        self = $(this);
		self.find('span.icon').stop().animate({'width':13, 'height': 13, 'margin-top': 10}, 150, function(){
			self.find('img.b').hide();
			self.find('img.s').show();
		});
	});
}

initBlog = function(){

    function Blog(id){
        this.id = id;
        
        var el = $('div.' + this.id),
            post = el.find('div.blog_list_item'),
            post_with_video = el.find('div.blog_list_item.one'),
            post_title = post.find('p.title'),
            post_preview = post.find('div.preview'),
            post_info = post.find('div.info'),
            post_more_info = post_info.find('div.more'),
            post_more_links = post_info.find('div.links'),
            post_more_links_cover = post_more_links.find('a.cover'),
            post_more_links_social = post_more_links.find('div.social'),
            post_video = post_more_info.find('iframe'),
            post_count = post.length,
            video = [],
            video_el = [],
            video_src = [],
            video_youtube_id = [],
            video_wrap,
            preview = [],
            opened_state = [],
            post_index,
            
            pane = $('#content').find('div.scrolled'),
            pane_settings = { showArrows: true },
            api,
            
            wrapVideos = function(){
                post_video.wrap('<div class="video"></div>');
                video_wrap = post_more_info.find('div.video');
            },
            
            isOpen = function(n){
                opened_state[n] = (opened_state[n]) ? false : true
            },
        
            getVideo = function(from){
                wrapVideos();
                from.each(function(i){
                    if ($(this).find('div.video').length != 0){
                        video_el[i] = $(this).find('div.video').find('iframe');
                        video_src[i] = video_el[i].attr('src');
                        video_youtube_id[i] = video_src[i].substr(video_src[i].indexOf('/embed/') + '/embed/'.length, 11);
                        // Old insert of youtube video (for jscrollpane)
                        video[i] = '<object width="' + video_el[i].attr('width') + '" height="' + video_el[i].attr('height') + '" wmode="transparent">' +
                            '<param name="movie" value="http://www.youtube.com/v/' + video_youtube_id[i] + '?version=3&amp;hl=ru_RU"></param>' +
                            '<param name="allowFullScreen" value="true"></param>' +
                            '<param name="allowscriptaccess" value="always"></param>' +
                            '<param name="wmode" value="transparent"></param>' +
                            '<embed src="http://www.youtube.com/v/' + video_youtube_id[i] + '?version=3&amp;hl=ru_RU" type="application/x-shockwave-flash" width="' + video_el[i].attr('width') + '" height="' + video_el[i].attr('height') + '" allowscriptaccess="always" allowfullscreen="true"></embed>' +
                        '</object>';
                    } else {
                        video[i] = 'Not found';
                    }
                });
                video_wrap.remove();
            }(post),    //iframes (<iframe ... > ... </iframe>)
            
            getPreview = function(from){
                from.find('div.preview').each(function(i){
                    preview[i] = ($(this).html() != '') ? $(this).html() : 'Not found';
                });
            }(post),    //images (<img ... >)
            
            replaceElems = function(n){
                if(opened_state[n]){
                    post_preview.eq(n).html(video[n]);
                } else {
                    post_preview.eq(n).html(preview[n]);
                }
            },
            
            slideMoreInfo = function(n){
                api = pane.data('jsp');
                if(opened_state[n]){
                    post_more_info.eq(n).slideToggle(150, function(){
						slideSocialLinks(n);
                        coverTextToggle(n);
						pane.jScrollPane(pane_settings);
					});
                } else {
                    post_more_info.eq(n).slideToggle(150, function(){
                        slideSocialLinks(n);
                        coverTextToggle(n);
                        pane.jScrollPane(pane_settings);
                        
                    });
                }
                if (n == 0)
                    api.scrollTo(0, 0);
                else 
                    api.scrollToElement(post.eq(n), true);

            },
            
            slideSocialLinks = function(n){
                post_more_links_social.eq(n).toggle();
            },
            
            coverTextToggle = function(n){
                post_more_links_cover.eq(n).html( (post_more_links_cover.eq(n).html() == 'Развернуть') ? 'Свернуть' : 'Развернуть' ).toggleClass('active');
            },
            
            postToggle = function(elem){
                elem.bind('click', function(){
                
                    /*if ($(this).hasClass('preview') && !$(this).parent().hasClass('one'))
                        return false;*/
                    
                    post_index = elem.index(this);
                    isOpen(post_index);
                    if ($(this).parents('div.blog_list_item').hasClass('one')) {
                        // video replace
                        replaceElems(post_index);
                    }
                    slideMoreInfo(post_index);
                    return false;
                });
            };
            
            
            // Default: closed all posts
            for (var i = 0; i < post_count; i++)
                opened_state[i] = false;
            
            post_preview.bind('click', function(){
                if (!$(this).parents('div.blog_list_item').hasClass('one'))
                    return false;
            });
            
            postToggle(post_title);
            postToggle(post_more_links_cover);
            postToggle(post_preview);
            
    }
    
    if ($('.blog_list').length != 0){
        blog = new Blog('.blog_list');
    }
    
}

var pos;

initCarusel = function(){
	
	var change = null,
        timer = null;
		thumbIndex = 0,
		stop = [false, false];
	
    // Carusel
	var caruselBlock = new Carusel('carusel');
	
    var caruselElem = caruselBlock.elem,
		filterBlock = $('#' + caruselBlock.id).find('.filter_block'),
		filterElem = filterBlock.find('a'),
		type = '#';
    
    // Show/hide arrows, set width, left position
    caruselBlock.setCarusel(caruselBlock.count);
    
    /*
     * CARUSEL move left/right
     */
	var moveSpeed = ($.browser.msie && $.browser.version == 8) ? 15 : 15,
	deltaMove = ($.browser.msie && $.browser.version == 8) ? 15 : 5,
	caruselUlElem = $('#' + caruselBlock.id).find('ul');
	
	pos = parseInt(caruselUlElem.css("left"));
	
	function moveRight(){
        pos += deltaMove;
		if (pos >= 0) {
			pos = 0;
            stop[0] = true;
            stop[1] = false;
            caruselBlock.prev.hide();
        }
		caruselUlElem.css({'left':pos}); 
    }
    function moveLeft(){
        pos -= deltaMove;
        if (pos <= caruselBlock.getFrameWidth() - caruselBlock.getWidth()) {
			pos = caruselBlock.getFrameWidth() - caruselBlock.getWidth();
            stop[0] = false;
            stop[1] = true;
            caruselBlock.next.hide();
        }
		caruselUlElem.css({'left':pos}); 
    }
	
	if (change) clearInterval(change);
	
    caruselBlock.next.mouseover(function(){
        caruselBlock.prev.show();
        stop[1] = false;
        (!stop[1]) ? change = setInterval(moveLeft, moveSpeed) : clearInterval(change);
    });
    caruselBlock.prev.mouseover(function(){
        caruselBlock.next.show();
        stop1 = false;
        (!stop[0]) ? change = setInterval(moveRight, moveSpeed) : clearInterval(change);
    });
    $('#' + caruselBlock.id).find('a.arr').mouseout(function(){ clearInterval(change); stop[0] = false;stop[1] = false;});
	caruselBlock.next.click(function(){ return false; });
	caruselBlock.prev.click(function(){ return false; });
    
    /*
     * CARUSEL filter
     */
    filterElem.each(function(i){
        if ($(this).hasClass('active'))
            type = $(this).attr('href'); 
    });
    function filterSel(t){
        var type = t;
        var n = 0;
        if (type != '#'){
            caruselElem.removeClass('active');
            caruselElem.hide().each(function(i){
                if ($(this).attr('data-worktype') == type) {
                    n++;
                    $(this).fadeIn().addClass('active');
                }
            });
        } else { 
            caruselElem.fadeIn().addClass('active');
            n = caruselElem.length;
        }
        if (n > 0){
            if (!isOpen){
                var bg = $('#' + caruselBlock.id).find('li.active').eq(0).find('a').attr('rel');
                    $('#bg').attr('src', bg);
            }
            caruselBlock.setCarusel(n);
        }
    }
    filterElem.click(function(){
        var self = $(this);
        if (!self.hasClass('active')){
            var type = self.attr('href');
                filterElem.removeClass('active');
                self.addClass('active');
                filterSel(type);
				pos = 0;
				$('#carusel').find('ul').css({'left':pos}); 
				$('#carusel').find('a.prev').hide();
        }
        return false;
    });
    //
    
    /*
     * CARUSEL background
     */
	$('<img id="bg_after" src="/media/images/blank.gif">').insertAfter("#bg");
	$('<div id="preloadImagesCarusel">').insertAfter("#bg_after").hide();
	for (var s = 0; s < caruselBlock.count; $('#preloadImagesCarusel').append('<img src="'+ caruselElem.find('a').eq(s).attr('rel') +'" />'), s++)
		
	caruselElem.find('a').bind('mouseenter mouseover', function(){
		if (!isOpen){
			if (timer){ clearTimeout(timer); }
			var self = $(this);
			function h() {
				var rel = self.attr('rel');
				var src = $('#bg').attr('src');
				$('#bg_after').css('opacity', 0).bind('load', function(){
					$(this).stop().animate({'opacity': 1}, 270, function(){
						$('#bg').attr('src', rel);
					});
				}).attr('src', rel);
			}
			timer = setTimeout(h, 300);
		}
	});
	caruselElem.find('a').mouseleave(function(){
		if (timer){ 
			clearTimeout(timer); 
		}
	});
	
	/*
     * CARUSEL POP-UP
     */
	caruselElem.find('a').click(function(){
		thumbIndex = caruselElem.find('a').index(this);
		isOpen = true;
		var i = caruselElem.find('a').index(this);
		var link = $(this).attr('href');
        var location = window.location + '#' + link;
            
            window.location = location;
            
			$('#overlay').show();
			if ($.browser.msie && $.browser.version < 9){
				$('#carusel').hide();
				$('#portfolio').show();
			} else{
				$('#carusel').animate({'opacity':0}, 300, function(){
					$(this).hide();
					$('#portfolio').show();
				});
			}

			if (link != ""){
			var thisEl = $(this);
				$.ajax({
					url: link,
					cache: true,
					success: function(html){
						$("#portfolio").html(html);
						defineLinks(thisEl);
                        if ($("#portfolio").find('div.preview ul li').length < 2) $("#portfolio").find('div.info div.navigation').hide();
						viewport();
						//initPortfolio();
					}
				});
			}
		return false;
	});

    /*
     * CARUSEL tooltip
     */
	caruselElem.find('a').wTooltip({
		className: 'wt',
		callBefore: function() { 
            var wt = $(".wt");
			caruselElem.find('a').bind('mouseover mousemove',function(){
				var i = caruselElem.find('a').index(this);
				if ($(this).offset().left + wt.innerWidth() > $(window).width()){
					wt.show().css({
						'position':'absolute',
						'left':$(window).width() - wt.innerWidth(),
						'top':$(this).offset().top - 46
					});
                    $(".wt span").css({
						'left':$(this).offset().left - $(window).width() + wt.innerWidth() + $(this).innerWidth()/2 - 18
					});
                    $(this).offset().left
				}
                else if($(this).offset().left < 0){
                    wt.show().css({
						'position':'absolute',
						'left':0,
						'top':$(this).offset().top - 46
					});
                    $(".wt span").css({
						'left':($(this).innerWidth()/2 + $(this).offset().left - 18 < 0) ? 0 : $(this).innerWidth()/2 + $(this).offset().left - 18
					});
                } else {
					wt.show().css({
						'position':'absolute',
						'left':$(this).offset().left,
						'top':$(this).offset().top - 46
					}); 
				}
				
				if (wt.width() < 125){
					wt.css({
						'left':$(this).offset().left + (145 - wt.width())/2 - 20
					});
					$(".wt span").css({
						'left':'50%',
						'margin-left':'-9px'
					});
					
				}
			});
			caruselElem.find('a').bind('mousemove', function(){
				return false;
			});
		},
		track: false
	});
}

/*
 *		PORTFOLIO
 */
initPortfolio = function(){
	if ($('#portfolio div.case').length != 0){
		$('#portfolio div.case_item div.preview li').eq(0).addClass('actv');
		$('#portfolio .navigation a.next, #portfolio .navigation a.prev').hover(function(){
			if (!$(this).hasClass('na')){
				$(this).parent().find('span.page').css('background','url(/media/images/arr_n_left_h.png) 100% 0');
			} else {
				$(this).parent().find('span.page').css('background','none');
			}
		}, function(){
			$(this).parent().find('span.page').css('background','none');
		});
		$('#portfolio img.close').css('opacity', 0.5);
		$('#portfolio img.close').hover(function(){
			$(this).css('opacity', 1);
		}, function(){
			$(this).css('opacity', 0.5);
		});
		$('.wp').remove();
		initPortfolioArr();
		initVideoAutoplayPortfolio();
		Cufon.replace('div.navigation span.page', { fontFamily: 'hcr' }, { hover: true });
		Cufon.replace('h1, div.navigation span.page strong', { fontFamily: 'HeliosCond' }, { hover: true });
		initPortfolioMedia();
	}
}

/*
    Autoplay Youtube video in Cases
*/
initVideoAutoplayPortfolio = function(){
    var initVideoAutoplayPortfolioSetDefaults = true,   // set default params in portfolio video iframe (src)
        videoParamSrc = [],                                // set all as in HTML (iframe src)
        videoParamAutoplayDisabledSrc = [],                // set all videos to autoplay=0 (iframe src)
        videoParamAutoplay = [];
        
        var liVideo = $('#portfolio div.case_item div.preview li.video'),
            videoCurrent;
			
			if (liVideo.length == 0) return;
            
            if (initVideoAutoplayPortfolioSetDefaults){
                liVideo.each(function(i){
                    videoParamSrc.push($(this).find('iframe').attr('src'));
                });
                for ( var j = 0; j < videoParamSrc.length; j++){
                    if (videoParamSrc[j].indexOf('autoplay=')>=0) {
                        if (videoParamSrc[j].indexOf('autoplay=0')>=0)
                            videoParamAutoplayDisabledSrc[j] = videoParamSrc[j];
                        if (videoParamSrc[j].indexOf('autoplay=1')>=0)
                            videoParamAutoplayDisabledSrc[j] = videoParamSrc[j].replace('autoplay=1', 'autoplay=0');
                        videoParamAutoplay[j] = true;
                    } else {
                        videoParamAutoplayDisabledSrc[j] = videoParamSrc[j] + '&autoplay=0';
                        videoParamAutoplay[j] = false;
                    }
                }
                initVideoAutoplayPortfolioSetDefaults = false;
            }

            liVideo.each(function(i){
                if ($(this).hasClass('actv'))
                    videoCurrent = i;
            });
            
            liVideo.find('iframe').each(function(g){
                if ( g != videoCurrent)
                    $(this).attr('src', videoParamAutoplayDisabledSrc[g]);   
            });
            
            if (videoParamAutoplay[videoCurrent]){
                liVideo.eq(videoCurrent).find('iframe').attr('src', videoParamSrc[videoCurrent]);
            }
}
/**/

$('#portfolio div.case_item div.navigation a').live('click', function(){

	if ($(this).hasClass('na')) return false;

    var portfolioPreviewElem = $('#portfolio div.case_item div.preview li'),
        n = portfolioPreviewElem.size(),
        caseCurrPage = $('#portfolio div.case_item div.navigation span.page strong'),
        casePrevPage = $('#portfolio div.case_item div.navigation a.prev'),
        caseNextPage = $('#portfolio div.case_item div.navigation a.next'),
        casePageBlock = $('#portfolio div.case_item div.navigation span.page'),
        i = parseInt(caseCurrPage.html()) || parseInt(caseCurrPage.find('cufontext').html());
		
        i = i - 1;
        
		if (n > 1){
			if (!$(this).hasClass('na')){
				if ($(this).hasClass('prev')) i--;
				if ($(this).hasClass('next')) i++;
			}
			if (i == 0) {
				casePrevPage.addClass('na');
				caseNextPage.removeClass('na');
				casePageBlock.css('background', 'none');
			} else {
				if (i == n - 1) {
					casePrevPage.removeClass('na');
					caseNextPage.addClass('na');
					casePageBlock.css('background', 'none');
				} else {
					casePrevPage.removeClass('na');
					caseNextPage.removeClass('na');
				}
			}
            
			portfolioPreviewElem.hide().removeClass('actv');
			portfolioPreviewElem.eq(i).show().addClass('actv');
			
			caseCurrPage.html(i + 1);
            
			Cufon.replace('div.navigation span.page', { fontFamily: 'hcr' }, { hover: true });
			Cufon.replace('div.navigation span.page strong', { fontFamily: 'HeliosCond' }, { hover: true });
		}
        
        initVideoAutoplayPortfolio();
        
	return false;
});
$('#portfolio a.case_nav').live('click', function(){
	var link = $(this).attr('href');
	if (link != ""){
		$.ajax({
			url: link,
			cache: true,
			success: function(html){
				$("#portfolio").html(html);
                if ($("#portfolio").find('div.preview ul li').length < 2) $("#portfolio").find('div.info div.navigation').hide();
				viewport();
				var thisId = $('#portfolio .case').attr('id');
				var thisEl = $('#carusel a.' + thisId);
					defineLinks(thisEl);
					initPortfolio();
					(function h() {
						$('#bg_after').remove();
						$('<img id="bg_after" src="/media/images/blank.gif">').insertAfter("#bg");
						var rel = $('#carusel a.' + thisId).attr('rel');
						var src = $('#bg').attr('src');
						$('#bg_after').css('opacity', 0).bind('load', function(){
							$(this).stop().animate({'opacity': 1}, 270, function(){
								$('#bg').attr('src', rel);
							});
						}).attr('src', rel);
					})();
			}
		});
	}
	return false;
});
$('#portfolio img.close').live('click', function(){
	isOpen = false;
	$('#portfolio').html('');
	$('#overlay').hide();
	if ($.browser.msie && $.browser.version < 9){
		$('#carusel').show();
	} else{
		$('#carusel').show().animate({'opacity':1}, 300);
	}
    clearHash();
});

initPortfolioArr = function(){
	$('#next_link, #prev_link').wTooltip({
		className: 'wp',
		callBefore: function() { 
			$('#next_link').bind('mousemove',function(){
				$(".wp").hide();
				if ($(this).hasClass('active')){
					$(".wp").html($(this).attr('title')).hide();
					Cufon.replace('.wp', { fontFamily: 'HeliosCond' }, { hover: true });
					$(".wp").css({
						'position':'absolute',
						'left':$(this).offset().left - $(".wp").innerWidth(),
						'top':$(this).offset().top
					}).show();
				} else {
					$(".wp").hide();
					return false;
				}
			});
			$('#prev_link').bind('mousemove',function(){
				$(".wp").hide();
				if ($(this).hasClass('active')){
					$(".wp").html($(this).attr('title')).hide();
					Cufon.replace('.wp', { fontFamily: 'HeliosCond' }, { hover: true });
					$(".wp").css({
						'position':'absolute',
						'left':$(this).offset().left + 30,
						'top':$(this).offset().top
					}).show();
				} else {
					$(".wp").hide();
					return false;
				}
			});
			$('#next_link, #prev_link').mouseout(function(){
				$(".wp").hide();
			});
		},
		track: false
	});
}
/*
 *		END PORTFOLIO
 */

var pw, ph;
function viewport(){
    // Window params
    win =            new Window();
    // Define blocks (id)
    blockWrap =      new Block('main'),
    blockHead =      new Block('header'),
    blockMenu =      new Block('menu'),
    blockLogo =      new Block('logo'),
    blockFooter =    new Block('footer'),
    blockContent =   new Block('content'),
    blockPortfolio = new Block('portfolio'),
    blockCarusel =   new Block('carusel'),
    // Define menu params (id, k, width)
    propMenu =       new Menu('menu', win.scale(), win.w);

	ph = (win.h*0.91 - tHeight*win.scale() > pHeight) ? pHeight : win.h*0.91 - tHeight*win.scale();
	pw = win.w*0.8;
		
	if ( win.ratio() >= win.constant ){
		blockWrap.set( win.w, win.w/win.constant, 0, (win.h - win.w/win.constant)/2 );
		blockHead.set( win.w, tHeight*win.scale(), 0, -(win.h - win.w/win.constant)/2 );
		blockFooter.set( win.w, 35, 0, win.h - (win.h - win.w/win.constant)/2 - 35 );
		blockContent.set( blockContent.w, Math.round(win.h - 45 - tHeight*win.scale()), (win.w - blockContent.w)/2, tHeight*win.scale() - (win.h - win.w/win.constant)/2 );
		// portfolio
		( (win.w/win.constant - ph)/2 > tHeight*win.scale() - (win.h - win.w/win.constant)/2 ) ?  blockPortfolio.set( pw, ph, (win.w - pw)/2,  (win.w/win.constant - ph)/2 ) :  blockPortfolio.set( pw, ph, (win.w - pw)/2,  tHeight*win.scale() - (win.h - win.w/win.constant)/2 );
		// carusel
		( $('#' + blockCarusel.id).hasClass('filter') ) ?  blockCarusel.set(win.w, 90, 0, win.h - (win.h - win.w/win.constant)/2 - 200) : blockCarusel.set(win.w, 90, 0, win.h - (win.h - win.w/win.constant)/2 - 165);
		
		// Define team (id, k)
		selectTeam =     new Team('team', win.w/PICTURE.w);
		
	} else {
		blockWrap.set( win.h*win.constant, win.h, (win.w - win.h*win.constant)/2, 0 );
		blockHead.set( win.w, tHeight*win.scale(), -(win.w - win.h*win.constant)/2, 0 );
		blockFooter.set( win.w, 35, -(win.w - win.h*win.constant)/2, win.h - 35 );
		blockContent.set( blockContent.w, Math.round(win.h - 45 - tHeight*win.scale()), -(win.w - win.h*win.constant)/2 + (win.w - blockContent.w)/2, tHeight*win.scale() );
		// portfolio
		( (win.h - ph)/2 > tHeight*win.scale() ) ?  blockPortfolio.set( pw, ph, -(win.w - win.h*win.constant)/2 + (win.w - pw)/2, (win.h - ph)/2 ) :  blockPortfolio.set( pw, ph, -(win.w - win.h*win.constant)/2 + (win.w - pw)/2, tHeight*win.scale() );
		// carusel
		( $('#' + blockCarusel.id).hasClass('filter') ) ? blockCarusel.set( win.w, 90, -(win.w - win.h*win.constant)/2, win.h - 200 ) : blockCarusel.set( win.w, 90, -(win.w - win.h*win.constant)/2, win.h - 165 );
		
		// Define team (id, k)
		selectTeam =     new Team('team', win.h*win.constant/PICTURE.w);
	}
	
	scrollBlock = $('#' + blockContent.id).find('div.scrolled');
	scrollBlock.height(Math.round(win.h - 45 - tHeight*win.scale()))
			   .jScrollPane({ showArrows: true });

	//blockMenu.set(propMenu.width, blockMenu.h*win.scale(), propMenu.left*win.scale(), 0);
	blockMenu.set(propMenu.width, tHeight*win.scale(), propMenu.left*win.scale(), 0);
	blockLogo.set(LOGO.w*win.scale(), LOGO.h*win.scale(), (propMenu.left*win.scale() - LOGO.w*win.scale())/2, 0);

	initPortfolioMedia();
	initPortfolio();
}

initPortfolioMedia = function(){
	// portfolio images
	if ($('#portfolio').find('.preview li img.img').size() != 0){
		
		var src = [],
			w = [],
			h = [],
			k = [];
			
		$('.loadedImg').remove();
		$('#portfolio').find('.img').each(function(i){
				src[i] = $(this).attr('src');
				w[i] = $(this).attr('width');
				h[i] = $(this).attr('height');
				k[i] = w[i]/h[i];					
				if (w[i] > h[i]){ w[i] = pw; h[i] = w[i]/k[i] } else { h[i] = ph; w[i] = k[i]*h[i] }
				if (w[i] > pw - pcWidth){ w[i] = pw - pcWidth; h[i] = w[i]/k[i]; }
				if (h[i] > ph){ h[i] = ph; w[i] = h[i]*k[i]; }
				$('#portfolio').find('.preview li img.img').eq(i).css({
					'width':w[i], 
					'height':h[i],
					'top': (ph - h[i])/2,
				});			
		});
		
	}
	// portfolio video
	if ($('#portfolio').find('.preview li.video').size() != 0){
		var vW = [];
		var vH = [];
		var vK = []
		var $this;
		$('.loadedVideo').remove();
		$('#portfolio').find('.preview li.video').each(function(i){
			$('body').append('<div class="loadedVideo"></div>');
			var video = $('.loadedVideo');
			var $this = $('#portfolio').find('.preview li.video').eq(i).find('iframe');
				vW[i] = $this.attr('width');
				vH[i] = $this.attr('height');
				vK[i] = vW[i]/vH[i];
				if (vW[i] > vH[i]){ vH[i] = vH[i]*(pw/vW[i]); vW[i] = pw; } else { vW[i] = vW[i]*(ph/vH[i]); vH[i] = ph; }
				if (vW[i] > pw - pcWidth){ vW[i] = pw - pcWidth; vH[i] = vW[i]/vK[i]; }
				if (vH[i] > ph){ vH[i] = ph; vW[i] = vH[i]*vK[i]; }
				$this.attr('width', vW[i]);
				$this.attr('height', vH[i]);
				$this.css({ 'position':'absolute', 'left':'50%', 'top':'50%', 'margin': '-' + vH[i]/2 + 'px 0 0 -' + vW[i]/2 + 'px'});
		});
	}
}

defineLinks = function(thisEl){
    var popPrevLink = $('#portfolio #prev_link'), // pop-up prev link
        popNextLink = $('#portfolio #next_link'), // pop-up next link
        workType = '#',
        elPrev, elNext,
        thisClass = $(thisEl).attr('class'),
        numThis = thisClass.substr(4, thisClass.length - 4),
        flinks = [], titles = [],
        prevLink, prevTitle, nextLink, nextTitle,
        currLink = $(thisEl).attr('href');
    
        $('#carusel.filter div.filter_block a').each(function(i){
            if ($(this).hasClass('active')) workType = $(this).attr('href');
        });

	if (workType != '#'){
		$(thisEl).parents('ul').find('a').each(function(k){
			if ($(this).parent().attr('data-worktype') == workType){
				flinks.push($(this).attr('href'));
				titles.push($(this).attr('title'));
			}
		});
		var numInFilter;
		for (var j = 0; j < flinks.length; j++){
			if (flinks[j] == currLink) numInFilter = j;
		}
		
        prevLink = flinks[numInFilter - 1];
		nextLink = flinks[numInFilter + 1];
		prevTitle = titles[numInFilter - 1];
		nextTitle = titles[numInFilter + 1];

    } else {
        elPrev = $(thisEl).parent().prev().find('a');
        elNext = $(thisEl).parent().next().find('a');
        
        prevLink = elPrev.attr('href');
        prevTitle = elPrev.attr('title');
        nextLink = elNext.attr('href');
        nextTitle = elNext.attr('title');
    }
    
    function addActive(el, link, title){
        el.attr('href', link).attr('title', title).addClass('active');
    }
    
    function removeActive(el) {
        el.hide();
    }
    
    (typeof prevLink != 'undefined') ? addActive(popPrevLink, prevLink, prevTitle) : removeActive(popPrevLink);
    (typeof nextLink != 'undefined') ? addActive(popNextLink, nextLink, nextTitle) : removeActive(popNextLink);
    
    window.location.hash = currLink;
    
}

checkPortfolio = function(){
    if($('#portfolio').length != 0){
        var hash = window.location.hash;
        if (hash != "" && window.location.href.indexOf('#') != window.location.href.length - 1) {
            var  href = hash.substr(1);
            var n = 0;
                $('#overlay').show();
		if ($.browser.msie && $.browser.version < 9){
			$('#carusel').hide();
			$('#portfolio').show();
		} else{
			$('#carusel').animate({'opacity':0}, 300, function(){
				$(this).hide();
				$('#portfolio').show();
			});
		}
                
            $('#carusel ul li a').each(function(i){
                if ($(this).attr('href') == href){
                    n = i;
                }
            });
            
            var thisEl = $('#carusel ul li a').eq(n);
            var bg = thisEl.attr('rel');
                $('#bg').attr('src', bg);
                $.ajax({
                    url: href,
                    //cache: true,
                    success: function(html){
                        $("#portfolio").html(html);
                        defineLinks(thisEl);
                        if ($("#portfolio").find('div.preview ul li').length < 2) $("#portfolio").find('div.info div.navigation').hide();
                        viewport();
                        //initPortfolio();
                        favicon.change("/media/images/favicon.ico");
                    }
                });

        }
    }
}

function clearHash(){
    window.location.hash = '';
}

function checkCaruselPosition(){
	
	if ($('#portfolio div.case').length == 0) return;


			var popupPortfolioID = $('#portfolio div.case').attr('id');
				$('#carusel ul li a').each(function(i){
					if ($(this).attr('class') == popupPortfolioID)
						thumbIndex = i;
				});
		
			var repaintCaruselUl = $('#carusel ul'),
				repaintCaruselUlPrev = $('#carusel a.prev'),
				repaintCaruselUlNext = $('#carusel a.next'),
				repaintCaruselUlWidth = repaintCaruselUl.width(),
				repaintCaruselFrameWidth = $('#carusel').width();
				
				if (repaintCaruselFrameWidth > repaintCaruselUl.find('li').length * 145 + 30) return;

				repaintCaruselUl.css("left", -thumbIndex * 145);
				
			var startCaruselPosition = parseInt(repaintCaruselUl.css("left"));
				
				if (startCaruselPosition != 0){
					repaintCaruselUlPrev.show();
					repaintCaruselUlNext.show();
					if (startCaruselPosition > 0){
						repaintCaruselUlPrev.hide();
					}
					if (startCaruselPosition <= repaintCaruselFrameWidth - repaintCaruselUlWidth){
						repaintCaruselUlNext.hide();
						startCaruselPosition = repaintCaruselFrameWidth - repaintCaruselUlWidth;
						repaintCaruselUl.css("left", startCaruselPosition);
					}
						
				}

}

function checkCaruselPositionOnResize(){
	if ($('#carusel').length != 0){
		var caruselUl = $('#carusel ul'),
			startCaruselPosition = parseInt(caruselUl.css("left")),
			caruselUlPrev = $('#carusel a.prev'),
			caruselUlNext = $('#carusel a.next'),
			caruselUlWidth = caruselUl.find('li').length * 145 + 30,
			caruselFrameWidth = $('#carusel').width(),
			caruselActiveElement = caruselUl.find('li.active');
			caruselActiveElementWidth = caruselActiveElement.length * 145 + 30;
			
			if (caruselFrameWidth > caruselUlWidth || caruselFrameWidth > caruselActiveElementWidth){
					caruselUlPrev.hide();
					caruselUlNext.hide();
					return;
			} else {
				if (startCaruselPosition == 0){
					caruselUlPrev.hide();
				} else {
					caruselUlPrev.show();
				}
				caruselUlNext.show();
				if (startCaruselPosition > 0){
					caruselUlPrev.hide();
				}
				if (startCaruselPosition <= caruselFrameWidth - caruselUlWidth){
					caruselUlNext.hide();
					startCaruselPosition = caruselFrameWidth - caruselUlWidth;
					caruselUl.css("left", startCaruselPosition);
					pos = startCaruselPosition;
				}
			}
	}
}

$(window).resize(function(){
	viewport();
	
	if ($('#team').length != 0) initMemberTooltip();
	
	checkCaruselPositionOnResize();
});

window.onload = function(){
    viewport();
	
	if ($('#team').length != 0) initMemberTooltip();
	
    runSlides();
	checkCaruselPosition();
    $('img.preload').hide();
	$('#bg, div#lights, div#peopleMove').css({'left':0, 'top':0});
    $('#header').append('<img src="/media/images/gradient_top.png" id="grTop" style="left:0;top:0;"/>');
    $('#carusel').append('<img src="/media/images/gradient_bottom.png" id="grBtm" style="left:0;bottom:0;" />');
    $('#grTop, #grBtm').bind('load', function(){
        $(this).show();
    });
	// Define carusel
	initCarusel();
}

$(document).ready(function(){
	initBlog();
	initMenu();
	initProduction();
	initAll();
    checkPortfolio();
    $('img.preload').bind('load', function(){
        $(this).show();
    });
});
