//Avoid being framed (to avoid clickjacking attacks)
if(top.location != location){
    top.location = self.location;
}
function displayValue (value, currency)
{
    var currencySymbol='';
    switch (currency)
    {
        case 'GBP':
            currencySymbol = '&pound;';
            break;
        case 'USD':
            currencySymbol = '$';
            break;
        case 'EUR':
            currencySymbol = '&euro;';
            break;
    }
    var Mycurrency=' '+currency;
    if (currencySymbol) { Mycurrency='';}
    dblValue = parseFloat(value);
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	value = Math.floor(dblValue/100).toString();
	if(intCents<10) {strCents = "0" + strCents;}
    formattedValue=currencySymbol+value+'.'+strCents+Mycurrency;
    return formattedValue;
}
function refreshHomeUpdate(JSONdata)
{
    //update featuredOffers:   id:featuredOffer<?=$v['id']?>Time , id:featuredOffer<?=$v['id']?>Price
    var bgColor;
    list = JSONdata.featuredOffers;
    for(var i in list){
        if (list.hasOwnProperty(i)){
            id      = list[i].id;
            time    = list[i].endDateDelta;
            price   = displayValue(list[i].currentPrice,JSONdata.defaultCurrency);
                    
            DOMPrice = $('#featuredOffer'+id+'Price');
            htmlText=DOMPrice.html();
            if (htmlText) {htmlText=htmlText.replace('\u00a3','&pound;');}
            if (htmlText) {htmlText=htmlText.replace('\u0080','&euro;');}
            bgColor=DOMPrice.closest('td').css('backgroundColor');
            if(DOMPrice.length && price!=htmlText ){
                DOMPrice.animate({backgroundColor: "lightgreen"}, 1000)
                        .html(price)
                        .animate({backgroundColor: "transparent"}, 1000);
                var periods=0;
                if (time/(3600*24)>1) periods=3;
                // if (!periods && (time/3600)>1) periods=2;
                DOMTime =$('#featuredOffer'+id+'Time span.countdown');
                
                DOMTime.countdown('destroy')
                        .animate({backgroundColor: "lightgreen"}, 1000)
                        .countdown({until:time,
                            significant:periods,
                            expiryUrl: window.location.href})
                        .animate({backgroundColor: "transparent"}, 1000); 
            }
        }
    }
    
    //update lastOffers:       id:lastOffer<?=$v['id']?>Price
    list = JSONdata.lastOffers;
    for(var j in list){
        if (list.hasOwnProperty(j)){            
            id      = list[j].id;
            price   = displayValue(list[j].currentPrice,JSONdata.defaultCurrency);
            
            DOMPrice = $('#lastOffer'+id+'Price');
            htmlText=DOMPrice.html();
            if (htmlText) {htmlText=htmlText.replace('\u00a3','&pound;');}
            if (htmlText) {htmlText=htmlText.replace('\u0080','&euro;');}
            bgColor=DOMPrice.closest('td').css('backgroundColor');
            if(DOMPrice.length && price!=htmlText ){      
                DOMPrice.animate({backgroundColor: "lightgreen"}, 1000)
                        .html(price)
                        .animate({backgroundColor: bgColor}, 1000);
            }
        }
    }

    //update nextEndOffers:    id:nextEndOffer<?=$v['id']?>Time ,  id:nextEndOffer<?=$v['id']?>Price
    list = JSONdata.nextEndOffers;
    for(var k in list){
        if (list.hasOwnProperty(k)){
            id      = list[k].id;
            time    = list[k].endDateDelta;
            price   = displayValue(list[k].currentPrice,JSONdata.defaultCurrency);
            
            DOMPrice = $('#nextEndOffer'+id+'Price');
            htmlText=DOMPrice.html();
            if (htmlText) {htmlText=htmlText.replace('\u00a3','&pound;');}
            if (htmlText) {htmlText=htmlText.replace('\u0080','&euro;');}
            var bgColor=DOMPrice.closest('td').css('backgroundColor');
            if(DOMPrice.length && price!=htmlText ){
                DOMPrice.animate({backgroundColor: "lightgreen"}, 1000)
                        .html(price)
                        .animate({backgroundColor: bgColor}, 1000);
                var periods=0;
                if (time/(3600*24)>1) periods=3;
                // if (!periods && (time/3600)>1) periods=2;
                
                DOMTime = $('#nextEndOffer'+id+'Time span.countdown');
                DOMTime.countdown('destroy')
                        .animate({backgroundColor: "lightgreen"}, 1000)
                        .countdown({until:time,
                            significant:periods,
                            expiryUrl: window.location.href})
                        .animate({backgroundColor: bgColor}, 1000);        
            }
        }
    }
  
    // update latest bids
    list = JSONdata.highestBids;
    var bidCount=0;
    for(var l in list){
        if (list.hasOwnProperty(l)){
            id      = list[l].offerId;
            var item    = list[l].item;
            var user    = list[l].user;
            var value   = displayValue(list[l].value,JSONdata.defaultCurrency);
            var relativePath = JSONdata.relativePath;
            htmlText='<strong>'+value+'</strong><br/><a href="'+relativePath+'offer/details/'+id+'">'+item+'</a><br/><a class="mostActiveUser" href="'+relativePath+'user/profile/'+user+'">'+user+'</a>';
                    
            DOMBid = $('#latestBid'+bidCount);
            DOMBid.html(htmlText);
            bidCount++;
        }    
    }   
}
function refreshHome(){
    $.ajax({
        url: relativePath+'index.php?v=JSON',
        success: refreshHomeUpdate,
        cache: false,
        dataType: "json"
    });
}

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);
              }
            }
          );
    }
}
$(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 //
       
    // Countdown
    $('span.countdown').each( function() {
        var $t = $(this);
        var oDate = $t.find('input').val();
        var periods=0;
        if (oDate/(3600*24)>1) periods=3;
        // if (!periods && (oDate/3600)>1) periods=2;
        $t.countdown({until:oDate,
            significant:periods,
        expiryUrl: window.location.href});
    });

    // TinyMCE
    if($('textarea').length){
        $('textarea:not(.simple)').tinymce({
            // General options
         theme : "advanced",
         // Plugins
         plugins :    "safari,layer,table,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,media,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras",
         // Theme options
         theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,bullist,numlist,|,outdent,indent,blockquote,formatselect,fontselect,fontsizeselect, |,justifyleft,justifycenter,justifyright,justifyfull",
         theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,preview,|,forecolor,backcolor",
            theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,advhr,|,fullscreen, |,cite,abbr,acronym,ins,attribs,|,visualchars,nonbreaking",
         theme_advanced_toolbar_location : "top",
         theme_advanced_toolbar_align : "left",
         theme_advanced_statusbar_location : "bottom",
         theme_advanced_resizing : true,
         convert_urls : false,   

            // Drop lists for link/image/media/template dialogs
            external_link_list_url : "js/link_list.js",
            external_image_list_url : "js/image_list.js",
            media_external_list_url : "js/media_list.js"           
        });
    }

    // 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();
        }
    });
   
    if(typeof(address)!="undefined"){
        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');
    }
}

