﻿var DownloadCenterCookieExpires = 7; //wird nur als Fallback verwendet, wird aus der Config überschrieben.
var DownloadCenterCookieName = 'DownloadCenter';  //wird nur als Fallback verwendet, wird aus der Config überschrieben.
var idSeperator = "|";//Mögliche werte sind "," und "|".

function GetCookieName(cName) {

  if (cName != null && typeof (cName) != 'undefined') {
    return cName
  }
  return DownloadCenterCookieName;
}

function createDownloadCenterCookie(value, cName) {

  var date = new Date();
  date.setTime(date.getTime() + (DownloadCenterCookieExpires * 24 * 60 * 60 * 1000));
  var expires = ";expires=" + date.toGMTString();

  document.cookie = GetCookieName(cName) + "=" + value + expires + "; path=/";
}

function readDownloadCenterCookie(cName) {
 var value = '';
  var nameEQ = GetCookieName(cName) + "=";
  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) 
       value  = c.substring(nameEQ.length, c.length);
  }
  //zum gradeziehen der Cookies wenn sich der Seperator ändert:  
  value = value.replace(/[|]/g,idSeperator).replace(/[,]/g,idSeperator);
  return value ;
}

function removeDownload(id, cName, reload) {
  var cookie = readDownloadCenterCookie(cName);
  if (cookie.indexOf(id) >= 0) {
    cookie = cookie.replace(id + idSeperator, "");
  }
  createDownloadCenterCookie(cookie, cName);
  if (reload == true) {
    document.forms[0].submit();
  }
  else {
    refreshDownloadCount(cName);
  }
}

function addDownload(id, cName, reload) {
  var cookie = readDownloadCenterCookie(cName);
  if (cookie.indexOf(id) < 0) {
    cookie += id + idSeperator;
  }
  createDownloadCenterCookie(cookie, cName);
  if (reload == true) {
    document.forms[0].submit();
  }
  else {
    refreshDownloadCount(cName);
  }

}

function refreshDownloadCount(cName) {
  var downloadIds = readDownloadCenterCookie(cName);

  var downloadIdList = downloadIds.split(idSeperator);

  var downloadCounter = downloadIdList.length;
  if (downloadCounter < 1) {
    downloadCounter = "0 Downloads"
  }

  if (downloadCounter > 0) {
    downloadCounter--;
    if (downloadCounter == 1) {
      downloadCounter = downloadCounter + " Download"
    } else {
      downloadCounter = downloadCounter + " Downloads"
    }
  }
  document.getElementById('ownDownloadCount').innerHTML = downloadCounter;

}

function SmartLinkSwitch(id, elNew, elExist, cName) {
  var cook = readDownloadCenterCookie(cName);
  cook = idSeperator + cook + idSeperator;
  if (cook.indexOf(idSeperator + id + idSeperator) >= 0) {
    elExist.style.display = 'block';
    elNew.style.display = 'none';
  }
  else {
    elExist.style.display = 'none';
    elNew.style.display = 'block';
  }

}
