$(function() {

    /// IMPROVEMENTS ///

    // classes for lists
    var $li=$('li');
    $li.filter(':first-child').addClass('first');
    $li.filter(':last-child').addClass('last');
    $('dt:first-child').addClass('first');
    $('dd:last-child').addClass('last');
    
    // if a table row has only a link, clicking anywhere on the row will send you directly to the link destination
    $('tr').each(function(){
        var $this=$(this);
        var $a=$this.find('a, input, select');
        if (1==$a.length){
            // once checked, we assign CSS attributes and events for clicking and hover
            $this.css({cursor:'pointer'}).click(function(){
                document.location=$a.get(0).href;
            }).hover(function(){
                $this.addClass('hover');
            },function(){
                $this.removeClass('hover');
            });
        }
    });

    
    /// IE HACKS ///
    
    // correct min-width for #wrap in IE
    if ($.browser.msie){
        var correctMW=function(){
            if($(window).width()*0.9>900){
                $('#wrap').width('auto');
            } else {
                $('#wrap').width('900px');
            }
        }
        correctMW();
        $(window).resize(correctMW);
    }
    
    // correcting IE6 non support for #menu li:hover
    $('#menu li').mouseenter(function() {
        $(this).addClass('hover');
    }).mouseleave(function() {
        $(this).removeClass('hover');
    });

    
    /// INVOCATIONS OF PLUGINS //
    
    // Fancybox (only in offerDetailsX)
    if(typeof($().fancybox)!="undefined"){
        $('#imageGallery a').fancybox();
    }
    
    // Countdown
    $('span.countdown').each( function() {
        var $t = $(this);
        var oDate = $t.find('input').val();
        $t.countdown({until:oDate})
    });

    // TinyMCE
    $('textarea').tinymce({
        theme : "advanced",
        // Theme options
        theme_advanced_buttons1 : 'bold,italic,underline,strikethrough,separator,undo,redo,separator,cleanup,separator,bullist,numlist',
        theme_advanced_buttons2 : "",
        theme_advanced_buttons3 : "",
        theme_advanced_buttons4 : "",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "",
        theme_advanced_resizing : false,
    });

    // sortable tables, for documentation view http://tablesorter.com/docs/
    $('table.tablesorter').tablesorter({
        widgets:['zebra'],
        textExtraction:function(nodo){
            return $(nodo).text();
        }
    });
    
    /// INITIATIONS ///
    
    // Bid history in offerDetailsX
    $('#bidHistory').hide();

    // In all pages with user text
    $('a.newWindow').click(function(){
        window.open(this.href);
        return false;
        });

    //TABS in offerDetailsX
    //Default Action
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content
    //On Click Event
    $("ul.tabs li").click(function() {
        $("ul.tabs li").removeClass("active"); //Remove any "active" class
        $(this).addClass("active"); //Add "active" class to selected tab
        $(".tab_content").hide(); //Hide all tab content
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute value to identify the active tab + content
        $(activeTab).fadeIn(); //Fade in the active content
        return false;
    });

    //filter in userSoldItem
    $("#filter").change(function() {
        $("#filterForm").submit();
    });

    if(typeof(refreshTime)!="undefined"){
        if(template == "index"){
            var refreshP = setInterval(refreshHome, refreshTime*1000);
        }
    }
});


/// MESSAGES ///
// tagList and tagDetails
$(function() {
    $('ul.tagList').each(function() {
        var $list = $(this).find('a');
        var $details = $(this).next().children();
        // we check if any of the links already has class="active"
        if (1 != $list.filter('.active').length) {
            $list.removeClass('active').eq(0).addClass('active');
        }
        $list.each(function(index) {
            var $t=$(this);
            if (!$t.hasClass('active')) {
                $details.eq(index).hide();
            }
            $t.click(function(){
                // if the  $list element does not exist we go on with the normal behavior
                if (!$details.eq(index).length) return true;
                if ($t.hasClass('active')) return false;
                
                $list.removeClass('active');
                $t.addClass('active');
                $details.filter(':visible').slideUp();
                $details.eq(index).slideDown();
                return false;
            });
        });
    });

    $('#content-messages div.messageActions').each(function() {
        var $this=$(this);
        var $messages=$this.closest('li').find('tr');
        // activating/desactivating links
        var checkLinks = function() {
            var checked = $messages.find('input:checked').length;
            var unread  = $messages.filter('.unread').find('input:checked').length;
            if (checked) {
                $this.find('a.delete').removeClass('disabled');
            } else {
                $this.find('a.delete').addClass('disabled');
            }
            if (checked != unread) {
                $this.find('a.markAsUnread').removeClass('disabled');
            } else {
                $this.find('a.markAsUnread').addClass('disabled');
            }
            if (unread) {
                $this.find('a.markAsRead').removeClass('disabled');
            } else {
                $this.find('a.markAsRead').addClass('disabled');
            }
        }
        $messages.find('input').change(checkLinks);
        // events related to the select element
        $this.find('select').change(function(){
            switch($('option:selected', this).attr('class')) {
                case 'all':
                    $messages.find('input').attr('checked','checked');
                    break;
                case 'none':
                    $messages.find('input').attr('checked', false);
                    break;
                case 'unread':
                    $messages.find('input').attr('checked', false);
                    $messages.filter('.unread').find('input').attr('checked','checked');
                    break;
                case 'read':
                    $messages.find('input').attr('checked', false);
                    $messages.not('.unread').find('input').attr('checked','checked');
                    break;
            }
            checkLinks();
        });
        
    });
});

function submitMessageForm(actionUrl)
{
    $("#messageForm").attr("action",actionUrl);
 
    $("#messageForm").submit(function(){
        return true;
    });

    $("#messageForm").submit();
}


/// OTHER FUNCTIONS ///
function displayError(errorText, container)
{
    // container must be either the DOM element we want to display the error in
    // or a String to get to that element
    var $c = $(container);
    if ($c.find('div.ko').length) { // if div.ko already exists...
        $c.find('div.ko').html(errorText).fadeOut().fadeIn();
    } else { //... else we create it
        $('<div class="ko" style="display:none">'+errorText+'</div>').prependTo($c).slideDown('fast');
    }
}

function refreshHome(){
    $.ajax({
        url: 'index.php?v=JSON',
        success: refreshHomeUpdate,
        dataType: "json"
    });
}

function refreshHomeUpdate(data)
{
    //update featuredOffers:   id:featuredOffer<?=$v['id']?>Time , id:featuredOffer<?=$v['id']?>Price
    list = data.featuredOffers
    for(var i in list){
        id      = list[i].id;
        time    = list[i].endDateDelta;
        price   = list[i].currentPrice;
        
        DOMPrice = $('#featuredOffer'+id+'Price');
        if(DOMPrice.length && price!=DOMPrice.text() ){
            DOMPrice.animate({backgroundColor: "red"}, 1000)
                    .text(price)
                    .animate({backgroundColor: "white"}, 1000);
            
            DOMTime =$('#featuredOffer'+id+'Time span.countdown');
            DOMTime.countdown('destroy')
                    .animate({backgroundColor: "red"}, 1000)
                    .countdown({until:time})
                    .animate({backgroundColor: "white"}, 1000);        
        }
    }
    
    //update lastOffers:       id:lastOffer<?=$v['id']?>Price
    list = data.lastOffers
    for(var i in list){
        id      = list[i].id;
        price   = list[i].currentPrice;
        
        DOMPrice = $('#lastOffer'+id+'Price');
        if(DOMPrice.length && price!=DOMPrice.text() ){
            DOMPrice.animate({backgroundColor: "red"}, 1000)
                    .text(price)
                    .animate({backgroundColor: "white"}, 1000);
        }
    }

    //update nextEndOffers:    id:nextEndOffer<?=$v['id']?>Time ,  id:nextEndOffer<?=$v['id']?>Price
    list = data.nextEndOffers
    for(var i in list){
        id      = list[i].id;
        time    = list[i].endDateDelta;
        price   = list[i].currentPrice;
        
        DOMPrice = $('#nextEndOffer'+id+'Price');
        if(DOMPrice.length && price!=DOMPrice.text() ){
            DOMPrice.animate({backgroundColor: "red"}, 1000)
                    .text(price)
                    .animate({backgroundColor: "white"}, 1000);
            
            DOMTime =$('#nextEndOffer'+id+'Time span.countdown');
            DOMTime.countdown('destroy')
                    .animate({backgroundColor: "red"}, 1000)
                    .countdown({until:time})
                    .animate({backgroundColor: "white"}, 1000);        
        }
    }
}

