
$(function($){
    var URI	= new URIParser($);
    function initScroller(){
        new Scroller()
    }
    
    $body = $('#thewrap').attr('scrollTop',0);
    $('#htop').css('top','-70px');
    $('header').hover(function(){
        $('#htop').animate({
            'top':'-64px'
        });
        $('#btop').animate({
            'top':'0px'
        });
    }, function() {
        $('#htop').animate({
            'top':'0px'
        });
        $('#btop').animate({
            'top':'-100px'
        });
    })
    resizeTOC();
    $(window).bind('load',on_load);
    function on_load(e){
        $('#preload').fadeOut(500,startHome);
        initScroller();
        if (URI.segment(1)!='')
            $('body').triggerHandler('ACTIVATE_NAV',URI.segment(1));
    }
    $('a[rel="int"]').click(function(){
        var hash = $(this).attr('href');
        var elem = hash.split("/");
        var position = $('#'+elem[1]).attr('scrollTo'); //$('div#p-'+id)
        console.log('position to: '+position);
        $('#thewrap').stop().animate({
            top: -position
        },1200,'easeInOutQuart',on_scroll_complete);
        function on_scroll_complete(e) {
            startPage(elem[1]);
        }
    })
    
});
$(window).resize(function(){
    $('#thewrap').css('top',0);
    resizeTOC();
})
function resizeTOC () {
    var hview = $(window).height();
    $('#bigwrapper,#home,#portfolio,#social,#contacts,#blog').height(hview-70);
    
    $('#home,#portfolio,#social,#contacts,#blog').each(function(){
        var posy = ($(this).offset().top)-70;
        $(this).attr('scrollTo',posy);
    })
}
function startPage(p) {
    if(p=='portfolio') {
        performPortfolio();
    }
    if(p=='blog') {
        loadBlog();
    }
}
function performPortfolio(){
    
    var hashdef = window.location.hash;
    var hash =hashdef.split('/');
    stp = 1;
    if(hash[2]>=1) {
        stp = parseInt(hash[2]);
    }
    $('#portfolio ul').jcarousel({
        scroll:1,
        start:stp,
        easing:'easeInOutQuart',
        wrap:'last',
        itemVisibleInCallback:itemVisib,
        initCallback:function(){
            $('#portfolio ul').css('display','block');
        }
    })

    $('.clipmg').hover(function(){
        $(this).animate({
            width:695,
            backgroundPosition: '0px 0px'
        },600,'easeInOutQuart');
        $('img',this).animate({
            'left':0,
            'opacity':0
        },600,'easeInOutQuart');
    }, function () {
        $(this).animate({
            width:375,
            backgroundPosition: '-100px 0px'
        },400,'easeInOutQuart');
        $('img',this).animate({
            'left':-100,
            'opacity':1
        },400,'easeInOutQuart');
    });
    $("a[rel^='fancy']").fancybox({
        padding:0,
        margin:20,
        overlayOpacity:0.2,
        overlayColor:'#000',
        titlePosition:'over'
    });
    $('a.fancycomm').removeAttr('onclick').fancybox({
        margin:90,
        overlayOpacity:0.2,
        overlayColor:'#000',
        titleShow:false,
        type:'iframe',
        width:570
    })
}
function itemVisib(c,li,i,s) {
    window.location.hash = '#/portfolio/'+i;
}
function startHome() {
    
    $('#hello').fadeIn(600,function(){
        $('#fotodavid').fadeIn(700,function(){
            $('#whoim').fadeIn(600,function(){
                $('#range').fadeIn(700);
            });
        })
        
        $('#htop').animate({
            'top':'0px'
        },700);
    });
}
/*
**
** URI PARSING
**
*/  
function URIParser($){
    this.Hash = location.hash;
    this.HashObjects = this.Hash.split("/");
    initialize();
    function initialize(){
        
    }
}

URIParser.prototype.segment=function(id){
    if (this.HashObjects[id])
        return this.HashObjects[id];
    else
        return '';
}
function Scroller(){
    init();
    function init (){
        $('body').bind('ACTIVATE_NAV',on_activate_nav);
        $(window).bind('scroll',on_scroll)
    }
    function on_activate_nav(e,id){
        //console.log(e,id)
        var position = $('#'+id).attr('scrollTo'); //$('div#p-'+id)
        
        $('#thewrap').stop().animate({
            top: -position
        },1200,'easeInOutQuart',on_scroll_complete(id));	
        

    }
    function on_scroll_complete(id){
        startPage(id);
    }
    function on_scroll(e){
        
        var pos = ($.browser.safari) ? $('#thewrap').attr('scrollTop') : $body.attr('scrollTop')
        var content = new Array('home','portfolio','social','contacts','blog')
        for (var i=0;i<content.length;i++) {		
            var $prevtop 	= (i==0) ? 0 : $('#'+content[i-1]).offset().top;
            var $curtop 	= $('#'+content[i]).offset().top;
            if ($curtop < pos+100 && pos+100>$prevtop){	
                $('body').triggerHandler('TOP',content[i])
            }
        }
    }
}
var blogopen = false;
function loadBlog() {
    if(!blogopen) {
    $('#blogcont').load('/wp-content/themes/ildavid2011/loadblog.php',function(){
        $('.post').each(function(index){
            $(this).delay(400*index).fadeIn(300);
        })
    })  
    blogopen=true; 
    } 
}

(function($) {
    $.extend($.fx.step,{
        backgroundPosition: function(fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
            }
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

            function toArray(strg){
                strg = strg.replace(/left|top/g,'0px');
                strg = strg.replace(/right|bottom/g,'100%');
                strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
                var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
                return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
            }
        }
    });
})(jQuery);
