//Avoid being framed (to avoid clickjacking attacks)
if(top.location != location){
    top.location = self.location;
}

$(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();
        $('#defaultImage a').fancybox();
    }
    
    // Countdown
    $('span.countdown').each( function() {
        var $t = $(this);
        var oDate = $t.find('input').val();
        $t.countdown({until:oDate,
        expiryUrl: window.location.href});
    });

    // TinyMCE
    if($('textarea').length){
        $('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,
            convert_urls : false
        });
    }

    // sortable tables, for documentation view http://tablesorter.com/docs/
    // with 1 parser for money and 1 for times
    $.tablesorter.addParser({
        id: "enuukMoney",
        is: function (s) {
            var sp = s.replace(/,/, '.');
            var test = (/([A-Z]{3} ?\d+\.?\d*|\d+\.?\d* ?[A-Z]{3})/.test(sp))
                    || (/([£$€] ?\d+\.?\d*|\d+\.?\d* ?[£$€])/.test(sp)); //check currency with symbol or ISO
            return test;
        }, format: function (s) {
            return $.tablesorter.formatFloat(s.replace(new RegExp(/[^\d\.]/g), ""));
        }, type: "numeric"
    });
    $.tablesorter.addParser({
        id: "enuukCountdown",
        is: function (s) {
            var test = /^(\d{1,3}\w+)?\d{1,2}\w+\d{1,2}\w+\d{1,2}\w+$/.test(s);
            return test;
        }, format: function (s) {
            var fields = s.match(/\d{1,3}/g);
            var acc = 0;
            for(var i=0;i<fields.length;i++){
                acc = acc*100 + parseInt(fields[i]);
            }
            return acc;
        }, type: "numeric"
    });
    $('table.tablesorter').tablesorter({
        widgets:['zebra'],
        textExtraction:function(node){
            return $(node).text();
        }
    });

    // google map init
    if(typeof(address)!="undefined" && typeof(address)=='string'){
        showMap(address);
    }

    /// 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
    if(typeof(address)=="undefined"){
        // there is no Google map, so we can hide the tabs directly, otherwise showMap() will do it
        closeAllTabsOpenFirst();
    }
    //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);
        }
    }

    // Effects //
    $('.categories li').hover( 
        function(){
            $(this).animate({marginLeft:'5px'},200)},
        function(){
            $(this).animate({marginLeft:'0'},200)}
        ); 
});


/// 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();
        });
        
    });
});

/// 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',
        cache:false,
        success: refreshHomeUpdate,
        dataType: "json"
    });
}

function refreshHomeUpdate(JSONdata)
{
    //update featuredOffers:   id:featuredOffer<?=$v['id']?>Time , id:featuredOffer<?=$v['id']?>Price
    list = JSONdata.featuredOffers;
    for(var i in list){
        id      = list[i].id;
        time    = list[i].endDateDelta;
        price   = list[i].currentPriceText;
        
        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 = JSONdata.lastOffers;
    for(var i in list){
        id      = list[i].id;
        price   = list[i].currentPriceText;
        
        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 = JSONdata.nextEndOffers;
    for(var i in list){
        id      = list[i].id;
        time    = list[i].endDateDelta;
        price   = list[i].currentPriceText;
        
        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);        
        }
    }
}

function closeAllTabsOpenFirst(){
    $(".tab_content").hide(); //Hide all content
    $("ul.tabs li:first").addClass("active").show(); //Activate first tab
    $(".tab_content:first").show(); //Show first tab content
}

function showMap(address)
{
    if (GBrowserIsCompatible()) {
        var con = document.getElementById("map");
        var map = new GMap2(con);
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(
            address,
            function(point) {
              if (point) {
                map.setCenter(point, 13);
                var marker = new GMarker(point);
                map.addOverlay(marker);
                marker.openInfoWindowHtml(address);
                setTimeout(closeAllTabsOpenFirst, 800);
              }
            }
          );
    }
}

