$(document).ready(function(){

    $.fn.cycle.updateActivePagerLink = function(pager, currSlideIndex) {
    $(pager).find('li').removeClass('active')
        .filter('li:eq('+currSlideIndex+')').addClass('active');
    };

    $('#subscribe_email').focus(function(){
       if($(this).val() == $(this).attr('title')) $(this).val('');
    });

    $('#subscribe_email').blur(function(){
       if($(this).val() == '') $(this).val($(this).attr('title'));
    });

    $('.cycle script').remove();

    $('.cycle').cycle({
        timeout: 2000000000,
        pager:  '#bb-nav ul',
        fx: 'fade',
        speed: 200,
        pagerAnchorBuilder: function(idx, slide) {
            return '<li><a href="#">' + $(slide).attr('name') + '</a></li>';
        }
    });

    $('.download-btn').click(function(){
        fileDownload($(this).attr('href'),$(this).attr('title'));
        return false;
    });

    $('.cboxElement').colorbox();
});

function submitDownloadForm()
{
    var file = $('#download_request_file').val();
    var filename = $('#download_request_filename').val();
    var valid = true;

    $('#download-form input:text').each(function(){
       if(!$(this).val())
       {
           alert($(this).attr('title') + ' is required.');
           valid = false;
           return false;
       }
       if(this.name == 'email')
       {
           var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
           var address = $(this).val();
           if(reg.test(address) == false) {
              alert('Invalid Email Address');
              valid = false;
              return false;
           }
       }
    });

    if(!valid) return false;

    $.post('/theme/download-form.php',$('#download-form').serialize()+'&submit=1',function(data){
        if(data.success == '1')
        {
            $('#popup').load('/theme/download-form.php?r='+Math.random(),'&success=1&file='+file+'&filename='+filename,function(){
                //fileDownload(file,filename);
                $('#final_download_link').click(finalClickDownload);
            });
        } else {
            alert('There was an error');
        }
    });
}

function finalClickDownload()
{
    var file = $(this).attr('href');
    $.post('/theme/download-form.php?r='+Math.random(),$('#download-form').serialize()+'&download=1',function(data){
        window.location = file;
    });
    return false;
}

function fileDownload(file,filename)
{
    $.colorbox({
        innerWidth:573,
        innerHeight:380,
        html: '<div id="popup">Loading...</div>',
        onComplete: function(){
            $('#popup').load('/theme/download-form.php?r='+Math.random(),'&file='+file+'&filename='+filename,function(){
                $('#final_download_link').click(finalClickDownload);
            });
        }
    });
    return false;
}

