var timeDiff  =  {
    setStartTime:function (){
        d = new Date();
        time  = d.getTime();
    },

    getDiff:function (){
        d = new Date();
        return (d.getTime()-time);
    }
}
var ajax = false;
var interval = '';
function resizenow() {
    var ss = $('#backgrdiv');
    var res = $('#backgrimg');
    var imh = res.height();
    var imw = res.width();
    var ratio = imh/imw;

    ss.hide();
    var supsize = $(window).width();
    var supsh = $(document.body).height();

    ss.width(supsize);
    ss.height(supsh);
    var browserwidth = $(document.body).width();
    var browserheight = supsh;
    ss.show();
    if ((browserheight/browserwidth) > ratio){
        res.width(browserheight / ratio);
    } else {
        res.width(browserwidth);
    }
    res.css({
        'left': (browserwidth - res.width())/2 ,
//        'top': (supsh - res.height())/2
        });
//    $('#loader').css('top', ($(window).height()/2)-12);
    

    return false;
}

function initAjax() {
getBackground1(window.item.keywords, window.item.id);

    
    $('#next').bind('click', function() {
        if (parseInt($('.num').text()) < parseInt($('.all').text())){
            if(ajax){
                ajax.abort();
            }
            $.getJSON($('#navform').attr('action'),{num: $('.num').text(), act: this.id},
            function(data) {
              if (data){
                  update(data);
                  getBackground(data.item.keywords, data.item.cacheid);
              }
          });
        }
        return false;
    });
    $('#back').bind('click', function() {
        if (parseInt($('.num').text()) != 1){
          if(ajax){
                ajax.abort();
            }
          $.getJSON($('#navform').attr('action'),{num: $('.num').text(), act: this.id},
          function(data) {
              if (data){
                  update(data);
                  getBackground(data.item.keywords, data.item.cacheid);
              }
          });
        }
        return false;
    });

}

function update(data){
    checkNavigation(data.num);

    if (data.num!=1) 
        $('#logourl').attr("href",'/');
    else
        $('#logourl').removeAttr("href");

    window.item.keywords = data.item.keywords;
    window.item.id = data.item.cacheid;

    var title = $('#title');
    if (data.title.src != title.attr("src"))
        title.fadeOut(500, function(){
            title.attr("src", data.title.src);
            title.attr("class", data.title.cls);
        });

    $('#black').css('height', $('#black').height());
    $('#red').css('height', $('#red').height());

    var blackcontent = $('#blackcontent');
    blackcontent.fadeOut(500,function(){
        blackcontent.css('visibility', 'hidden');
        blackcontent.css('display', '');
        blackcontent.html(data.item.description);
        $('#black').animate({width: data.item.isabout?213:150, height: 215},500,function(){
                blackcontent.css('visibility', 'visible');
                blackcontent.css('display', 'none');
                blackcontent.fadeIn(500);
                title.fadeIn(500);
        });
    });

    var redcontent = $('#redcontent');
    redcontent.fadeOut(500,function(){
        redcontent.css('visibility', 'hidden');
        redcontent.css('display', '');
        redcontent.html(data.item.isabout?'<div id="contacts">'+data.item.contacts+'</div>':'<a id="prjurl" target="_blank" href="'+data.item.url+'">'+data.item.domain+'</a><img id="screenshot" border="0" src="'+data.item.screenshot+'">');
        if (!data.item.isabout){
                    $('#red').animate({width: 160, height: 190},500,function(){
                            redcontent.css('visibility', 'visible');
                            redcontent.css('display', 'none');
                            redcontent.fadeIn(500);});
        } else {
            $('#red').animate({height: 82, width: 205},500,function(){
                        redcontent.css('visibility', '');
                        redcontent.css('display', 'none');
                        redcontent.fadeIn(500);});
        }
    });
    
    window.clearInterval(window.h);
    $('.num').text(data.num);
    window.location.hash = '#!'+data.num;
    hashCheck();

}

function checkImage(imgName, data, keywords, cacheid) {
    var cacheImage = document.createElement('img');
    cacheImage.src = imgName;
    window.clearInterval(window.c);
    window.c= window.setInterval(function(){
        if (IsImageOk(cacheImage)){
            window.clearInterval(window.c);
            cacheReady(imgName);
            if (data){
                $('#phototitle').text(data.background.title);
                var owner = $('#owner');
                owner.attr("href", data.background.owner.profileurl);
                owner.text(data.background.owner.username);
            }
        }
    }, 400);

}

function IsImageOk(img) {
    if (!img.complete) {return false;}

    	if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
      	  return false;
    	}
    	return true;
}

function cacheReady(imgName){
    var img = $('#backgrimg');
    img.fadeOut(100, function(){
        $('#backgrimg').attr('src',imgName);
        resizenow();
    });
    img.fadeIn(100)
}

function hashCheck() {
    var hash = window.location.hash;
    window.h= window.setInterval(function(){ 
        if (window.location.hash != hash){
            hash = window.location.hash;
            if (hash){
               loadPageByHash(hash);
            }
        }
    }, 400);
}

function getBackground2(keywords, cacheid){
    timeDiff.setStartTime()
    $(document).unbind('keydown');
    $.getJSON('/loadbg',{keywords: keywords, cacheid: cacheid},
            function(data) {
              if (data){
                  if (!data.error){
                     checkImage(data.background.url, data);
                     
                     getBackground1(keywords, cacheid);
                  }
              }
              bindHotkeys();
          });
}

function getBackground(keywords, cacheid){
    $(document).unbind('keydown');
    ajax = $.getJSON('/loadbg',{keywords: keywords, cacheid: cacheid},
            function(data) {
              if (data){
                  if (!data.error){
                     
                     interval = setTimeout(function() { check_all(data.background.url, data, keywords, cacheid); }, 1);
                     

                  }
              }
              bindHotkeys();
          });
if(interval){
    clearInterval(interval);
}
}

function getBackground1(keywords, cacheid){
    timeDiff.setStartTime()
    $(document).unbind('keydown');
    ajax = $.getJSON('/loadbg',{keywords: keywords, cacheid: cacheid},
            function(data) {
              if (data){
                  if (!data.error){
                     timeDiff.getDiff();
                     if(timeDiff.getDiff()<5000){
                        var time = 5000 - timeDiff.getDiff();
                     }
                     else
                     {
                        var time = 0;
                     }

                     interval = setTimeout(function() { check_all(data.background.url, data, keywords, cacheid); }, time);


                  }
              }
              bindHotkeys();
          });
if(interval){
    clearInterval(interval);
}
}

function check_all(d, da, keywords, cacheid){
if(interval){
    clearInterval(interval);
}
checkImage(d, da);
getBackground1(keywords, cacheid);
}

function checkNavigation(num){
    if (num==1){
        $('#back').css('visibility','hidden');
    }
    else {
        $('#back').css('visibility','visible');
    }
    if (num == parseInt($('.all').text())){
        $('#next').css('visibility','hidden');
    } else {
        $('#next').css('visibility','visible');
    }
}
function loadPageByHash(hash){
     var num = hash?hash.substr(2):1;
     if (num <= parseInt($('.all').text()))
        $('#content').load('/', {num: num},function(response, status, xhr) {
            checkNavigation(num);
            if (num!=1) $('#logourl').attr("href",'/');
            $('#content').css('visibility', 'visible');
            checkImage($('#backgrimg').attr('src'));
            resizenow();
            initAjax();

          });
}

function bindHotkeys(){
    $(document).bind('keydown', 'left', function (evt){getBackground(window.item.keywords, window.item.id); return false; });
    $(document).bind('keydown', 'right', function (evt){getBackground(window.item.keywords, window.item.id); return false; });
    $(document).bind('keydown', 'ctrl+left', function (evt){$('#back').click(); return false;});
    $(document).bind('keydown', 'ctrl+right', function (evt){$('#next').click(); return false; });
}


