(function($) {
    $.fn.fadeIn = function(speed, callback) {
    	return this.animate({opacity: 'show'}, speed, function() {
    		if ( $.browser.msie && $.browser.version<9)
    		{
    			this.style.removeAttribute('filter');
    		}
    		if ( $.isFunction(callback) )
    		{
    			callback.call(this);
    		}
    	});
    };
    $.fn.fadeOut = function(speed, callback) {
    	return this.animate({opacity: 'hide'}, speed, function() {
    		if ( $.browser.msie && $.browser.version<9 )
    		{
    			this.style.removeAttribute('filter');
    		}
    		if ( $.isFunction(callback) )
    		{
    			callback.call(this);
    		}
    	});
    };
    $.fn.fadeTo = function(speed, to, callback) {
    	return this.animate({opacity: to}, speed, function() {
    		if ( to == 1 && $.browser.msie && $.browser.version<9 )
    		{
    			this.style.removeAttribute('filter');
    		}
    		if ( $.isFunction(callback) )
            {
    			callback.call(this);
    		}
    	});
    };
})(jQuery);


$(document).ready(function(){

    var ie;
    if($.browser.msie && Math.floor($.browser.version)<9){
	    ie='shit';	
    }

    if(window.location.pathname != "/") {
        window.location.assign(window.location.protocol + "//" + 
                               window.location.host + "/#!" + window.location.pathname);
    }

    var hash = window.location.hash.split('!')[1];
    var old_hash = hash;
    var isIndex = false;
    var contentLoaded = false;
    var baseUrl = window.location.protocol + '//' + window.location.host;
    var baseUrlLength = baseUrl.length;
    if(hash === undefined || hash == '/') {
        isIndex = true;
    }
    
    // TODO: put this string to news module
    // $('#right').height($('#left').height());

    function getHref(element) {
        var href = element.attr('href');
        if(href.indexOf(baseUrl) === 0) {
            return href.substr(baseUrlLength);
        } 
        return href;
    }

    function loadContent(callback) {
        $.ajax({
            url: contentUrl,
            success: function(data) {
                var url_part = window.location.hash.split('!')[1];
                $('body').html(data).attr('id', '');
                $('html').css('overflow', 'auto');
                if(typeof callback === "function") {
                    callback();
                }
            },
            dataType: 'html'
        });
    }

    function switchIndexToContent(href) {
		var div=$('<div />');

		$('#desk .block').each(function(){
			$(this).delay(Math.floor(Math.random()*301))
				.animate({opacity:0},Math.floor(Math.random()*301));
		});
	    // $('html').removeAttr('style');
		$('#menu').delay(300).append(div).animate({width:'110%'},400,function(){
            window.location.hash = "#!" + href;
            // $('html').css('overflow', 'auto');
        });
    }

    function loadIndex() {
        $.ajax({
            url: indexUrl,
            dataType: 'html',
            success: function(data) {
                $('body').empty().append(data).attr('id', 'index');
                if(ie == "shit") {
                    $('html').css('overflow', 'hidden');
                }
		        document.onselectstart = function() {return false;} // ie
		        //show items
		        $('#desk .block').each(function(){
			        if(ie != 'shit'){
				        $(this).delay(Math.floor(Math.random()*301))
					        .animate({opacity:1},Math.floor(Math.random()*301));
			        }
		        });
		        //mouse scroll
		        if($.browser.webkit) scroller=$('body');
		        else scroller=$('html');
		        scroller.scrollLeft($('#desk div.block').eq(25).offset().left-28).scrollTop($('#desk div.block').eq(25).offset().top-100);
		        
		        var view=$('#view');
		        var ml=0,mt=0,scl=0,sct=0;
		        view.mousedown(function(mouse){
                                view=$(document);
			        var mXtmp=mouse.pageX;
			        var mYtmp=mouse.pageY;
			        $('#view').css('z-index','999');
			        if(ie != 'shit')
				        $('#logo, #menu').stop().fadeTo(400,0.5);
			        view.mousemove(function(mouse){
				        mX=mouse.pageX;
				        mY=mouse.pageY;
				        scl=scroller.scrollLeft();
				        sct=scroller.scrollTop();
				        scroller.scrollLeft(scl+(mXtmp-mX));
				        scroller.scrollTop(sct+(mYtmp-mY));
			        });
			        return false;
		        });
                view=$(document);
                view.mouseup(function(){
			        $('#view').css('z-index','20');
			        view.unbind('mousemove');
			        if(ie != 'shit')
				        $('#logo, #menu').stop().fadeTo(400,1);
		        });
                        /*
		        if(ie != 'shit') 
			        view.mouseleave(function(){
				        $('#view').css('z-index','20');
				        view.unbind('mousemove');
				        if(ie != 'shit')
					        $('#logo, #menu').fadeTo(400,1);
			        });
                        */

	            //mainmenu effects
	            $('#menu a').click(function(){
                    var href = getHref($(this));
                    switchIndexToContent(href);
		            return false;
	            })

	            //mainmenu show/hide
	            $('#switch').hover(function(){
		            $(this).stop().animate({
			            opacity:1
		            },400)
	            },function(){
		            if($('#menu').css('left')=='-29px'){
			            $(this).stop().animate({
				            opacity:0
			            },400)
		            }
	            });
	            $('#switch').toggle(function(){
		            if(ie != 'shit'){
			            $('#menu ul').animate({
				            backgroundPosition: '0'
			            },100)
		            }else{
			            $('#menu ul').css('background-position','0px 0px')
		            }
		            $('#menu').animate({
			            left:0
		            },150).animate({
			            left:-351
		            },250);
		            $(this).stop()
			            .css({opacity:0,backgroundPosition:'0px 0px'})
			            .animate({
				            opacity:1
			            },400)
	            },function(){
		            $('#menu ul').css('background-position','29px 0');
		            $('#menu').animate({
			            left:-380
		            },150).animate({
			            left:-29
		            },250);
		            $(this).animate({
			            opacity:0
		            },600).css({backgroundPosition:'0 -64px'});
	            });
            }
        });
    }

    function setNewsHeight() {
        var r_height = $('#right').height();
        var l_height = $('#left').height();
        var min_height = r_height + 100;
        $('#right').animate({height: min_height > l_height ? min_height : l_height});
    }

    function menuChanged() {
        var a = $('p.menuitem').find('a[href="/' + hash.split('/')[1] + '/"],a[href="' + baseUrl + '/' + hash.split('/')[1] + '/"]');
 	    var ph = a.parent();

		var currcont = ph.next();
        document.title = a.html();

        function setNewInnerItemContent(data) {
            currcont.append(data);
			currcont.slideDown(400, setNewsHeight);
			if(ie=='shit') {
				currcont.find('ul.submenu li')
					.css({top: -50})
					.animate({
						top:0
					},500)
			} else {
				currcont.find('ul.submenu li')
					.css({top: -50, opacity: 0 })
					.animate({top: 0, opacity: 1 }, 500)
			}
			ph.nextAll('.hr:first').show();
        }

        function openNewInnerItem() {
            $.ajax({
                url: hash,
                success: function(data) {
                    setNewInnerItemContent(data);
                },
                statusCode: {404: function() {
                    setNewInnerItemContent('<div class="text">Раздел находится в разработке</div>');
                }},
                dataType: 'html' 
            });
        }
        
		$('.menuitem').removeClass('selected');
		ph.addClass('selected');
        var visible_currcont = $('.innercontent:visible');
        if (visible_currcont.length > 0) {
            visible_currcont.slideUp(200, function() {
                visible_currcont.empty();
				$('span.hr').hide();
                openNewInnerItem();
            });
        } else {
            openNewInnerItem();
        }
     }

    function agencySubMenuClicked() {
        var a = $('ul.agency').find('a[href="' + hash + '"],a[href="' + baseUrl + hash + '"]');
        document.title = a.html();
	    var ph = a.parent();	
		var currcont = ph.parent().next();
        
		$('.agency li').removeClass('selected');
		ph.addClass('selected');
        currcont.slideUp(200, function() {
            currcont.empty();
            $.ajax({
                url: hash,
                dataType: 'html',
                success: function(data) {
                    var html = $("<div>" + data + "</div>").find('div.text');
                    currcont.html(html).slideDown(400).show(function() {
                        currcont.html(html).show();
                    });
                }
            });
        });
    }

    function newsSubMenuClicked() {
		var currcont = $('.innercontent:visible');
        currcont.slideUp(200, function() {
            currcont.empty();
            $.ajax({
                url: hash,
                dataType: 'html',
                success: function(data) {
                    currcont.append(data);
				    currcont.slideDown(400);
                    setNewsHeight();
                }
            });
        });
    }

    $(window).hashchange(function(event) {
        old_hash = hash;
        hash = window.location.hash.split('!')[1];
        if(hash === undefined || hash == '/') {
            loadIndex();
            isIndex = true;
        } else if (isIndex || !contentLoaded) {
            loadContent(menuChanged);
            isIndex = false;
            contentLoaded = true;
        } else {
            if(old_hash.split('/')[1] != hash.split('/')[1]) {
                menuChanged();
            } else {
                if(hash.search(/^\/agency\//) != -1) {
                    agencySubMenuClicked();
                } else if (hash.search(/^\/news\//) != -1) {
                    newsSubMenuClicked();
                } else if (hash.search(/^\/works\//) != -1) {
                    if(old_hash.search(/^\/works\/\d+/) == -1) {
                        newsSubMenuClicked();
                    } else if (hash.search(/^\/works\/\d+\/$/) != -1) {
                        newsSubMenuClicked();
                    }
                } else {
                    // alert(1);
                }
            }
        }
    });

    $(window).hashchange();

    $('p.menuitem a').live('click',function(e){
        var url = getHref($(this));
 	    var ph = $(this).parent();

	    if(!ph.hasClass('selected')){
            window.location.hash = "#!" + url;
        } else if (url.search(/^\/news\//) != -1) {
            window.location.hash = "#!" + url;
        } else if (url.search(/^\/works\//) != -1) {
            window.location.hash = "#!" + url;
            menuChanged();
        }

        return false;
    });


    $('ul.agency a').live('click',function(){
	    var ph = $(this).parent();	
        var url = getHref($(this));
	    
	    if(!ph.hasClass('selected')){
            window.location.hash = "#!" + url;
	    }
        
	    return false;
    });

    $('a.news_year').live('click', function() {
        if(!$(this).hasClass('selected')) {
            window.location.hash = "#!" + getHref($(this));
        }
        return false;
    });

    $('a.news_item').live('click', function() {
        window.location.hash = "#!" + getHref($(this));
        return false;
    });

    $('a.news_item_index').live('click', function() {
        switchIndexToContent(getHref($(this)));
        return false;
    });

    $('#language_form a').live('click', function() {
        var lang_set = $(this).attr('id');
        $('input#language').val(lang_set);
        $('#language_form input[name="next"]').val(window.location);
        $('#language_form').submit();
        return false;
    });

    $('a.back_to_works').live('click', function() {
        $('a.wcat').eq(0).click();
        return false;
    });

    $('a.wcat').live('click',  function() {
        var pn = $(this).parent();
        var wcatHref = getHref($(this));
        var classNames = $(this).attr('class').replace( /^\s+|\s+$/g, '').split(/\s+/);
        var catId = null;
        $("ul.submenu li").removeClass("selected");
        pn.addClass("selected");
        for (var i = 0; i < classNames.length; i++) {
            var className = classNames[i];
            if(className.search(/^wcat_\d+$/) > -1) {
                catId = className.substr(5);
                break;
            }
        }
        var divBlock = $("div.portfolio div.block");
        function showHideCategory() {
            divBlock.each(function () {
                var classNames = $(this).attr('class').replace( /^\s+|\s+$/g, '').split(/\s+/);
                for (var i = 0; i < classNames.length; i++) {
                    var className = classNames[i];
                    if(className.search(/^cat_\d+$/) > -1) {
                        if(catId === null || className.substr(4) == catId) {
                            $(this).show();
                        } else {
                            $(this).hide();
                        }
                        break;
                    }
                }
            });
        }
        if(divBlock.size() == 0) {
            var ulSubmenu = $(".innercontent ul.submenu");
            var ulSubmenuSiblings = ulSubmenu.siblings();
            ulSubmenuSiblings.slideUp(200, function(){
                if($(this).attr("id") == "left") {
                    ulSubmenuSiblings.remove(); 
                    window.location.hash = "#!" + wcatHref;
                    $.ajax({
                        url: wcatHref,
                        dataType: 'html',
                        success: function(data) {
                            var divPortfolio = $("<div>" + data + "</div>").find("div.portfolio").hide();
                            ulSubmenu.after(divPortfolio);
                            divBlock = divPortfolio.find("div.block");
                            showHideCategory();
                            divPortfolio.slideDown(400);
                        }
                    });
                }
            });
        } else {
            showHideCategory();
        }
        return false;
    });

});

