﻿// ====================================================================================
// Not used anymore
// ====================================================================================

function Comparison()
{
  Spif.DOMEvents.attach(window, "load", this.doLoad, this);
}

// Items die aangevinkt staan om te vergelijken moeten uitgevinkt (dus niet langer onthouden) worden op het moment dat de soort pagina (results, favorieten) verlaten wordt
// Solution: add a cookie type=Results or type=Favorites and use that to determine whether we set the cookie in a certain location
// When we decide to add a new cookie later on, check if the existing cookie matches the new type
// If not, empty the existing cookie and set a new one
// If it does match, continue as normal!

Comparison.prototype = {

  doLoad: function()
  {    
    if (!Cookie.isSupported())
      return false;
      
    Spif.DOMEvents.attach(document, "click", comparison.doClick);
  
    // check for a cookie and check the boxes associated with each item if it exists
    if (Cookie.exists("comparisons"))
    {
      var cookie = comparison.cookieToArray(Cookie.read("comparisons"));
                
      // check each checkbox associated with ids in the cookie
      for (var i = 0; i < cookie.length; i++)
      {
        var compareEl = document.getElementById('compare-' + cookie[i][0]);
        if (compareEl)
        {
          document.getElementById('compare-' + cookie[i][0]).checked = true;
          comparison.changeResultClassName(cookie[i][0], 'notComparing', 'comparing');
        }
      }
    
			// if we're adding items for a new cookie type, empty the cookie first
			var cookieType = new RegExp(comparison.getCookieType(), "i");
			if (!cookieType.test(window.location.href))
				comparison.deleteCookie();
      
      // show active cookies in a notice at the top of the page
      comparison.updateNotice();
      
    }
    
  },
  
  // Add or remove a comparison from the cookie
  doClick: function(e)
  {
  
    var el = e.subject; 
    
    // are we a checkbox?
    if (el.type == "checkbox" && /^compare-/.test(el.id))
      comparison.handleCheckBox(el, e);
    
    // are we the "compare" link?
    if (/-compare$/.test(el.className))
      comparison.handleCompareLink(el, e);
      
  },
  
  handleCheckBox: function(el, e)
  {
    if (comparison.handleCookie(el, e))
    {
      var id = el.id.split("-")[1];
      // Highlight this result so we know we checked it (wheee!)
      comparison.changeResultClassName(id, 'notComparing', 'comparing');
            
      // Show cookie IDs in a notice
      comparison.updateNotice();
    }
  },
  
  handleCookie: function(el, e)
  {    
    var cookie = Cookie.read("comparisons");
    var id = el.id.split("-")[1];    
    var code = el.className.replace(/code-/, "");
      
    // if we uncheck, remove
    if (el.checked == false)
    {
      comparison.removeItemFromCookie(id);
      return;
    }    
    
    // if the id is already in the cookie, don't do anything (shouldn't happen)
    var regex = new RegExp("\\|" + id + ";");
    if (regex.test(Cookie.read("comparisons")))
      return false;
    
    // we can't check more than 3 results
    if (cookie.substring(1, cookie.length).split("|").length > 2)
    {
      alert(resources.messages.comparison.select_only_2_to_3);
      (e.srcElement||e.target).blur();
      if (e.preventDefault)
        e.preventDefault();
      return false;
    }

    // passed all tests; add item to cookie
    comparison.addItemToCookie(id, code);
    comparison.setCookieType();
    
    return true;
  },
  
  deleteCookie: function()
  {
    Cookie.remove('comparisons', '/', '');
  },
  
  getCookieType: function()
  {
    return Cookie.read('comparisonType');
  },
  
  setCookieType: function()
  {
    var type = window.location.href.match(/Favorieten/) ? "Favorieten" : "Results";
    Cookie.write('comparisonType', type, new Date() + 3600*24*365, '/', '', 0);
  },
  
  addItemToCookie: function(id, code)
  {
    var accName = document.getElementById('result_' + id).getElementsByTagName('h3')[0].getElementsByTagName('a')[0].innerHTML;
    Cookie.write('comparisons', Cookie.read('comparisons') + ('|' + id + ";" + code + ";" + accName), new Date() + 3600*24*365, '/', '', 0);
  },
  
  changeResultClassName: function(id, oldCN, newCN)
  {
    var spifContainer = document.getElementById('spifcontainer_' + id);
    Spif.ClassNameAbstraction.replace(spifContainer, oldCN, newCN);
  },
   
  // are we the "compare" link? then check if we have anything checked and forward to comparison page
  handleCompareLink: function(el, e)
  {   
    if (/-compare$/.test(el.className))
    {
      var cookie = Cookie.read("comparisons");
      cookie = cookie.substring(1, cookie.length);
      var cookieItems = cookie.split("|");
      
      if (cookieItems.length >= 2 && cookieItems.length <= 3)
      {
        window.location.href = el.href;
      }
      else
      {
        alert(resources.messages.comparison.first_select_2_to_3);
        
        (e.srcElement || e.target).blur();
        
        if (e.preventDefault)
          e.preventDefault();
          
        return false;
      }
    }
  },
  
  removeItemFromCookie: function(id)
  {
    var cookie = Cookie.read("comparisons");
    var regex = new RegExp("\\|(" + id + ");([^\\|]*)", "i");
    cookie = cookie.replace(regex, '');
    
    Cookie.write('comparisons', cookie, new Date() + 3500*24*365, '/', '', 0);
    
    // try unsetting stuff on the result. this won't work if we're not on the same page
    // as the result anymore!
    try {
      comparison.changeResultClassName(id, 'comparing', 'notComparing');
      document.getElementById('compare-' + id).checked = false;
    } catch (e) {}
    
    // update the notice
    comparison.updateNotice();
    
    return; // return false rechecks the checkbox in IE (obviously)
  },
  
  updateNotice: function()
  {
    var cookie = Cookie.read("comparisons");
    var notice = document.getElementById('comparisons-notice');
  
    // No cookie? Then hide the notice
    if (cookie.length == 0)
    {
      if (notice)
        Spif.ClassNameAbstraction.replace(notice, 'showNotice', 'hideNotice');
      return false;
    }
    
    Spif.ClassNameAbstraction.replace(notice, 'hideNotice', 'showNotice');
  
    cookie = comparison.cookieToArray(cookie);
    
    if (notice)
    {
      var noticeText = comparison.getNoticeText(cookie);
      notice.getElementsByTagName('p')[0].getElementsByTagName('span')[0].innerHTML = noticeText;
    }
    
  },
  
  getNoticeText: function(cookie)
  {
    var notice = document.getElementById('comparisons-notice');
    var noticeText = comparison.makeLinkToAccommodationFromCookieItem(cookie[0]);
    
    if (cookie[1])
      noticeText += ", " + comparison.makeLinkToAccommodationFromCookieItem(cookie[1]);
    if (cookie[2])
      noticeText += " " + resources.messages.and + " " + comparison.makeLinkToAccommodationFromCookieItem(cookie[2]);
      
    noticeText += '. <br /> &raquo; ' + resources.messages.comparison.go_to_page;
      
    return noticeText;
  },
  
  makeLinkToAccommodationFromCookieItem: function(cookieItem)
  {
    return '<span class="selectedComparison">'+
      '<a href="/Accommodatie.aspx?' + cookieItem[0] + '">' + cookieItem[1] + '</a> '+
      '<a href="" onclick="comparison.removeItemFromCookie(' + cookieItem[0] + '); return false"'+
      ' class="bad" title="' + resources.messages.comparison.remove_from_comparison + '">x</a></span>';
  },
  
  cookieToArray: function(cookie)
  {
    if (cookie.length == 0)
      return [];
  
    if (cookie.substring(0,1) == "|")
      cookie = cookie.substring(1, cookie.length);
      
    cookie = cookie.split("|");
    for (i = 0; i < cookie.length; i++)
    {
      var cookieArray = [];
      var id = cookie[i].substring(0, cookie[i].indexOf(";"));
      var name = cookie[i].substring(cookie[i].indexOf(";") + 1);
      name = name.substring(name.indexOf(";") + 1);
      cookieArray.push(id);
      cookieArray.push(name);
      cookie[i] = cookieArray;
    }
    return cookie;
  }

};

//var comparison = new Comparison();
