/* 
	Title:		Gumtree Global Parameters & Functions
	Copyright:	2008-2009 Gumtree.com
	Date:		16 July 2009
	Authors:	Antonio Lulic/Adam Perfect/Desigan Chinniah/David Edwards
	Email:		anlulic@ebay.com
*/

// Before the DOM has loaded

	var ie = 'NA';
	if ($.browser.msie) {
		ie = IEVersion();
	}
	//	IE6/7 Rounded Corners (Search box, Headings, Main action links, boxouts)
	if (ie.DocMode < 8) {
		DD_roundies.addRule('div.global form#search', '0 10px 10px 0');
		DD_roundies.addRule('form#search button.submit', '4px');
		DD_roundies.addRule('.section, .column h2', '10px');
		DD_roundies.addRule('div#sidebar div.panel.top','10px 10px 0 0');
		DD_roundies.addRule('div#sidebar div.panel.bottom','0 0 10px 10px');
		DD_roundies.addRule('ul#locale', '12px 0 0 12px');
		DD_roundies.addRule('div#other-gumtrees h3#uk-ireland', '9px 9px 0 0');
		DD_roundies.addRule('.directory', '10px');
		DD_roundies.addRule('.boxout', '10px');
		DD_roundies.addRule('.boxout h3', '9px 9px 0 0');
		DD_roundies.addRule('div.quotes blockquote');
		DD_roundies.addRule('h5 strong.urgent, div.posting-description strong.urgent, form#post-an-ad strong.urgent', '3px');

//		Global Nav main actions
		DD_roundies.addRule('div#global-nav #main-actions li.primary, div#global-nav #main-actions li.primary a', '0 0 10px 0');

//		Homepage Only
		DD_roundies.addRule('#gumtree-forums, div.home #main-actions li.secondary, div.home #main-actions li.secondary a, div.home #main-actions li.primary, div.home #main-actions li.primary a', '12px');
		DD_roundies.addRule('div.home form#search', '4px');
		DD_roundies.addRule('#gumtree-forums h2', '0');
		DD_roundies.addRule('div#spotlight', '10px');
		DD_roundies.addRule('div#spotlight h2', '8px 8px 0 0');
	}

// After the DOM has loaded
$(document).ready( function() {
	if ($.browser.msie && $.browser.version == 8) {
		$('div#header.global form#search')
			.css('position','absolute');
	}

//	IE6 PNG Transparency
//	Commented out, as we've fallen back to a transparent GIF for the logo under IE6.
//	To reenable this, uncomment this section and the <script> tag for DD_belatedPNG in head_default.ttk
/*
	if ($.browser.msie && $.browser.version < 7) {
		$("img[src$='png']").DD_belatedPNG();
		$(this).find('*').each(function(){
			if ($(this).css('background-image').indexOf(".png")!=-1){
				$(this).DD_belatedPNG();
			}
		});
	}
*/

//	Fix buttons with background images in FireFox 2 (by removing the images)
	if ($.browser.mozilla && $.browser.version.substr(0,3)=='1.8') {
		$('ul#main-actions li.secondary a,form#search button.submit').css({'background':'#84c667'});
		$('ul#main-actions li.primary a').css({'background':'#ff8814'});
	}
	
//	Prevent null searches
	$('form#search button.submit').click(function() {
		if ($('form#search input.text').val() == '') {
			alert('Please enter some terms that you\'d like to search for.');
			$('form#search input.text').focus();
			return false;
		}
	});
	
//	Fetch a random tagline keyword - TODO: Move into Perl, not JS
	var taglineWords = [
		'white tuxedos',
		'vintage records',
		'warm weather',
		'pet lizards',
		'free stuff',
		'Spanish lessons',
		'opera singers',
		'Subbuteo sets',
		'Scottish kilts',
		'coffee makers',
		'theatre tickets',
		'free stuff',
		'yellow submarines',
		'cinema posters',
		'Persian cats',
		'porcelain dolls'
	];
    var taglineIndex = Math.floor(Math.random()*taglineWords.length);
    $('#random-tagline-word').text(taglineWords[taglineIndex]);

//	Clear search field on focus, empty on blur
	var keywordsLabel = $('form#search label.example');
//	Show example label on page load if the field is empty
	if ($('form#search input.text').val() == '') {
		keywordsLabel.removeClass('hidden');
	}

//	Clicking the example label focusses on the input
	$('form#search label.example').click( function() {
		$('form#search input.text').focus();
	});
	$('form#search input.text').focus( function() {
		if (!keywordsLabel.hasClass('hidden')) {
			keywordsLabel.addClass('hidden');
		}
	});
	$('form#search input.text').blur( function() {
		if (keywordsLabel.hasClass('hidden') && $(this).val() == '') {
			keywordsLabel.removeClass('hidden');
		}
	});
	
//	Toggle Change City
	$('a.change-city, p.change-city a, p.close-overlay a').click(function(){
		$('a.change-city, p.change-city a').toggleClass('selected');
		$('div#change-city').toggle();
		if ($.browser.msie) {
			if ($.browser.version < 7) {
				$('div.home form#search select').toggle();
			}
			if ($.browser.version < 8) {
				DD_roundies.addRule('#change-city', '12px');
				DD_roundies.addRule('div#change-city h2#change-uk-ireland','10px 10px 0 0');
			}
		}
		return false;
	});
	
//	Scroll Back to Top
	$("a[href='#skip']").click(function(){
		var scrollTime = $(document).height() / 2.5; // This number defines the speed of the scroll; the lower, the slower.
		$.scrollTo('div#skip', scrollTime);
		return false;
	});

//	Make AdSense links open in a new window
	$('ul.adsense_open_new li.adsense_ad a').click(function(){
		window.open(this.href);
		return false;
	});

//	show/hide press coverage sections
	$('#press-coverage h4.group-head a').click(function() {
		var targetEl = $($(this).attr('href'));
		$(this).parent('h4')
			.toggleClass('open')
			.toggleClass('closed');
		targetEl
			.toggleClass('open')
			.toggleClass('closed');
		return false;
	});
	$('#press-releases h4.group-head a').click(function() {
		var targetEl = $($(this).attr('href'));
		$(this).parent('h4')
			.toggleClass('open')
			.toggleClass('closed');
		targetEl
			.toggleClass('open')
			.toggleClass('closed');
		return false;
	});
//	show/hide change city sections
	$('#change-city h2 a').click(function() {
		var targetEl = $($(this).attr('href'));
		$(this).parent('h2')
			.toggleClass('open')
			.toggleClass('closed');
		targetEl
			.toggleClass('show')
			.toggleClass('hidden');
		return false;
	});
//	show/hide browse/search options
	$('#list-postings-refinements h3 a').click(function() {
		var targetEl = $($(this).attr('href'));
		$(this).parent('h3')
			.toggleClass('open')
			.toggleClass('closed');
		targetEl
			.toggleClass('show')
			.toggleClass('hidden');
		return false;
	});	

//	Show Homepage Spotlight Ads
	if ($('div#header.home').length > 0) { // homepage only

		var docStyle = document.documentElement.style;

		$.getJSON('/get_homepage_features/' + siteId + '?rnd=' + Math.random()*10, function(data) {
//		$.getJSON('/common/hpf.html', function(data) { // Used for testing on VMs

			var totalSpotlightAds = data.items.length;

			$.each(data.items, function(i,ad){

			var adTitle = ad.title;
			var adLocation = ad.location;

//			FireFox doesn't speak text-overflow, so we'll do it ourselves
			if (!('textOverflow' in docStyle || 'OTextOverflow' in docStyle)) {
				$('p.spotlight-location').ellipsis('width');
			}

//			Load in the first 12 ads, regardless
				if (i < 6) {
					if (ad.thumbnail_url == '/common/v2/images/artifacts/listings-no-thumb.gif') {
						var adClass = 'no-picture';
					} else {
						var adClass = ' ';
					}
					$('#spotlight ul').append('<li class="' + adClass + '"><a class="spotlight-picture" rel="nofollow" href="' + ad.path + '"><img width="96" height="72" alt="' + ad.title + '" src="' + ad.thumbnail_url + '" /></a><p class="spotlight-title"><a title="' + ad.title + '" rel="nofollow" href="' + ad.path + '">' + adTitle + '</a></p><p class="spotlight-location">' + adLocation + '</p></li>');
				}
			});
		
//			If there are no items, set blankSpaces to fill up one page-worth of ads
			if (totalSpotlightAds == 0 ) {
				var blankSpaces = 6;
//			If there are less than 12 items, set blankSpaces to fill up to the nearest page-worth of ads
			} else if (totalSpotlightAds < 12 ) {
				var blankSpaces = Math.ceil(totalSpotlightAds/6) * 6 - totalSpotlightAds;
			}

//			Create a spotlight ad list item for each blankSpace
			for(var i = 0; i < blankSpaces; i++ ) {
				$('#spotlight ul').append('<li><a class="spotlight-learn-more spotlight-picture" rel="nofollow" href="#"><img width="96" height="72" alt="No picture" src="/common/v2/images/artifacts/listings-no-thumb.gif" /></a><p class="spotlight-title">Get your ad displayed here please</p><p class="spotlight-location"><a href="#" rel="nofollow" class="spotlight-learn-more tip-for-spotlight-learn-more has-tip">Learn more</a></p></li>');
			}

			function showCarousel() {
				activateToolTips();
				$('#spotlight').css({'background':'#ffffff'});
				$('#spotlight ul').animate({'left':'0'}, 1000);		
				$('p.spotlight-title a').ellipsis('height');
//				Update the Page X of Y reading for the spotlight ads. Commented out as we're hiding the page count for now
//				$('span.total-pages').text(Math.ceil($('#spotlight ul li').length/6));
			}

			$('#spotlight ul').jcarousel({
				animation: 900,
				easing: 'swing',
				scroll: 6,
				visible: 6,
				buttonNextHTML:'<p>Next</p>',
				buttonPrevHTML:'<p>Previous</p>',
				initCallback: showCarousel,
				itemFirstInCallback: function(carousel, item, idx, state) {
					$(item).addClass('first');
//					Update the Page X of Y reading for the spotlight ads. Commented out as we're hiding the page count for now
//					$('span.current-page').text(Math.ceil(idx/6));
				},
				itemFirstOutCallback: function(carousel, item, idx, state) {
					$(item).removeClass('first');
				},
				itemLastInCallback: function(carousel, item, idx, state) {

					var adsInSpotlight = $('#spotlight ul li').length;
					var lastVisibleAdPosition = $(item).prevAll().length + 1;
					var loadToAd = adsInSpotlight + 6;

					$.each(data.items, function(i,ad){
//						Only put ads that aren't already loaded in the carousel, and only load 6 more at a time
						if (i == adsInSpotlight && i < loadToAd) {
//							Figure out what position the new ad should go in
							var newAdPosition = adsInSpotlight + 1;
							carousel.add(newAdPosition,'<a class="spotlight-picture" rel="nofollow" href="' + ad.path + '"><img width="96" height="72" alt="' + ad.title + '" src="' + ad.thumbnail_url + '" /></a></p><p class="spotlight-title"><a title="' + ad.title + '" rel="nofollow" href="' + ad.path + '">' + ad.title + '</a></p><p class="spotlight-location">' + ad.location + '</p>');
							adsInSpotlight++;
						}
					});

//					If there are less than a multiple of 6 ads, fill in the gaps with blankSpaces again
					blankSpaces = Math.ceil($('#spotlight ul li').length/6) * 6 - adsInSpotlight;
					for(var i = 0; i < blankSpaces; i++ ) {
						var newAdPosition = adsInSpotlight + 1;
						carousel.add(newAdPosition,'<a class="spotlight-learn-more spotlight-picture" rel="nofollow" href="#"><img width="96" height="72" alt="No picture" src="/common/v2/images/artifacts/listings-no-thumb.gif" /></a><p class="spotlight-title">Get your ad displayed here</p><p class="spotlight-location"><a href="#" rel="nofollow" class="spotlight-learn-more tip-for-spotlight-learn-more has-tip">Learn more</a></p>');
						adsInSpotlight++;
					}

//					Update the carousel controls to accomodate the added list items
					carousel.size($('#spotlight ul li').length);
				}
			});

	    });
	}
	
//	Lightbox/modal
	function hideLightbox() {
		$('#lightbox-bg')
			.animate({'opacity':'0'}, 200, function () {
				$(this).remove();
			});
	}
	$('a.modal').click(function() {
		var targetDivId = $(this).attr('href').match(/#(.+)/)[0];
		var targetDiv = $(targetDivId);
		
		if (targetDiv.hasClass('show')) {
			hideLightbox();
			targetDiv.removeClass('show');
		}
		else {
			$('body').append('<div id="lightbox-bg"></div>');
			$('#lightbox-bg')
				.css('height', $(document).height()+'px')
				.animate({'opacity':'0.5'}, 200);
			targetDiv.addClass('show');
			
//			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();
			targetDiv.css('left', leftOffset+'px');
			targetDiv.css('top', topOffset+'px');
//			move to end of body tag to sort out z-index issues
			targetDiv.appendTo('body');
			
			if ($.browser.msie && $.browser.version < 8) {
				if ($('body > ignore').length == 0) {
					DD_roundies.addRule(targetDivId);
					DD_roundies.addRule(targetDivId+' h3');
				}
				else {
					$('body > ignore').show();
					$('body > ignore').css('left', leftOffset+'px');
					$('body > ignore').css('top', topOffset+'px');
				}
			}
		}
		return false;
	});
	$('div.modal p.close a').click(function() {
		hideLightbox();
		if ($.browser.msie && $.browser.version < 8) {
			$('body > ignore').hide();
		}
		var targetDiv = $(this).parents('div.modal');
		targetDiv.removeClass('show');
		return false;
	});

	activateToolTips();
	
	/* Old VIP */
	$('body#view_item_page a#save_ad, div#posting ul#posting-actions a#starred').click(function(){
	   var id = $(this).parents('li').attr('id').match(/save-ad-([0-9]+)/)[1];
	   showposting_ToggleStarred(id);
	   return false;
	});
    /* End Old VIP */

});

function open_close(el) {
	if (el.hasClass('open')) {
		el.removeClass('open');
		el.addClass('closed');
	}
	else {
		el.removeClass('closed');
		el.addClass('open');
	}
}

// Google/legacy code expects these "global" functions to exist, so we map them to our jQuery functions
function google_afs_request_done( ads ) {
	return $.gtadslots.adsense.google_afs_request_done( ads );
}
function google_ad_request_done( ads ) {
	return $.gtadslots.adsense.google_ad_request_done( ads );
}

// Activate ad placements and alter related elements
function activateAdPlacements() {
	$('div.ad').each(function(){
		var adId = $(this).parent().eq(0).attr('id');
		if (($(this).children('iframe.gumtree-dart-wrapper').length > 0 && $(this).children('iframe.gumtree-dart-wrapper').contents().find('body').children('div.no-banner').length == 0) || $(this).children('ul.adsense').length > 0 ) {
			$(this).addClass('show');
			$('.' + adId + '-related').addClass('has-placement');
		} else {
			$(this).removeClass('show');
			$('.' + adId + '-related').removeClass('has-placement');
		}
	});
}

// Activate Tooltips
function activateToolTips() {
	$('.has-tip').click(function() {
		var targetDivId = '#'+$(this).attr('className').match(/tip-for-[a-zA-Z-]+/)[0];
		var targetDiv = $(targetDivId);
		
		if (targetDiv.children('p.close').length == 0) {
			targetDiv.append('<p class="close"><a href="#">Close</a></p>');
		}
		$(targetDivId+' p.close a').click(function() {
			var targetDiv = $(this).parents('div.tip-content');
			if ($.browser.msie && $.browser.version < 7) {
				$('body > ignore').hide();
			}
			targetDiv.removeClass('show');
			return false;
		});

		if (targetDiv.children('div.bottom').length == 0) {
			targetDiv.append('<div class="bottom"></div>');
		}

//		work out offset to the document
		var offsets = $(this).offset();
		var leftOffset = offsets.left - 200;
		var topOffset = offsets.top - targetDiv.height();
		if (topOffset < 5) {
			topOffset = 5;
		}

		if (targetDiv.hasClass('show')) {
			if (targetDiv.css('left') != leftOffset && targetDiv.css('top') != topOffset) {
				targetDiv.css('left', leftOffset+'px');
				targetDiv.css('top', topOffset+'px');				
			} else {
			targetDiv.removeClass('show');
			}
		} else {
			targetDiv.addClass('show');
			targetDiv.css('left', leftOffset+'px');
			targetDiv.css('top', topOffset+'px');
//			move to end of body tag to sort out z-index issues
			targetDiv.appendTo('body');
			
			if ($.browser.msie && $.browser.version < 7) {
				if ($('body > ignore').length == 0) {
					DD_roundies.addRule(targetDivId+' p');
					DD_roundies.addRule(targetDivId+' p.close a');
					DD_roundies.addRule(targetDivId+' div.bottom');
				}
				else {
					$('body > ignore').show();
					$('body > ignore').css('left', leftOffset+'px');
					$('body > ignore').css('top', topOffset+'px');
				}
			}
		}
		return false;
	});
}

function chooseBucket (id, test_name, buckets) {
    buckets = buckets.sort();
    var test_hex = '0x'+$.md5(id+test_name).substring(0,8);
    return buckets[(test_hex % buckets.length)];
}
var Starred = new Object();

// showposting

var saveitsaved = '/common/images/save_it_button_saved.gif';
var saveit = '/common/images/save_it_button.gif';

function showposting_ToggleStarred(id) {
	if (Starred[id]) {
		removeFromStarred(id, function(id){
			document.getElementById('starred').className = 'icon';
			updateSavedAdsCount(-1);
			$('li.save a').text('Save');
		});
	} else {
		$('li.save a').text('Saving');
		addToStarred(id, function(id) {
			document.getElementById('starred').className = 'icon icon_saved';
			updateSavedAdsCount(1);
			$('li.save a').text('Saved');
		});
	}
}

function showposting_load(id,ispl) {
	fillStarred(function (Starred) {
		if (Starred[id]) {
			document.getElementById('starred').className = 'icon icon_saved';
			$('li.save a').text('Saved');
		}
	});
}

// listpostings

function listpostings_ToggleStarred(id)
{
	if (Starred[id]) {
		if (document.getElementById('star_'+id)) {
			document.getElementById('star_'+id).innerHTML = 'Save'; // progress
		}
		if ( document.getElementById('star_fa_'+id) ) {
			document.getElementById('star_fa_'+id).innerHTML = 'Save'; // progress
		}
		removeFromStarred(id, function(id) {
			if (document.getElementById('star_'+id)) {
				document.getElementById('star_'+id).className = 'icon';
			}
			if ( document.getElementById('star_fa_'+id) ) {
					document.getElementById('star_fa_'+id).className = 'icon';
			}
		} );
		updateSavedAdsCount(-1);
	} else {
		if (document.getElementById('star_'+id)) {
			document.getElementById('star_'+id).innerHTML = 'Saved'; // progress
		}
		if ( document.getElementById('star_fa_'+id) ) {
			document.getElementById('star_fa_'+id).innerHTML = 'Saved'; // progress
		}
		addToStarred(id, function(id) {
			if (document.getElementById('star_'+id)) {
				document.getElementById('star_'+id).className = 'icon icon_saved';
			}
			if ( document.getElementById('star_fa_'+id) ) {
					document.getElementById('star_fa_'+id).className = 'icon icon_saved';
			}
		} );
		updateSavedAdsCount(1);
	}
}

function listpostings_starredpostings_removeAll(Starred)
{
	for (var id in Starred) {
		listpostings_ToggleStarred(id);
	   //removeFromStarred(id, function (id) { document.getElementById('star_'+id).innerHTML = ''; document.getElementById('star_'+id).className = 'empty'; } );
	   // removeFromStarred(id, function (id) { document.getElementById('star_'+id).style.display = 'none'; } );
	}
	starredpostings_TryHideButton(1);
}


function listpostings_load()
{
	fillStarred(function (Starred) {
		for (var p in Starred) {
			if (document.getElementById('star_'+p)) {
				document.getElementById('star_'+p).className = 'icon icon_saved';
				document.getElementById('star_'+p).innerHTML = 'Saved';
			}
			if (document.getElementById('star_fa_'+p)) {
				document.getElementById('star_fa_'+p).className = 'icon icon_saved';
				document.getElementById('star_fa_'+p).innerHTML = 'Saved';
			}
		}
	} );
}

// my saved ads

function starredpostings_TryHideButton(hideforsure)
{
    var atleastone = 0;
    if (!hideforsure) {
      for (var id in Starred) {
           if (Starred[id]) {
             atleastone = 1;

             break;
           }
      }
    }
    if (!atleastone) {

//		setTimeout("document.getElementById('noads').style.display = 'block';", 1000);        
//        document.getElementById("removeall").style.display = 'none';
       document.getElementById('noads').style.display = 'block';
       document.getElementById("removeall").style.display = 'none';
    }

}

function starredpostings_removeFromStarred(Starred, id)
{
   document.getElementById('star_removing_'+id).innerHTML = ''; // progress
   //removeFromStarred(id, function (id) { document.getElementById('star_'+id).innerHTML = ''; document.getElementById('star_'+id).className = 'empty'; starredpostings_TryHideButton(0); } );
   removeFromStarred(id, function (id) { document.getElementById('star_'+id).style.display = 'none'; starredpostings_TryHideButton(0); } );
}

function starredpostings_removeAll(Starred)
{
        for (var id in Starred) {
           //removeFromStarred(id, function (id) { document.getElementById('star_'+id).innerHTML = ''; document.getElementById('star_'+id).className = 'empty'; } );
           removeFromStarred(id, function (id) { document.getElementById('star_'+id).style.display = 'none'; } );
        }
        starredpostings_TryHideButton(1);
}

// lower layer

function fillStarred(callbackfunc)
{
  CheckSession();
  if (isAnonymous()) {
      var A = new Array();
      var posting_ids = getCookie('posting_ids');
      if  (posting_ids) {
          A = posting_ids.split(' ');
          for (var i = 0; i < A.length; ++i) {
            Starred[A[i]] = 1;
          }
      }
      var saved_ids = getCookie('saved_ids');
      if  (saved_ids) {
          A = saved_ids.split(' ');
          for (var i = 0; i < A.length; ++i) {
            Starred[A[i]] = 1;
          }
      }

      callbackfunc(Starred);      
  } else {
      ajaxcall('/cgi-bin/my_saved_ads.pl?action=getpostings',  function(xml) {
                                    var node = xml.getElementsByTagName('data')[0];
                                    if (node) {
                                      for (i = 0;  i < node.getElementsByTagName('posting').length; ++i) {
                                        var p = node.getElementsByTagName('posting')[i].firstChild.nodeValue;
                                        Starred[p] = 1;
                                       }
                                       callbackfunc(Starred);
                                    }
      });
  }
}

function ToggleStarred(id)
{
   if (Starred[id]) {
     removeFromStarred(id);
   } else {
     addToStarred(id);
   }
}


function addToStarred(id, callbackfunc)
{
  CheckSession();
  if (isAnonymous()) {
      Starred[id] = 1;
      updatePostingsCookie(id, callbackfunc);
  } else {
      ajaxcall('/cgi-bin/my_saved_ads.pl?action=addposting&posting_id='+id,  function(xml) {
                                    if (xml.getElementsByTagName('result')[0].firstChild.nodeValue != 1) {
                                      alert('failed - mark posting starred');
                                    } else {
                                      Starred[id] = 1;
                                      if (callbackfunc) callbackfunc(id);
                                    }
      });
  }
}

function removeFromStarred(id, callbackfunc)
{
  CheckSession();
  if (isAnonymous()) {
      Starred[id] = 0;
      updatePostingsCookie(id, callbackfunc);
  } else {
      ajaxcall('/cgi-bin/my_saved_ads.pl?action=removeposting&posting_id='+id,  function(xml) {
                                    if (xml.getElementsByTagName('result')[0].firstChild.nodeValue != 1) {
                                      alert('failed - unmark posting starred');
                                    } else {
                                      Starred[id] = 0;
                                      if (callbackfunc) callbackfunc(id);
                                    }
      });
  }
}

// lowest layer

function ajaxcall(url, callbackfunc) {
        var request;
        if (window.XMLHttpRequest) {
                request = new XMLHttpRequest();
        } else {
                request = new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        request.open("GET", url, true);
        request.onreadystatechange = function(){
                if (request.readyState == 4 && request.status == 200) {
                        if (request.responseXML){
                                callbackfunc(request.responseXML);
                        }
                }
        }
        request.send(null);
}

// helpers

function CheckSession()
{
  var SID = getCookie('SID');
  var RE = new RegExp("^[au][a-f0-9]{32}", "i");
  if (!SID.match(RE)) { // !
    setCookie('SID', 'a'+Math.random().toString().substring(2,12)+Math.random().toString().substring(2,12)+Math.random().toString().substring(2,12)+Math.random().toString().substring(2,4));
  }
}

function updatePostingsCookie(id, callbackfunc)
{
      var A = new Array();
      for (var p in Starred) {
        if (Starred[p]) {
          A.push(p);
        }
      }
      setCookie('posting_ids', '');
      var date = new Date();
      date.setTime(date.getTime()+(365*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
      setCookie('saved_ids', A.join(' '), expires, '/', 'gumtree.com');
      setCookie('saved_ids', A.join(' '), expires, '/', 'gumtree.ie');

      if (callbackfunc) callbackfunc(id);
}

function isAnonymous()
{
  CheckSession();
  var RE = new RegExp("^a", "i");
  return getCookie('SID').match(RE); 
}

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 setCookie (name, value, expires, path, domain, secure)
{
      path = '/';
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
