var aantal          = 100
,   count           = 10000
,   firstscroll     = false
,   post            = ''
,   url             = 'about:blank'
,   veiling;

;jQuery.fn.inputblur = function(){
    this.each(function(){
        var startText;
        $(this).focus(function(){
            if (typeof(startText) == 'undefined'){
                startText = $(this).val();
            }
            if ($(this).val() == startText) {
                $(this).val('');
            }
        }).blur(function(){
            if ($(this).val() == '') {
                $(this).val(startText);
            }
        });
    });
};

function debug(e) {
    if (typeof(console) == undefined) {
        return false;
    }
    return console.debug(e);
}

function stristr (haystack, needle, bool) {
    var pos = 0;
    haystack += '';
    pos = haystack.toLowerCase().indexOf((needle + '').toLowerCase());
    if (pos == -1) {
        return false;
    } else {
        if (bool) {
            return haystack.substr(0, pos);
        } else {
            return haystack.slice(pos);
        }
    }
}

function laadHtml() {
    var html = $('#post').html();
    var controller = '/veilingen';
    
    if(html != 'true') {
        post = 'post='+html;
    }
    
    if(stristr(window.location.pathname,'dashboard')) {
        controller = '/dashboard';
        
        var get    = window.location.pathname.split('/');
        var filter = get[3];
        var order  = get[4];
        
        $.get(controller + '/jveiling/' + veiling + '/' + aantal + '?filter=' + filter + '&order=' + order, function(data){
            if (data == 'false') {
                return false;
            }
            $('#j-veiling-container').append(data);
            $('img.notloaded:last').load(function(){
                aantal += count;
                return laadHtml();
            });
        });
    } else {
        $.get(controller + '/jveiling/' + veiling + '/' + aantal + '?' + post, function(data){
            if (data == 'false') {
                return false;
            }
            $('#j-veiling-container').append(data);
            $('img.notloaded:last').load(function(){
                aantal += count;
                return laadHtml();
            });
        });
    }
}

// Object popup opbouwen.
function laadProduct() {
    $('select').hide();
    $('#j-veiling-product').show();
    $('#j-popup-background').fadeTo('slow',0.5, function() {});
    $('#j-veiling-product').html('<div id="content" style="border:1px solid #D2CCE5;background:#fff; float:left;'+
        ' margin: 0 auto; z-index: 10px; width:960px" height="500px"">'+
        '<img class="closewindow" style="float: right;" src="http://s3-eu-west-1.amazonaws.com/zadelhoff/img/layout/close.png" alt="sluit venster"/>'+
        '<h1 style="margin-top:10px;text-align:center">Het product wordt geladen</h1>'+
        '<img style="clear:both; float:left; margin-left:435px; margin-bottom:20px;" '+
        ' src="http://s3-eu-west-1.amazonaws.com/zadelhoff/img/prettyPhoto/facebook/loader.gif" align="center"/>'+
        '</div>');
    $.get(url+ '/ajax',function(data){
        $('#j-veiling-product').html(data);
    })
}

function hideProduct(){
    $('select').show();
    $('#j-veiling-product').hide();
    $('#j-popup-background').hide();
}

// object popup positioneren in ie7
function scroll(){
    var scrollHeight = $(this).scrollTop();
    if (scrollHeight < 129) {
        $('#j-veiling-product').css('top',"129px");
    } else {
        $('#j-veiling-product').css('top',"10px");
    }
}

function firstScroll() 
{
    laadHtml();
}

function closePrettyPhoto()
{
    if (stristr(window.location.pathname,'veilingen') || stristr(window.location.pathname,'categorieen') || stristr(window.location.pathname,'dashboard')){
        $.prettyPhoto.close();
        hideProduct();
    } else {
        window.location.reload();
    }
}

// Toevoegen aan Mijn Catalogus.
function favorietenActie(element) 
{
    var element = $(element);
    var object = element.attr('rel');

    $.get('/mijn-catalogus/favorieten/' + object, function(data) {
        element.text(data);
    });
}

// Openen van object popup vanuit veiling lijst.
// Maakt gebruik van laadProduct().
function productActie(element) 
{
    url = $(element).attr('href');
    laadProduct();
    return false;
}

// Openen van object popup vanuit veiling lijst.
// Maakt gebruik van laadProduct().
// Vergelijkbaar met productActie().
function veilingUrlActie(element)
{
    if (stristr(window.location.pathname,'veilingen') || stristr(window.location.pathname,'dashboard') || stristr(window.location.pathname,'categorieen') || stristr(window.location.pathname,'live')){
        url = $(element).attr('href');
        laadProduct();
        return false;
    }
}

function emailActie(element) 
{
    if ($(element).val() === 'Vul hier een e-mailadres in ...') {
        $(element).val('');
    }
}

function zoekenActie(element)
{
    if ($(element).val() === 'Zoek op trefwoord ...') {
        $(element).val('');
    }
}

// Mijn Berichten > Verwijderen van een bericht.
function verwijderBerichtActie(element)
{
    var button      = $(element)
    ,   berichtenId = button.attr('rel')
    ,   url         = '/mijn-berichten/verwijder/' + berichtenId;

    $.post(url, function(data) {
        var data = JSON.parse(data);
        if (data.status == true) {
            button.parent().parent().fadeOut();
        }
    });
    
    return false;
}

// Mijn Favorieten > Verwijderen van een object uit Mijn Favorieten.
function mijnFavorietVerwijderActie(element)
{
    var $this    = $(element)
    ,   objectID = parseInt($this.attr('rel'));

    $this.parent().parent().remove();
    $('.blok').each(function(index,value) {
        if($(value).next().hasClass('blok') || $(value).next().html() == null) {
            // Indien blok leeg is na weghalen van object, dan gehele blok verbergen.
            $(value).remove();
        }
    });
}

$(function() {    
    var request = window.location.pathname
    ,   get     = request.split('/');
    veiling     = get[2];
    
    // Event click delegation.
    $(document).click(function(event) {
        var $t = $(event.target);
        
        if ($t.hasClass('favorieten-actie') || $t.hasClass('favorieten-actie-object')) {
            favorietenActie(event.target);
        };
        
        if ($t.hasClass('mijn-catalogus-favoriet-verwijderen')) {
            return mijnFavorietVerwijderActie(event.target);
        }
        
        if ($t.parent().hasClass('mijn-catalogus-favoriet-verwijderen')) {
            return mijnFavorietVerwijderActie($t.parent());
        }
        
        if ($t.hasClass('prevproduct') || $t.hasClass('nextproduct')) {
            return productActie(event.target);
        }
        
        if ($t.parent().hasClass('prevproduct') || $t.parent().hasClass('nextproduct')) {
            return productActie($(event.target).parent());
        }
        
        if ($t.hasClass('veilingurl')) {
            return veilingUrlActie(event.target);
        }
        
        if ($t.parent().hasClass('veilingurl')) {
            return veilingUrlActie($(event.target).parent());
        }
        
        if ($t.hasClass('closewindow')) {
            return hideProduct();
        }
        
        if (event.target.id == 'j-popup-background') {
            return hideProduct();
        }
        
        if ($t.hasClass('aanmelden-nieuwsbrief-button')) {
            return $("#aanmelden-nieuwsbrief-popup").slideToggle('slow');
        }
        
        if ($t.hasClass('bied-ajax')) {
            return $.prettyPhoto.close();
        }
        
        if ($t.hasClass('email')) {
            return emailActie(event.target);
        }
        
        if ($t.hasClass('zoeken-input-text')) {
            return zoekenActie(event.target);
        }
        
        if ($t.hasClass('j-verwijder-bericht')) {
            return verwijderBerichtActie(event.target);
        }
        
        if ($t.hasClass('print')) {
            return print();
        }
    });
    
    // Object popup > Toevoegen aan Mijn Catalogus.
    $('#j-veiling-container').live('click',function(event) {
        var $targ = $(event.target);

        if ($targ.is(".favorieten-actie")) {
            var objectID = parseInt($targ.attr('rel'));

            $.get('/mijn-catalogus/favorieten/' + objectID, function(data) {
                $targ.text(data);
            });
        }
    });

    // Object popup stylen.
    var $jPopupBackground = $('#j-popup-background');
    $jPopupBackground.css('height', $(window.document).height());
    $jPopupBackground.css('width', $(window.document).width());
    $jPopupBackground.css('opacity', '0.5');

    // Object popup > klik op plaatje > prettyphoto.
    if (typeof($().prettyPhoto) == 'function') { // error check
        $("a[rel^='prettyPhoto']").prettyPhoto({
            allowresize: false,
            callback: function(){
                return false;
            }
        });
    }

    $('a.thumbnail img').live("mouseover",function() {
        var src = $(this).attr('src');
        src = src.replace('164x90', '268x327');
        $('.afbeelding img').attr('src', src);
    });

    if ($(".fotoslider").length > 0) {
        var slidecurrent = 1;
        var countfotos = $(".fotoslider").attr("rel");
        $(".foto:first").removeClass('foto').addClass('fotoshow');
        $(".foto").removeClass("foto").addClass('fotohide');
        $(".fotohide").hide();

        if($(".back").live('click',function(){
            slidecurrent--;
             $(".fotoshow").removeClass("fotoshow").addClass('fotohide').prev().removeClass("fotohide").addClass('fotoshow');
             $(".fotohide").hide();
             $(".fotoshow").show();
            checkbuttons();
        }));
        if($(".next").live('click',function(){
            slidecurrent++;
            $(".fotoshow").removeClass("fotoshow").addClass('fotohide').next().removeClass("fotohide").addClass('fotoshow');
            $(".fotohide").hide();
            $(".fotoshow").show();
            checkbuttons();
        }));

        function checkbuttons(){
            if(slidecurrent == 1){
                $(".back").css("visibility","hidden");
            }
            else{
                $(".back").css("visibility","visible");
            }
            if(slidecurrent == countfotos){
                $(".next").css("visibility","hidden");
            }
            else{
                $(".next").css("visibility","visible");
            }
        };
        checkbuttons();
    };
});
