
var gum = {}; // gloabl gumtree namespace...

gum.constants = {}; // any constants needed - object should be overwritten in global.js if required
gum.events = jQuery({}); // empty jQuery object for binding/triggering custom events

/* 
 * GUMTREE LOG
 * Safe logging function - if console isn't available
 * it wont throw an error!
 *
 */
gum.log = function( obj ) {
    window.console && console.log && console.log(obj);
}

/*  
 * GUMTREE template renderer
 * Provides basic template parsing abilities
 * Templates can be stored under the same gum.templates namespace (just
 * don't call one 'render' ;-) )
 */
gum.templates = (function(){
    
    var _tmplCache = {};
    
    function parse(str, data)
    {  
      var err = "";
      try {
          var func = _tmplCache[str];
          if (!func) {
              var strFunc =
              "var p=[],print=function(){p.push.apply(p,arguments);};" +
                          "with(obj){p.push('" +
              str.replace(/[\r\t\n]/g, " ")
                 .replace(/'(?=[^#]*#>)/g, "\t")
                 .split("'").join("\\'")
                 .split("\t").join("'")
                 .replace(/<#=(.+?)#>/g, "',$1,'")
                 .split("<#").join("');")
                 .split("#>").join("p.push('")
                 + "');}return p.join('');";
              func = new Function("obj", strFunc);
              _tmplCache[str] = func;
          }
          return func(data);
      } catch (e) { err = e.message; }
      return "< # ERROR: " + err + " # >";
    }
    
    return {
        
        render : function( str, data )
        {
            if ( this[str] !== undefined ) str = this[str]; // if template exists, use it's content        
            return parse( str, data );
        }
        
    }
    
})();

/* 
 * GUMTREE utility functions
 * Functions/utilities that will only have one instance,
 * providing some helpful functionality, like getting/setting cookies etc
 *
 */
gum.utils = {};

// addRoundie: custom rounded corner implementation for Gumtree
gum.utils.addRoundie = function( selector, cornerString, wrapperID )
{
    var i, _this = $(selector),
        corners = cornerString.split(/\s/),
        count = corners.length;
    
    if ( wrapperID != undefined )
    {
        _this.wrap('<div id="'+wrapperID+'"></div>');
        _this = $('#'+wrapperID);
    }
    
    for ( i = 0; i < count; ++i )
    {
        _this.append('<div class="roundie '+corners[i]+'"></div>');
    }
};

// setStarStatus: set the styling and text of the star
gum.utils.setStarStatus = function( starForm, status, init )
{
    starForm.each(function(){
        
       var _this   = $(this),
            action = _this.find('input[name=action]'),
            label  = _this.find('label'),
            cnst   = gum.constants;

       _this.toggleClass(cnst.STAR_IS_SAVED_CLASS);

       action.val( status == 'added' ? 'remove' : 'add' ); // set value of 'action' input field
       if ( init !== true ) label.text( status == 'added' ? cnst.STAR_SAVE_SUCCESS : cnst.STAR_REMOVE_SUCCESS ).show(); // set and show helper text
       
    });
   
};

gum.utils.submitStarForm = function( e ){

    var _this   = jQuery(this),
        ads = gum.data.ads,
        details = {
            id          : _this.attr('data-id') || '',
            title       : _this.attr('data-title') || '',
            shorttitle  : _this.attr('data-title') ? _this.attr('data-title').substring(0, 24) : '',
            price       : _this.attr('data-price') || '',
            img         : _this.attr('data-img') || '',
            location    : _this.attr('data-location') || '',
            flags       : _this.attr('data-flags') ? _this.attr('data-flags').split(/\s/) : '',
            link        : _this.attr('data-link') || ''
        };
        
    e.stopPropagation();
    
    return ! ads.toggleSaved( details.id, details );
};

/* 
 * GUMTREE data stores
 * Pure data stores for storing/saving data.
 * Should not interact with the DOM but may trigger custom events
 * so that other items can act on them.
 *
 */
gum.data = {};

/*
 * Ads viewed/saved data store with cookie persistence
 *
 * Events triggered:    saved_ad_added / saved_ad_removed
 *                      viewed_ad_added / viewed_ad_removed
 *                      saved_ads_updated
 *                      viewed_ads_updated
 *                      saved_ads_cleared
 *                      viewed_ads_cleared
 */
gum.data.ads = (function()
{
    var ids = { saved : [], viewed : [] },
    items   = { saved : {}, viewed : {} };

    var updated = function( type )
    {
        var c  = gum.constants;
        if ( typeof type === 'string' && items[type] )
        {
            gum.events.trigger(type+'_ads_updated', ids[type].length);
            
            for ( var domain, i = -1; domain = gum.constants.COOKIE_GUMTREE_DOMAINS[++i]; )
            {
                // create a cookie for all of the specified domains
                createCookie( c['COOKIE_'+type.toUpperCase()+'_IDS'], ids[type].join(' '), c.COOKIE_DEFAULT_LIFETIME, domain );
            }        
        } 
        else
        {
            // trigger all 
            for ( type in ids )
            {
                if ( ids.hasOwnProperty(type) && items[type] )
                {
                    gum.events.trigger(type+'_ads_updated', ids[type].length);
                    
                    for ( var domain, i = -1; domain = gum.constants.COOKIE_GUMTREE_DOMAINS[++i]; )
                    {
                        // create a cookie for all of the specified domains
                        createCookie( c['COOKIE_'+type.toUpperCase()+'_IDS'], ids[type].join(' '), c.COOKIE_DEFAULT_LIFETIME, domain );
                    }
                }
            }
        }
    };
    
    var add = function( type, id, item, triggerUpdate )
    {
        if ( ! items[type][id] )
        {
            ids[type].push(id);
            items[type][id] = item || {};
            
            gum.events.trigger(type+'_ad_added', [id, item] );
            if ( triggerUpdate !== false ) updated(type);

            return true;
        }
        return false;
    };
    
    var remove = function( type, id, triggerUpdate )
    {     
        if ( items[type][id] )
        {
            ids[type] = jQuery.grep(ids[type], function(value){
                return value != id;
            });
            delete items[type][id];
            gum.events.trigger(type+'_ad_removed', id );
            if ( triggerUpdate !== false ) updated(type);
            
            return true;
        }
        return false;
    };
    
    var toggle = function( type, id, item )
    {
        if ( items[type][id] && remove( type, id ) ) return 'removed';
        else if ( add( type, id, item ) ) return 'added';
        else return false;
    }
    
    var bulkAddIds = function( type, ids )
    {
         for ( var id, i = -1; id = ids[++i]; ) add( type, id, {}, false );
         updated(type);
    };
    
    var clear = function( type )
    {
        ids[type] = [];
        items[type] = {};
        updated(type);
        eraseCookie(gum.constants['COOKIE_'+type.toUpperCase()+'_IDS'])
        gum.events.trigger(type+'_ads_cleared');
        return true;
    };
    
    var setup = function()
    {
        var cnst         = gum.constants,
            savedCookie  = getCookie( cnst.COOKIE_SAVED_IDS ),
            viewedCookie = getCookie( cnst.COOKIE_VIEWED_IDS );
            
        if ( savedCookie ) bulkAddIds( 'saved', savedCookie.split(cnst.COOKIE_CHUNK_SPLIT) );
        if ( viewedCookie ) bulkAddIds( 'viewed', viewedCookie.split(cnst.COOKIE_CHUNK_SPLIT) );            
    };
    
    jQuery (function(){setup();});
    
    return {
            
        save : function( id, item ){ return add( 'saved', id, item ); },

        unsave : function( id ){ return remove( 'saved', id ); },
        
        toggleSaved : function( id, item ){ return toggle( 'saved', id, item ); },
        
        clearSaved : function(){ return clear( 'saved' ); },
        
        
        view : function( id, item ){ return add( 'viewed', id, item ); },

        unview : function( id ){ return remove( 'viewed', id ); },

        toggleViewed : function( id, item ){ return toggle( 'viewed', id, item ); },
        
        clearViewed : function(){ return clear( 'viewed' ); },
        
        
        getSavedCount : function(){ return ids['saved'].length; },
        
        getViewedCount : function(){ return ids['viewed'].length; },
            
        getSavedIds : function(){ return ids['saved']; },
        
        getViewedIds : function(){ return ids['viewed']; },
        
        
        isSaved : function( id ){ return !! items['saved'][id]; },
        
        isViewed : function( id ){ return !! items['viewed'][id]; },
        
        init : function()
        {
            gum.events.trigger('saved_ads_updated', ids['saved'].length);
            gum.events.trigger('viewed_ads_updated', ids['viewed'].length);
        }
    }

})();

//////////////////////

;(function($){
    
    var defaults = {
        type                : 'saved',
        max                 : 6,
        adTemplate          : '',
        contentTemplate     : '<#= ads #>',
        noContentTemplate   : '',
        clearedTemplate     : '',
        adIdentifierFormat  : 'li.ad-'
    };
    
    $.fn.adList = function( options )
    {
        return this.each(function(){
            
            var o       = $.extend(true, {}, defaults, options),
                cont    = o.container = $(this);
            
            // listen out for events and act accordingly    
            gum.events.bind(o.type+'_ad_added', function( e, id, ad ){ addItem( o, ad ); });              
            gum.events.bind(o.type+'_ad_removed', function( e, id ){ removeItem( o, id ); });
            gum.events.bind(o.type+'_ads_cleared', function( e ){ clearAll( o ); });
            
            cleanUp( o );
            
        });
    };
    
    function addItem( o, ad )
    {
        if ( isEmpty( o ) )
        {
            var item = gum.templates.render( o.adTemplate, ad );
            o.container.empty();
            o.container.append(gum.templates.render(o.contentTemplate, {'ads': item }));
            o.container.find('form.save').bind('submit', gum.utils.submitStarForm); // can't do this with live in IE7 :-(
        }
        else
        {
            var item = jQuery(gum.templates.render( o.adTemplate, ad ));
            item.find('form.save').bind('submit', gum.utils.submitStarForm); // can't do this with live in IE7 :-(
            
            o.container.find('li:first').before(item);
        }
        cleanUp( o );
    }
  
    function removeItem( o, id )
    {
        var selector = (o.adIdentifierFormat+id).replace(/:/, '\\:'); // backslash escape colons for jQuery
        o.container.find(selector).fadeOut(500, function(){
            
            $(this).remove();
            if ( isEmpty( o ) )
            {
               o.container.empty();
               o.container.append(o.noContentTemplate);
            }
            cleanUp( o ); 
        });
    }
    
    function clearAll( o )
    {
        o.container.find('*').animate({'opacity':'0'}, 1000, function(){
            var _this = $(this);
            o.container.empty();
            o.container.append(o.clearedTemplate);
        });
    }
    
    function isEmpty( o )
    {
        return ! o.container.find('li').length;
    }
    
    function cleanUp( o )
    {
        // do a general cleanup
        var li = o.container.find('li'),
            count = li.length;
        
        li.show();
        
        li.removeClass('odd even last-visible first last');
        li.filter(':first').addClass('first').end();
        li.filter(':odd').addClass('odd').end();
        li.filter(':even').addClass('even').end();
        
        li.eq( count > o.max ? o.max-1 : count-1 ).addClass('last').end();
        li.eq(o.max-1).addClass('last-visible').end();
        
        li.slice(o.max, count).hide();
    } 
    
})(jQuery);

// GT in-textbox labels plugin.
// Will accept a custom 'getText' function if necessary to control
// exactly how the plugin retrieves the label text.
;(function($){
    
    var defaults = {
        labeledClass        : 'gt-inline-label',
        withContentClass    : 'with-content',
        dataName            : 'defaultVal',
        getText             : function( field ){
            // default function for getting the text to be used as inline label.
            // can be overridden on a case-by-case basis
            var label = jQuery('label[for='+field.attr('name')+']:eq(0)', field.parents('form'));
            if ( label.size() ) return label.hide().text();
            else return null;
        }
    };
    
    $.fn.GT_inlineLabels = function( options )
    {
        return this.each(function(){
            
            var o           = $.extend(true, {}, defaults, options),
                field       = $(this),
                defaultData = o.getText( field );
            
            field.addClass(o.labeledClass);
            if ( defaultData )
            {
                field.data('defaultVal', defaultData);
                if ( field.val() == '' ) {
                    field.val(defaultData);
                }
                else if ( field.val() !== defaultData ) {
                    field.addClass(o.withContentClass);
                }
                
                field.bind('focus', function(){
                    var _this = $(this);
                    if ( _this.val() == defaultData ) _this.addClass(o.withContentClass).val(''); // value is the default value, clear it out
                }).bind('blur', function(){
                    var _this = $(this);
                    if ( _this.val() == '' ) _this.removeClass(o.withContentClass).val(defaultData);
                });

                field.parents('form').bind('submit', function(){
                    if ( field.val() == defaultData ) field.val(''); // remove default values before submitting
                });
            }
        });
    }
    
})(jQuery);


// GT Pager/ Carousel plugin
// pretty simple functionality, but extendable if necessary -
// init and swapSets functions can be extended outside the plugin
// to customise behaviour if necessary. 
;(function($) {
	
	var defaults = {
		perSet          : 8, // number of items per page
		startSet        : 1, // page to begin on - NOT zero indexed
		easing          : 'swing',
		speed           : 750,
		atEnd           : 'stop',
		wrapper_class   : 'GT-carousel-wrap'
	};
	
	$.fn.GT_pager = function( options )
	{
		return this.each(function(){
		
			var o = $.extend(true, {}, defaults, options), // set options
			    inner = o.inner = $(this);			
			
			inner.wrap('<div class="'+o.wrapper_class+'" />')
			
			o.outer = inner.parent('.'+o.wrapper_class);
			
			inner.bind( 'show.gtpager', function( e, pageNum ){ show( o, pageNum-1 ); });
			inner.bind( 'next.gtpager', function(){ next( o ); });
			inner.bind( 'prev.gtpager', function(){ prev( o ); });
			
			setUp( o );
		});
	};
	
	function setUp( o )
	{
		o.perSet	    = parseInt(o.perSet);
		o.items 		= o.inner.children();
		o.totalItems	= o.items.size();
		o.totalSets		= Math.ceil( o.totalItems / o.perSet );
		o.currentSet 	= parseInt(o.startSet) - 1;
		o.first 		= isFirstSet( o, o.currentSet );
		o.last 			= isLastSet( o, o.currentSet );
		o.pages			= [];
		o.totalSetsImagesLoaded = 0;
		
		if ( o.currentSet > o.totalSets-1 ) o.currentSet = o.totalSets-1;

        $.fn.GT_pager.init( o );
			
		for ( var i = 0; i < o.totalSets; i++ )
		{
			var startItem = i*o.perSet;
			o.pages[i] = o.items.slice( startItem, (startItem + o.perSet) );
		}
		
		show( o, o.currentSet );
		
		o.inner.trigger( 'initialized.gtpager', [o.currentSet+1, o.totalSets] );
	}
	
	function next( o )
	{
		switch( o.atEnd )
		{
		    case 'stop': show( o, (o.last ? o.totalSets - 1 : o.currentSet + 1) ); break; // stop when getting to last page 
			default: show( o, (o.last ? 0 : o.currentSet + 1) ); break;
		}
	}
	
	function prev( o )
	{
		switch( o.atEnd )
		{
		    case 'stop' : show( o, (o.first ? 0 : o.currentSet - 1) ); break; // stop when getting to first page 
			default: show( o, (o.first ? o.totalSets - 1 : o.currentSet - 1) ); break;
		}
	}
	
	function show( o, pageNum )
	{	
		if ( pageNum > o.totalSets-1 ) pageNum = o.totalSets-1;
		
		// if this set hasn't got images yet, add them
		if ( pageNum > o.totalSetsImagesLoaded) {
		    var currSetItem = pageNum * o.perSet;
		    var currSetLast = currSetItem + o.perSet - 1;
		    
		    while(currSetItem <= currSetLast) {
		        var link = $(o.items[currSetItem]).find('a');
		        
		        link.html('<img src="' + link.attr('data-thumbnail-path') + '" alt="" height="54" width="72" />');
		        
		        currSetItem += 1;
		    }
		    
		    o.totalSetsImagesLoaded += 1;
		}
				
		if ( ! o.pages[o.currentSet].is(':animated') )
		{
			o.inner.trigger( 'started.gtpager', o.currentSet+1 );
			
			$.fn.GT_pager.swapSets( o, pageNum, function(){
				
				o.currentSet = pageNum;
			
				o.first = isFirstSet( o, o.currentSet );
				o.last = isLastSet( o, o.currentSet );
			
				o.inner.trigger( 'finished.gtpager', [o.currentSet+1, o.first, o.last] );
						
			});
		}
	}
	
	// public setup and action functions, can override this if neccessary for custom transitions
	$.fn.GT_pager.init = function( o ){};
	
	$.fn.GT_pager.swapSets = function( o, setNum, onFinish )
	{
	    if ( o.atEnd == 'stop' )
	    {
            var leftpos = o.items.eq( setNum*o.perSet ).position().left * -1;
        	o.inner.animate( { left : leftpos }, o.speed, o.easing, onFinish );
        	onFinish();	        
	    }
	    else
	    {
	        // to be implemented if it is ever needed... :-)
	    }
	};
	
	// utility functions
	function isFirstSet( o, internalSetNum ) { return ( internalSetNum === 0 ); }
	function isLastSet( o, internalSetNum ) { return ( internalSetNum === o.totalSets-1 ); }
	
})(jQuery);

// Simple GT tabs implementation. Nothing fancy!
// Need to pass in individual tabs items (rather than the containing element)
// so that you can have disparate 'tabs' across a page (see the VIP for example).
// Uses a closure to keep references to tabs/panels intact.
;(function($){
    
    var defaults = {
        active_class : 'current',
        panel_id_attr : 'href'
    };
    
    $.fn.GT_tabs = function( options )
    {
        var o           = $.extend(true, {}, defaults, options),
            panelsArray = [],
            panels      = $({});
            
        this.each(function(){

            var tab     = $(this),
                tablink = tab.find('> a');
            
            if ( tablink.length && tablink.attr(o.panel_id_attr) )
            {
                var panelID = tablink.attr(o.panel_id_attr).replace('#',''),
                    panel   = $('#'+panelID);  

        
                if ( panel.length ) panelsArray.push('#'+panelID);
            
                panel.click(function(e){
                    // when the panel is within the tab li, stop click events within it closing the panel
                    e.stopPropagation();
                })
            
                tab.click(function(){
                    panel.trigger(tab.hasClass(o.active_class) ? 'hide' : 'show');
                    return false;
                });
            
                function hide(){
                    tab.removeClass(o.active_class);
                    panel.hide(); 
                }
            
                function show(){
                    panels.trigger('hide');
                    tab.addClass(o.active_class);
                    panel.show();
                }
            
                tab.bind('hide', hide);
                tab.bind('show', show);
                panel.bind('hide', hide);
                panel.bind('show', show);
                                                  
            }

        });
        
        if ( panelsArray.length ) panels = $(panelsArray.join(','));
             
        return this;
    }
    
})(jQuery);

// Very simple tooltip plugin to generate tooltips
// for the gumtree site - all styling done via CSS!
;(function($){
    
    var defaults = {
        tooltip_class       : 'gt-tooltip',
        tooltip_class       : 'gt-tooltip',
        tooltip_content_class : 'gt-tooltip-content',
        tooltip_arrowbox_class : 'gt-tooltip-arrowbox', 
        theme_class         : 'gt-tooltip-theme-default',
        arrow_border_class  : 'gt-tooltip-arrow-border',
        arrow_class         : 'gt-tooltip-arrow',
        content             : '',
        left_offset         : 0,
        top_offset          : 0,
        show_delay          : 300,
        hide_delay          : 200,
        speed               : 100
    },
    showTimers = [],
    hideTimers = [];
    
    $.fn.GT_tooltip = function( options )
    {                
        return this.each(function(){
                        
            var o       = $.extend(true, {}, defaults, options),
                item    = $(this);
                
            o.ref =	new Date().getTime();
            o.item = item;
    
            create( o );
                
            item.hover(function(){
                show( o ); 
            }, function(){
                hide( o );
            });
            
            o.tooltip.hover(function(){
                clearTimeout(hideTimers[o.ref]);
            }, function(){
                hide( o );
            });
            
        });
    }
    
    function show( o, position )
    {
        var position = o.item.offset();
     
        var pos = {};
        pos.top = position.top - o.outerHeight - o.top_offset;
        pos.left = position.left - o.outerHalfWidth + o.left_offset + o.itemWidth;
        o.tooltip.css({top:pos.top,left:pos.left});
        
        showTimers[o.ref] = setTimeout(function(){
            
            o.tooltip.css('z-index',10000);            
            if ( o.speed ) o.tooltip.stop().fadeTo(o.speed, 1, function(){
                o.tooltip.show();
            });
            else o.tooltip.show();
            
        }, o.show_delay);
    }
    
    function hide( o )
    {
        clearTimeout(showTimers[o.ref])
        hideTimers[o.ref] = setTimeout(function(){
            
            if ( o.speed ) o.tooltip.stop().fadeTo(o.speed, 0, function(){
                o.tooltip.hide();
            });
            else
            {
                o.tooltip.hide();
            } 
            
            o.tooltip.css('z-index','0'); // avoid cursor 'flashing' in FF3.6
            
        }, o.hide_delay);
    }
    
    function create( o )
    {
        o.inner = $('<div class="'+o.tooltip_content_class+'"></div>');
        o.tooltip = $('<div class="'+o.tooltip_class+' '+o.theme_class+ '"></div>');
        
        o.tooltip.append($('<div class="'+o.tooltip_arrowbox_class+'"></div>').html('<div class="'+o.arrow_border_class+'"></div><div class="'+o.arrow_class+'"></div>'));
        
        o.inner.html(o.content);
        $('body').append(o.tooltip.prepend(o.inner));
                      
        o.tooltip.find('.'+o.arrow_border_class+', .'+o.arrow_class).css('left',(o.tooltip.outerWidth() / 2)-8) ;
        
        o.tooltip.hide();
        
        o.outerHeight = o.tooltip.outerHeight();
        o.outerHalfWidth = o.tooltip.outerWidth() / 2;
        o.itemWidth = o.item.width() / 2;
        
        o.tooltip.bind('hide', function(){
            hide(o);
        })
    }
    
})(jQuery);

function hideModalBox() {
    $('#overlay')
		.animate({'opacity':'0'}, 400, function() {
    		$('.modal-content.show').removeClass('show');
			$(this).remove();
		});
    // if the callback is defined, call it
    if (typeof hideModalCallback == 'function') {
        hideModalCallback();
    }
    $('.modal-content.show').removeClass('show');
    
}
function showModalBox (targetDiv, e) {
    $('body').append('<div id="overlay"></div>');

    if (targetDiv.find('.inner').length < 1) {
        targetDiv.wrapInner('<div class="inner"></div>');
    }
    
    $('#overlay')
          .css('height', $(document).height()+'px')
          .animate({'opacity':'1'}, 400, function () {
              // work out offset to the document
              var leftOffset = parseInt($(window).width()/2) - parseInt(targetDiv.width()/2) + $(window).scrollLeft();
              var topOffset = parseInt($(window).height()/2) - parseInt(targetDiv.height()/2) + $(window).scrollTop();
              // move to end of body tag to sort out z-index issues
              targetDiv
                  .css('left', leftOffset+'px')
                  .css('top', topOffset+'px')
                  .addClass('show');
               
      });
    
      var leftOffset = parseInt($(window).width()/2) - parseInt(targetDiv.width()/2) + $(window).scrollLeft();
        var topOffset = parseInt($(window).height()/2) - parseInt(targetDiv.height()/2) + $(window).scrollTop();
        // move to end of body tag to sort out z-index issues
        targetDiv
            .css('left', leftOffset+'px')
            .css('top', topOffset+'px')
            .addClass('show');
    
    // hide on click outside
    $(document).one('click', function(){
             hideModalBox();
             return false;
         });
    targetDiv.click(function(e){
        e.stopPropagation();
    });
}


/* Cookies */
function createCookie(name,value,days,domain) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    var cookie = name+"="+value+expires+"; path=/";
    if(domain) cookie += "; domain=" + domain;
    document.cookie = cookie;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function getCookie(c_name) {
    if (document.cookie.length>0) {
        c_start=document.cookie.indexOf(c_name + "=");
        if (c_start!=-1) { 
            c_start=c_start + c_name.length+1;
            c_end=document.cookie.indexOf(";",c_start);
            if (c_end==-1) c_end=document.cookie.length;
            return unescape(document.cookie.substring(c_start,c_end));
        } 
    }
    return "";
}

function eraseCookie(name) {
    var components = document.location.host.split('.');

    while(components.length) {
        createCookie(name,"",-1,components.join('.'));
        components.shift();
    }
}

    (function(jQuery) {

    	jQuery.gtcookie = {
    		permanent: {
    			attr: function( name, value ) {
    				return cookie_attr( 'permanent', name, value );
    			},
    			removeAttr: function( name ) {
    				return cookie_remove_attr( 'permanent', name );
    			},
    			id: function() {
    				return cookie_id( 'permanent' );
    			}
    		},
    		session: {
    			attr: function( name, value ) {
    				return cookie_attr( 'session', name, value );
    			},
    			removeAttr: function( name ) {
    				return cookie_remove_attr( 'session', name );
    			},
    			id: function() {
    				return cookie_id( 'session' );
    			}
    		}
    	};

    	var cookie_name = {
    		permanent: 'gt_p',
    		session: 'gt_s'
    	};

    	var cookie_domain = '.' + location.hostname.replace( /[^.]*\.([^:\/]*).*/, "$1" );

    	function cookie_id( scope ) {
    		if ( typeof scope == 'undefined' || ( scope != 'permanent' && scope != 'session' ) ) {
    			return;
    		};

    		var content = read_cookie( cookie_name[scope] );
    	        if ( content == null ) {
    			content = write_cookie( scope );
    		};

    		return extract_id( content );
    	};

    	function cookie_attr( scope, name, value ) {
    		if ( typeof scope == 'undefined' || ( scope != 'permanent' && scope != 'session' ) || typeof name == 'undefined' ) {
    			return;
    		};

    		if ( typeof value == 'undefined' ) {
    			return get_cookie_attr( scope, name );
    		} else {
    			return set_cookie_attr( scope, name, value );
    		};
    	};

    	function cookie_remove_attr( scope, name ) {
    		if ( typeof scope == 'undefined' || ( scope != 'permanent' && scope != 'session' ) || typeof name == 'undefined' ) {
    			return;
    		};

    		return set_cookie_attr( scope, name );
    	};



    //    alert(get_cookie_attr('permanent','updated'));

    	function get_cookie_attr( scope, name ) {
    		var content = read_cookie( cookie_name[scope] );

    		if ( content != null )
    		{
    			var attr = extract_attributes( content );
    			return attr[name];
    		};
    	};

    	function set_cookie_attr( scope, name, value ) {
    		var content = read_cookie( cookie_name[scope] );
    		var id = null;
    		var attr = new Object();
    		if ( content != null ) {
    			id = extract_id( content );
    			attr = extract_attributes( content );
    		}
    		if ( typeof value == 'undefined' ) {
    			delete attr[name];
    		} else {
    			attr[name] = value;
    		};

    		return write_cookie( scope, id, attr );
    	};

    	function read_cookie(name) {
    		var nameEQ = name + "=";
    		var ca = document.cookie.split(';');
    		for(var i=0;i < ca.length;i++) {
    			var c = ca[i];
    			while (c.charAt(0)==' ') c = c.substring(1,c.length);
    			if (c.indexOf(nameEQ) == 0) return unescape(c.substring(nameEQ.length,c.length));
    		}
    		return null;
    	};

    	function write_cookie( scope, id, attr ) {
    		var days = ( scope == 'session' ) ? 0 : 1825;
    		if (days) {
    			var date = new Date();
    			date.setTime(date.getTime()+(days*24*60*60*1000));
    			var expires = date.toGMTString();
    		} else {
    			var expires = "";
    		}
    		var id = id || generate_session_id();
    		var attr_str = build_attr_str( attr );

    		document.cookie = cookie_name[scope] + '=' + id + '|' + attr_str + '; expires=' + expires + '; path=/; domain=' + cookie_domain;

    		return id;
    	};

    	function generate_session_id(){
    	        var chars = "abcdef0123456789";
    		var pieces = [];
    		for( var i = 0; i < 32; i++ ){
    			var offset = Math.floor( Math.random() * chars.length );
    			pieces.push( chars.substr( offset, 1 ) );
    		}
    		return pieces.join("");
    	};

    	function extract_id( content ) {
    		var ida = content.split('|',1);
    		return ida[0];
    	};

    	function extract_attributes( content ) {
    		var ida = content.split('|');
    		var attr = new Object();
    		for ( var i = 1; i < ida.length; i++ ) {
    			if ( ida[i] != '' ) {
    				var attri = ida[i].split(':',2);
    				attr[attri[0]] = $.base64Decode( attri[1] );
    			};
    		};
    		return attr;
    	};

    	function build_attr_str( attr )
    	{
    		var attr_str = '';
    		if ( typeof attr == 'object')
    		{
    			var attr_array = new Array();
    			$.each( attr, function( k, v ) {
    				attr_array.push( k + ':' + $.base64Encode( v + '') );
    			});
    			attr_str = attr_array.join('|');
    		}

    		return attr_str;
    	};


    }) (jQuery);

    $(document).ready( function() {
    	var p_id = $.gtcookie.permanent.id();
    	var s_id = $.gtcookie.session.id();
    	if ( ! $.gtcookie.permanent.attr('rfts') )
    	{
    		$.gtcookie.permanent.attr('rf',document.referrer);
    		$.gtcookie.permanent.attr('rfts',new Date().getTime());
    	};
    });
/* End Cookies */


/* 
    Title:      Gumtree Global Parameters & Functions
    Copyright:  2008-2009 Gumtree.com
    Date:       Once Upon A Time in 2010
    Authors:    Antonio Lulic/Adam Perfect/Desigan Chinniah/David Edwards
    Email:      anlulic@ebay.com
*/

gum.constants = {

    // cookies
    COOKIE_DEFAULT_LIFETIME     : 365,
    COOKIE_GUMTREE_DOMAINS      : [ 'gumtree.com', 'gumtree.ie' ],
    COOKIE_VIEWED_IDS           : 'recent_ids',
    COOKIE_SAVED_IDS            : 'saved_ids',
    COOKIE_CHUNK_SPLIT          : /[\s]+/,
    
    // saved stars
    STAR_IS_SAVED_CLASS         : 'remove',
    STAR_SAVE_SUCCESS           : 'Saved!',
    STAR_REMOVE_SUCCESS         : 'Removed!',
    STAR_SAVE_HINT              : 'Save',
    STAR_REMOVE_HINT            : 'Remove',
    
    // saved ads 
    SAVED_ADS_MAX               : 6,
    TITLE_MAX_CHARS             : 24,
    
    // modals
    MODAL_OVERLAY_ID            : 'overlay',
    MODAL_BOX_CLASS             : 'modal-content',
    MODAL_CLOSE_CLASS           : 'modal-close'

}

// HTML 'templates'  ////////////

// footer saved ads 
gum.templates.footerSavedAd = '<li class="ad-<#= id #>"><a href="<#= link #>" title="<#= title #>"><span class="thumbnail small-thumb"><img width="72" height="54" src="<#= img #>"></span> <span class="title"><#= shorttitle #>&hellip;'+'</span><span class="location"><#= location #></span></a><a href="#" class="remove-ad" data-id="<#= id #>" data-type="save">remove</a></li>';

gum.templates.footerNoAds = '<div class="empty"><h3>No saved ads</h3><p>If you save any ads, they\'ll show up here.</p></div>';

gum.templates.footerHasAds = '<h3>Latest saved ads <a href="/cgi-bin/my_saved_ads.pl">View all</a></h3><ol class="carousel-ads"><#= ads #></ol><a href="/cgi-bin/my_saved_ads.pl" class="clear-saved-ads">Clear saved ads</a>';

gum.templates.footerAdsCleared = '<div class="empty"><h3>Saved ads cleared</h3><p>Your saved ads have been cleared. Any ads you save from now on will appear in this box.</p></div>';

// header saved ads dropdown
gum.templates.headerSavedAd = '<li class="hlisting with-price saved-listing ad-<#= id #>"><div class="thumbnail leader"><a href="<#= link #>"><img src="<#= img #>"></a></div><div class="info"><p class="title"><a href="<#= link #>" rel="bookmark" class="summary"><#= shorttitle #></a></p><p><form data-id="<#= id #>" class="save" action="#" method="post"><input type="submit" value="Save" class="save-ad save-<#= id #>" /></form>&nbsp;<span class="price"><#= price #></span>&nbsp;<span class="locality"><#= location #></span></p></li>';

gum.templates.headerNoAds = '<div class="empty"><p>No saved ads</p><p>If you save any ads, they\'ll show up here.</p></div>';

gum.templates.headerHasAds = '<p>Showing 1-<span class="saved-ads-max">0</span> of your saved ads</p><ol class="listing with-thumbnails"><#= ads #></ol><a href="/cgi-bin/my_saved_ads.pl" class="button primary"><span>View all saved ads</span></a>';

gum.templates.headerAdsCleared = '<div class="empty"><p>Saved ads cleared</p><p>Your saved ads have been cleared. Any ads you save from now on will appear in this box.</p></div>';

// footer recently viewed ads 
gum.templates.footerViewedAd = '<li class="ad-1:<#= id #>"><a href="<#= link #>" title="<#= title #>"><span class="thumbnail small-thumb"><img width="72" height="54" src="<#= img #>"></span> <span class="title"><#= shorttitle #>&hellip;'+'</span><span class="location"><#= location #></span></a><a href="#" class="remove-ad" data-id="<#= id #>" data-type="save">remove</a></li>';

gum.templates.footerNoViewedAds = '<div class="empty"><h3>No recently-viewed ads</h3><p>When you look at an ad, we&#8217;ll keep a link to it so you&#8217;ve got easy access to your recenty viewed ads.</p><p>Don&#8217;t worry, you can clear your ad viewing history whenever you want.</p></div>';

gum.templates.footerHasViewedAds = '<h3>Recently viewed ads</h3><ol class="carousel-ads"><#= ads #></ol><a href="#" class="clear-history-link">Clear history</a>';

gum.templates.footerViewedAdsCleared = '<div class="empty"><h3>Viewed ads cleared</h3><p>When you look at an ad, we&#8217;ll keep a link to it so you&#8217;ve got easy access to your recenty viewed ads.</p></div>';


$(document).ready( function() {

    var docBody        = $('body'),
        ads            = gum.data.ads
        cnst           = gum.constants,
        tmpl           = gum.templates,
        ev             = gum.events,
        saveAdForm     = $('form.save'),
        savedAdsCounts = $('.saved-ads-count');

    
    docBody.addClass('JSlive'); // DIFFERENT to hasJS - hasJS is added earlier than this!
    
    if ( jQuery.browser.webkit ) docBody.addClass('webkit'); // sorry about this :-(
    
    /* Autocomplete */
    if ( typeof cities == 'object' ) {
        $("#search_location").autocomplete(cities, {selectFirst: false}).bind('focus', function(){
            $(this).select(); // automatically select text when focus is on textbox
        });
    }
    
    // Search submit
    $('form#search').submit(function(){
        var searchLoc = $('#search_location');
        if (searchLoc.val().match(/^uk/i)) {
            searchLoc.val('United Kingdom');
        }
    });
    
    // move adsense scripts in to correct position
    // $('.adsense-wrapper').each(function(){
    //     var _this = $(this),
    //         ad_id = this.id.replace(/-wrapper$/,'');
    //         _this.append($('#adloader #'+ad_id+' .adsense')).css('height','auto');  
    // });
    
    // lazy load images
    if (!$('body').hasClass('ie')) {
        $(".hlisting img").lazyload({ effect : "fadeIn" });
    }
    
     //////// carousels //////////////
    
    var carousel = $('div#spotlight-ads ul.featured-ads');
    
    if ( carousel.length )
    {
        carousel.GT_pager();
    
        $('.carousel-pagination a').click(function(){
            carousel.trigger(this.rel+'.gtpager'); // prev/next functionality
            return false;
        });
        
        carousel.bind('finished.gtpager', function( e, currentSet, isFirst, isLast ){
            
            var next = $('.carousel-pagination a.next'),
                prev = $('.carousel-pagination a.prev');
                
            if ( isFirst ) prev.addClass('prev-disabled');
            else prev.removeClass('prev-disabled');
            
            if ( isLast ) next.addClass('next-disabled');
            else next.removeClass('next-disabled');
            
        });
    }
    
    //////// DART placements //////////////
    var dart_placements = $('div.dart-placement');
    

    if (dart_placements.length) {

        dart_placements.each(function(){
            
            var placement = $(this);
            
            gum.log('Async DART for ' + placement.attr('id'));
            
            if (typeof(ord) == 'undefined') {
                ord = Math.random()*100000000000000000;
            }
            if (typeof(dc_tile) == 'undefined') {
                dc_tile = 1;
            }
            dc_ref = escape(window.location);
            var ad_script_path = '/adj/'+placement.attr('data-dart-site')+'/'+placement.attr('data-dart-zone')+';l2='+placement.attr('data-dart-12')+';l3='+placement.attr('data-dart-13')+';l4='+placement.attr('data-dart-14')+';kw='+placement.attr('data-search-terms')+';pos='+placement.attr('data-pos')+';sz='+placement.attr('data-dart-size')+';tile=' + dc_tile + ';'+placement.attr('data-cat-field')+'='+placement.attr('data-cat-id')+';page_type='+placement.attr('data-page-type-name')+';site='+placement.attr('data-version')+';mtfIFPath=/common/;' + 'dc_ref=' + dc_ref;
            
            dc_tile++;
        
            //take the refurl of the page
            var referrer_url = escape(document.referrer);
            var ad_script_src  = "http://ad.uk.doubleclick.net" + ad_script_path + ";dc_ref=" + referrer_url + ";";
            gum.log(ad_script_src);

            var dartScriptTag = "<script src=\""+ad_script_src+"\"></script>";

            placement.html(writeCapture.sanitize(dartScriptTag));
            
        });

        activateAdPlacements();
    }
    
    //////// saved / viewed ads interactions //////////////
    
    saveAdForm.find('label').css({opacity:0});
    
    $('#saved-ads').adList({
        type                : 'saved',
        max                 : cnst.SAVED_ADS_MAX,
        adTemplate          : tmpl.footerSavedAd,
        contentTemplate     : tmpl.footerHasAds,
        noContentTemplate   : tmpl.footerNoAds,
        clearedTemplate     : tmpl.footerAdsCleared
    });
    
    $('#header-saved-ads').adList({
        type                : 'saved',
        max                 : cnst.SAVED_ADS_MAX,
        adTemplate          : tmpl.headerSavedAd,
        contentTemplate     : tmpl.headerHasAds,
        noContentTemplate   : tmpl.headerNoAds,
        clearedTemplate     : tmpl.headerAdsCleared
    });
    
    $('#recently-viewed').adList({
        type                : 'viewed',
        max                 : cnst.SAVED_ADS_MAX,
        adTemplate          : tmpl.footerViewedAd,
        contentTemplate     : tmpl.headerHasViewedAds,
        noContentTemplate   : tmpl.footerNoViewedAds,
        clearedTemplate     : tmpl.footerViewedAdsCleared
    });

    // loop through all saved ads and mark them as saved     
    jQuery.each( ads.getSavedIds(), function( i, id ){
        var ad = $('input.save-'+id);
        if ( ad.length ) gum.utils.setStarStatus( ad.closest('form'), 'saved', true );
    });
    
    // bind any ad count areas to the 'saved_ads_updated' event
    // so the automatically update
    ev.bind('saved_ads_updated', function( e, num ){
        savedAdsCounts.text(num);
        $('#header-saved-ads .saved-ads-max').text( num > cnst.SAVED_ADS_MAX ? cnst.SAVED_ADS_MAX : num );
    });
    
    // when the ads are cleared, set any stars back to unsaved state
    ev.bind('saved_ads_cleared', function( e ){
        $('form.save.remove').each(function(){
            gum.utils.setStarStatus( $(this), 'removed' );
        });
    });
    
    // if we are on the 'saved ads' page, fade the row out when an ad is removed
    // or all the ads are cleared
    if ( $('#my-saved-ads-list').length )
    {
        ev.bind('saved_ad_removed', function( e, id ){
            $('input.save-'+id).closest('li').fadeOut(); // remove item
        });
        ev.bind('saved_ads_cleared', function( e ){
            $('#my-saved-ads-list').fadeOut(); // remove whole list
        });
    }

    // when an ad is saved or unsaved, find all stars and set their status appropriately
    ev.bind('saved_ad_added saved_ad_removed', function( e, id, details ){
        var ad = $('input.save-'+id);        
        if ( ad.length ) gum.utils.setStarStatus( ad.closest('form'), ads.isSaved(id) ? 'added' : 'removed' );
    });
    
    // deal with submissions of the saved ad form
    saveAdForm.bind('submit', gum.utils.submitStarForm);
    
    // stop click propagation - bind is done on form submit
    saveAdForm.find('input.save-ad').click(function(e){
        e.stopPropagation();
    });
    
    $('.clear-saved-ads').live('click', function(){
        return ! ads.clearSaved();
    });
    
    $('.clear-history-link').click(function(){
        return ! ads.clearViewed();
    });
    
    // removing individual viewed/saved ads in the footer
    $('.remove-ad').live('click', function(){
        var _this = $(this);
        return ! ads['un'+_this.attr('data-type')](_this.attr('data-id'));
    });
    
    $('.primary li.hlisting').hover(function(){
        
        var _this = $(this),
             form = _this.find('form');
             
             form.find('label').text( form.hasClass('remove') ? cnst.STAR_REMOVE_HINT : cnst.STAR_SAVE_HINT )
                 .stop().fadeTo(200, 1);
    
        }, function(){
            $(this).find('form label').stop().fadeTo(600, 0);
    });

    gum.data.ads.init(); // run the ads init function - needs to be AFTER events are bound (as above)
    
    /////////////////////////////////
    
    /* Retrace footer */
    
    $('#my-gumtree-list li').GT_tabs({'active_class':'active'});
    
    /* End Retrace footer */
    
    // Show/hide toggles
    $('.toggle').each(function() {
        var targetelement = $($(this).attr('href'));
        if(targetelement.hasClass('initial-show')) {
            $(this).addClass('active');
            targetelement.addClass('show');
        } else {
            targetelement.addClass('hidden');
        }
    });
    
    $('.toggle').live("click", function(){
        $($(this).attr('href')).toggleClass('hidden');
        $($(this).attr('href')).toggleClass('show');
        $(this).toggleClass('active').blur();
        return false;
    });
    
    // Modal pop-ups
    $('.modal-content').each(function(){
       $(this).appendTo('body');
       $(this).find('h2').after('<p class="close"><a href="#" class="modal-close">Close</a></p>');
    });
    $('a.modal-trigger').click(function(e) {
        var targetDivId = $(this).attr('href').match(/#(.+)/)[0];
        var targetDiv = $(targetDivId);
        
        if (targetDiv.hasClass('show')) {
            hideModalBox();
        }
        else {
            showModalBox(targetDiv, e);
        }
        return false;
    });
    $('div.modal-content p.close a').click(function() {
        hideModalBox();
        return false;
    });
    
    // Sidebar full/truncated location/category toggling
    
    $('.hierarchical-list .see-full a').click(function(e) {
        e.preventDefault();
        $(this).closest('ul').addClass('hidden').next('ul').removeClass('hidden');
    });
    $('.hierarchical-list .see-truncated a').click(function(e) {
        e.preventDefault();
        $(this).closest('ul').addClass('hidden').prev('ul').removeClass('hidden');
    });
    
    // sidebar input fields
    var inputs = $('.secondary .form input.text');
    if ( inputs.length ) inputs.GT_inlineLabels(); // enable default val hide/show
    
    // Search form
    var searchinputs = $('form#search input.text');
    if ( searchinputs.length ) searchinputs.GT_inlineLabels({ 
        getText : function( field ){
            var label = $('label[for='+field.attr('name')+']:eq(0) span', field.parents('form'));
            if ( label.size() ) return label.hide().text().replace(/\(|\)/g,'');
            else return null;
        }
    }); // enable default val hide/show
    
    
    // TODO - make not hacky
    $('#global-search-submit').click(function(){
        $('#refine-attributes-searchform').submit();
    })
    //////////////// sidebar price range textbox validation //////////////// 

    $('#refine-attributes-searchform').bind('submit',function(){
        
        if ($('input[name=max_price]', this).val() != '' && $('input[name=min_price]', this).val() != ''
            &&
            $('input[name=max_price]', this).val() != undefined && $('input[name=min_price]', this).val() != undefined
            ) {
        
            var _this = $(this),
                max = ~~(1*$('input[name=max_price]', this).val()),
                min = ~~(1*$('input[name=min_price]', this).val()),
                formlist;
                
        
            if ( min > max || ( min === 0 && max === 0 ) )
            {
                // form not filled in correctly
                _this.find('p.error').remove();
                _this.find('ol#price-range').before('<p class="error">Please check you\'ve typed the minimum price correctly and you have used only numbers</p>');
                return false;
            }
        }    
    });
    
    // make tabbed interface for the 'link-farm' footer //////////////////
    
    var qlinks = $('#quicklinks');
    
    if ( qlinks.length )
    {
        var sections = qlinks.find('.section');
        if ( sections.length )
        {
            var tabs = $('<ul />').addClass('tabs');
            sections.each(function(){
                
                var _this = $(this),
                    title = _this.find('h3');
                
                var link = $('<li class="'+_this.attr('id')+'"><a href="#'+_this.attr('id')+'">'+title.text()+'</a></li>').bind('click', function(){
                    var _self       = $(this),
                        siblings    = _self.siblings('li');
                    
                    if ( _self.hasClass('current') )
                    {
                        _self.removeClass('current');
                        siblings.andSelf().filter(':not(:last)').addClass('split');
                        sections.hide();
                        tabs.addClass('closed');
                    }
                    else
                    {
                        _self.addClass('current');
                        siblings.removeClass('current split');
                        siblings.filter(':not(:last):not(:eq('+(_self.index()-1)+'))').addClass('split');
                        sections.hide();
                        _this.show();
                        tabs.removeClass('closed');
                    }
                    
                    return false;
                });
                
                tabs.append(link);
                title.remove();
            });
            qlinks.prepend(tabs);
        }
        
        var firsttab = qlinks.find('li:first').trigger('click');        
        if ( ! $('body.uk').length ) firsttab.trigger('click');
    }
    
    ////// tooltips ///////////////////////
     
     var featuredHelp = $(".listing .featured-help").click(function(){return false});
     featuredHelp.GT_tooltip({
         content       :   $('#about-featured-ads').html(),
         theme_class   :   'gt-tooltip-theme-info',
         top_offset    : -10,
         left_offset   : -7
     });
     
      var spotlightHelp = $("#spotlight-ads a.learn-more").click(function(){return false});
      spotlightHelp.GT_tooltip({
          content       :   $('#about-spotlight-ads').html(),
          theme_class   :   'gt-tooltip-theme-info',
          top_offset    : -10
      });
     
       var spotAd = $("li.featured-ad a");
        if ( spotAd.length )
        {
           spotAd.unbind('hover');
           
           spotAd.each(function(){
               var _this    = $(this),
                   title    = _this.attr('title'),
                   price    = _this.attr('data-price'),
                   location = _this.attr('data-location'),
                   linkUrl  = _this.attr('href');
                   
                 _this.GT_tooltip({
                     content       :   '<div class="tooltip-text"><a href="#" class="close-tooltip">close</a><h2><a href="'+linkUrl+'">'+title+'</a></h2><p><span class="price">'+price+'</span> <span class="location">'+location+'</span></p></div>',
                     theme_class   :   'gt-tooltip-theme-spotlight',
                     top_offset    : -15,
                     left_offset    : 2
                 }); 
           });
       }
       
       $('.close-tooltip').live('click', function(){
           var _this = $(this);
           _this.parents('.gt-tooltip').eq(0).trigger('hide');
           return false;
       });
    
    ///// header bar /////
    
    if ( ! docBody.hasClass('ie6') )
    {
        var headerActions      = document.getElementById('main-actions'),
            myGum              = document.getElementById('my-gumtree'),
            adForms            = $('.manage-ad-login, .manage-ad-reminder', headerActions),
            footerAdForms      = $('.manage-ad-login, .manage-ad-reminder', myGum),
            headerTabs         = $('#your-saved-ads, #manage-ads-link, #country-picker', headerActions),
            reminderForm       = $('.manage-ad-reminder', headerActions),
            footerReminderForm = $('.manage-ad-reminder', myGum);
        
        headerTabs.GT_tabs({panel_id_attr:'data-panel'}); // tabify...
        
        $("#utilities .panel").bind( "clickoutside", function(event){
            headerTabs.each(function(){
                if ( $(this).hasClass('current') ) $(this).trigger('click');
            });
           
            if ( reminderForm.is(':visible') ) adForms.toggle();
            if ( footerReminderForm.is(':visible') ) footerAdForms.toggle();
        });
    
        $('.forgotten-password, .back', headerActions).click(function(){
            adForms.toggle();
            return false;
        });
        
        $('.forgotten-password, .back', myGum).click(function(){
            footerAdForms.toggle();
            return false;
        });
    }
    
    $('#your-gumtree a#your-gumtree-link').click(function(){
        var thisLink = $(this);
        if (thisLink.hasClass('active')) {
            thisLink.removeClass('active');
            $(thisLink.attr('href')).removeClass('show');
            $('#your-gumtree-options .panel').hide();
            $('#your-gumtree-options li').removeClass('current');
        } else {
            thisLink.toggleClass('active');
            $(thisLink.attr('href')).toggleClass('show');

            // hide on click outside
            $(document).one('click', function(){
                     thisLink.removeClass('active');
                     $(thisLink.attr('href')).removeClass('show');
                     return true;
                 });
            thisLink.click(function(e){
                e.stopPropagation();
            });
        }
        
        return false;
    });

    /// IE6 fixes //////////////////
    
    // ie fixes 
    if ( docBody.hasClass('ie6') ) $('span.active.abundance-count').addClass('active-abundance-count');

    if ( $('body').hasClass('ie') )
    {
        gum.utils.addRoundie( '#my-gumtree', 'tr tl br bl', 'my-gumtree-wrapper' );
        gum.utils.addRoundie( '.uk #inner-head', 'tr tl br bl' );

        if ( !$('body').hasClass('uk') && !$('body').hasClass('promo') ) gum.utils.addRoundie( '#page', 'tr tl br bl' );
        else
        {
            // gum.utils.addRoundie( '#page', 'br bl' ); 
            gum.utils.addRoundie( '#main-wrapper', 'tl tr' );
        }
    }   
    
});
