/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
var ad_rotate;
function ad_rotate_obj(div,ads){
    this.delay=4000;//ms
    this.div=div;
    this.ads=ads;
    this.pos = 0;
    this.timer = null;
    for(var x=0; x<this.ads.length; x++){
        this.ads[x]['tag'] = $('<a href="'+this.ads[x].href+'"><img src="'+this.ads[x].pic+'"></a>').appendTo(this.div).children('img').hide();
    }
    $(this.ads[this.pos]['tag']).show();
    $(this.div).click(function(){
            window.location = ad_rotate.ads[ad_rotate.pos].href;
        }).find('#left').click(function(){
            ad_rotate.clearTimer();
            ad_rotate.setPlay();
            ad_rotate.prev();
            return false;
        });
    $(this.div).find('#right').click(function(){
        ad_rotate.clearTimer();
        ad_rotate.setPlay();
        ad_rotate.next();
        return false;
    });
    $(this.div).find('#pause').click(function(){
        ad_rotate.clearTimer();
        if($(this).attr('play')){
            ad_rotate.setTimer();
            $(this).attr('play','').css('background-image','url(ad_rotate/pause.png)');
        }else{
            ad_rotate.setPlay();
        }
        return false;
    });
    this.setPlay = function(){
        $(this.div).find('#pause').attr('play','1').css('background-image','url(ad_rotate/right.png)');
    }
    this.clearTimer = function(){
        if(ad_rotate.timer){
            clearTimeout(ad_rotate.timer);
            ad_rotate.timer=null;
        }
    }
    this.setTimer = function(){
        this.next();
        this.timer=setTimeout(function(){ad_rotate.setTimer();},this.delay);
    }
    this.next = function(){
        var temp = $(this.ads[this.pos]['tag']).css('z-index','2');
        this.pos++;
        if(this.pos>=this.ads.length)
            this.pos=0;
        $(this.ads[this.pos]['tag']).show();
        $(temp).fadeOut('fast',function(){$(this).css('z-index','');});
        //$(temp).fadeOut('fast',function(){$(temp).css('z-index','1');});
    };
    this.prev = function(){
        var temp = $(this.ads[this.pos]['tag']).css('z-index','2');
        this.pos--;
        if(this.pos<0)
            this.pos=this.ads.length-1;
        $(this.ads[this.pos]['tag']).show();
        $(temp).fadeOut('fast',function(){$(this).css('z-index','');});
    };
    this.timer=setTimeout(function(){ad_rotate.setTimer();},this.delay);
}


$(document).ready(function(){
    $('#ad_rotate').hover(function(){
        $(this).find('.ad_button').fadeIn('fast');
    },function(){
        $(this).find('.ad_button').fadeOut('fast');
    });
    if(ads && ads.length){
        ads.sort(function(a,b){return Math.floor(Math.random()*10-5);});
        ad_rotate = new ad_rotate_obj($('#ad_rotate'),ads);
    }
});

