
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]) {
     document.getElementById('starred').innerHTML = ''; // progress
     removeFromStarred(id, function(id) { document.getElementById('starred').className = 'icon'; } );
   } else {
     document.getElementById('starred').innerHTML = ''; // progress
     addToStarred(id, function(id) { document.getElementById('starred').className = 'icon icon_saved'; } );
   }
}


function showposting_load(id, ispl)
{
    // if (ispl) {
    //   saveitsaved = '/common/pl-PL/images/save_it_button_saved.gif';
    //   saveit = '/common/pl-PL/images/save_it_button.gif';
    // }

    fillStarred(function (Starred) {
       if (Starred[id]) {
         document.getElementById('starred').className = 'icon icon_saved';
       } else {
         document.getElementById('starred').className = 'icon';
       }
    } );
}

// listpostings

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


function listpostings_load()
{
    fillStarred(function (Starred) {
        for (var p in Starred) {
          if (document.getElementById('star_'+p)) {
             document.getElementById('star_'+p).className = 'icon icon_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" : "");
}
