﻿var topWin = (isSameDomain()) ? top : parent.topWin; //parent is IntegratedPage.aspx

function isSameDomain() {
  //Using try/catch to check for top.location so we don't throw a JS error
  try {
    return !!top.location.href;
  } catch (e) {
    return false;
  }
}

function ProcessJSTemplate(template, data, target) {
  var usingTemplate = TrimPath.parseTemplate(template);
  var processedTemplate = usingTemplate.process(data);

  // TODO : test
  //alert(processedTemplate);

  if (jQuery('#' + target).length > 0)
    jQuery('#' + target).html(processedTemplate);
}

function onError(data) {
  var message = '';
  if ((typeof (data) != "undefined") && data != '') {
    if (('' + data).indexOf('XMLHttpRequest') == -1) {
      message = 'Erreur :' + '\n' + data;
    }
  }
  else {
    message = 'Erreur technique !';
  }
  if (message != '') {
    alert(message);
  }
}

function LoadFile(scriptPath) {
  return $.ajax({
    url: scriptPath,
    async: false
  }).responseText;
}

function LoadAndEvalScript(scriptPath) {
  eval(LoadFile(scriptPath));
}


// Popup size methods, return desired dimension or max possible for the current screen
function GetPopupHeight(desiredHeight) {
  pHeight = pageHeight() - 50;
  if (topWin.isIntegrated)//Making a shorter popup when in an integrated website
    pHeight = pHeight - 70;
  if (desiredHeight > pHeight) {
    return (pHeight);
  }
  else {
    return desiredHeight;
  }
}

function GetPopupWidth(desiredWidth) {
  pWidth = pageWidth() - 40;
  if (desiredWidth > pWidth) {
    return (pWidth);
  }
  else {
    return desiredWidth;
  }
}

function pageWidth() { return topWin.window.innerWidth || topWin.document.documentElement.clientWidth || topWin.document.getElementsByTagName('body')[0].clientWidth; };
function pageHeight() { return topWin.window.innerHeight || topWin.document.documentElement.clientHeight || topWin.document.getElementsByTagName('body')[0].clientHeight; };

function viewport() {
  var e = window, a = 'inner';

  if (!('innerWidth' in window)) {
    a = 'client';
    e = document.documentElement || document.body;
  }

  return { width: e[a + 'Width'], height: e[a + 'Height'] }
}

// Create template object Utility
function TemplateObject() {
  this.d = 0;
}

function CreateNewTemplateObject(data) {
  returnValue = new TemplateObject();
  returnValue.d = data;
  return returnValue;
}


function makeAlternativeStyle(gridId) {
  jQuery('#' + gridId + ' tr').removeClass('ligne-paire').removeClass('ligne-impaire').removeClass('isEven').removeClass('isOdd');
  jQuery('#' + gridId + ' tr.contentLine:nth-child(even)').addClass('ligne-paire');
  jQuery('#' + gridId + ' tr.contentLine:nth-child(odd)').addClass('ligne-impaire');
  jQuery('#' + gridId + ' tr.contentLine:nth-child(even)').addClass('isEven');
  jQuery('#' + gridId + ' tr.contentLine:nth-child(odd)').addClass('isOdd');
}

function ChangeSelection(control, className) {
  jQuery('.' + className).attr('checked', false);
  if (control != null) {
    control.checked = true;
  }
}

function SetDateTimePicker() {

  // If in French we set default language for datepicker to French
  if (i18n_LG == 'FR') {
    $.datepicker.setDefaults($.datepicker.regional['fr']);
  }

  jQuery('.input_date').datepicker({
    numberOfMonths: [1, 1],
    stepMonths: 1,
    speed: 10,
    showOn: 'button',
    buttonImage: 'images/ico/cal.gif',
    buttonImageOnly: true,
    changeYear: true,
    changeMonth: true,
    shortYearCutoff: 25,
    yearRange: '1926:2025',
    constrainInput: true,
    onSelect: function () {
      $(this).change();
    },
    onChangeMonthYear: function (year, month, inst) {
      var newYear = year.toString().substring(2, 4);
      var newMonth = month.toString();
      if (newMonth.length < 2) {
        newMonth = '0' + newMonth;
      }
      if (i18n_LG == 'FR') {
        jQuery('#' + inst.id).val(jQuery('#' + inst.id).val().toString().substring(0, 2) + '/' + newMonth + '/' + newYear);
      }
      else {
        jQuery('#' + inst.id).val(newMonth + '/' + jQuery('#' + inst.id).val().toString().substring(0, 2) + '/' + newYear);
      }
    }
  });
}

function DestroyDateTimePicker() {
  jQuery('.input_date').datepicker('destroy');
}

function InitFilterTextBox(id) {
  if (jQuery("#" + id).hasClass("greyTextBox")) {
    jQuery("#" + id)[0].value = "";
    jQuery("#" + id).removeClass("greyTextBox");
  }
}

function SetInitFilterTextBox(id, defaultText) {
  if (jQuery("#" + id)[0].value == "" || jQuery("#" + id)[0].value == defaultText) {
    jQuery("#" + id)[0].value = defaultText;
    jQuery("#" + id).addClass("greyTextBox");
  }
  else {
    if (jQuery("#" + id).hasClass("greyTextBox"))
      jQuery("#" + id).removeClass("greyTextBox")
  }
}

function GetValueOfGreyTextBox(id) {
  if (jQuery("#" + id).hasClass("greyTextBox"))
    return '';
  return jQuery("#" + id)[0].value;
}

function SetPopupTitle(text) {
  document.getElementById("popupTitle").innerHTML = text;
}

function ResetFileInput(originalInput) {
  if (originalInput != null) {
    var clearedInput = originalInput.cloneNode(false);
    originalInput.parentNode.insertBefore(clearedInput, originalInput);
    originalInput.parentNode.removeChild(originalInput);
  }
}


function gup(name) {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if (results == null)
    return "";
  else
    return results[1];
}


function EndOfPopup() {
}

function RemoveAccents(data) {
  var noaccents = data.replace(/[àâäÀÂÄ]/gi, "A")
  noaccents = noaccents.replace(/[éèêëÉÈÊË]/gi, "E")
  noaccents = noaccents.replace(/[îïÎÏ]/gi, "I")
  noaccents = noaccents.replace(/[ôöÔÖ]/gi, "O")
  noaccents = noaccents.replace(/[ùûüÙÛÜ]/gi, "U")
  return noaccents
}

function RemoveSpecialChars(data) {
  var nospechars = data.replace(/['"]/gi, " ")
  return nospechars
}

function RemoveIntPhoneNumber() {
  var nospechars = data.replace(/[']/gi, " ")
  return nospechars
}

function RemoveWordWrap(source) {
  var reg = new RegExp("[\n]", "g");
  var returnValue = source.replace(reg, " ");
  reg = new RegExp("[\n]", "g");
  returnValue = returnValue.replace(reg, " ");
  return returnValue
}

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/

function trim(str, chars) {
  return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
  chars = chars || "\\s";
  return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}



// Methods for changing background color of validated controls
function AssignOnChangeValidate(id) {
  jQuery("#" + id).change(function (event) { return CheckValidatorColor(id); });
}
function CheckValidatorColor(id) {
  for (var i = 0; i < Page_Validators.length; i++) {
    var val = Page_Validators[i];
    if (val.controltovalidate == id) {
      if (!(val.isvalid)) {
        jQuery('#' + val.controltovalidate).css("background-color", "#e94412");
      }
      else {
        jQuery('#' + val.controltovalidate).css("background-color", "#FFFFFF");
      }
      return;
    }
  }
}

function isIE() {
  return (navigator.appName.indexOf('Internet Explorer') > -1);
}

var mainScrollY = 0;
function ScrollCheck() {
  // If popup is visible, we fix the scroll position
  if (gPopupIsShown) {
    scroll();
  }
}

// Scrolls the page to the first dom element matching the id
function ScrollToID(id) {
  try {
    jQuery('html,body').animate({ scrollTop: $("#" + id).offset().top }, 1000);
  }
  catch (e) {
    alert("Error in animate .. ScollToID(" + id + ")" + e.toString());
  }
}

// Sends an email to adress in the textbox specified by the id
function SendEmail(id) {
  var emailAddress = jQuery('#' + id)[0].value;
  if (emailAddress && emailAddress != null && emailAddress != '') {
    window.location.href = 'mailto:' + emailAddress;
  }
}

// This utility method will load a combobox and set the value, using a timeout if first set of value fails
//   used as a workaround for IE6 loading + set value problem
function LoadDropDown(htmlOptions, ctrl, id) {
  jQuery(ctrl).html(htmlOptions);
  try {
    jQuery(ctrl).val(id);
  }
  catch (ex) {
    setTimeout("jQuery('" + ctrl + "').val('" + id + "')", 1);
  }
}

function PutSortArrow(targetSortField, sortFieldValue, sortDirection) {
  if (targetSortField == sortFieldValue) {
    if (sortDirection == "ASC" || sortDirection == " ASC") {
      return '&nbsp;<img src="images/sort_down.png" width="10" height="9"/>';
    }
    else {
      return '&nbsp;<img src="images/sort_up.png" width="10" height="9"/>';
    }
  }
  else {
    return '&nbsp;<img src="images/sort_empty.png" width="8" height="9"/>';
  }
}


// Array methods to manage multiple selection
function IndexOfArray(key, keyArray) {
  var len = keyArray.length;
  for (var i = 0; i < len; i++) {
    if (keyArray[i] == key) {
      return i;
    }
  }
  return -1;
}

function AddInArray(key, keyArray) {
  var idx = IndexOfArray(key, keyArray);
  if (idx < 0) {
    keyArray.push(key);
  }
}

function DeleteInArray(key, keyArray) {
  var idx = IndexOfArray(key, keyArray);
  if (idx >= 0) {
    keyArray.splice(idx, 1);
  }
}

function SwitchInArray(key, keyArray) {
  var idx = IndexOfArray(key, keyArray);
  if (idx < 0) {
    keyArray.push(key);
    return true;
  }
  else {
    keyArray.splice(idx, 1);
    return false;
  }
}

function ArrayToString(keyArray) {
  var len = keyArray.length;
  var ids = '';
  for (var i = 0; i < len; i++) {
    if (ids != '') {
      ids += ',';
    }
    ids += keyArray[i].toString();
  }
  return ids;
}

// Basic sprintf
function sprintf(format, etc) {
  var arg = arguments;
  var i = 1;
  return format.replace(/%((%)|s)/g, function (m) { return m[2] || arg[i++] })
}

// <!-- TIME  ZONE

// return the time difference between Greenwich Mean Time (GMT) and local time, in minutes. Rounding if need.
function GetTimeZoneOffset(roundingFactor) {

  var current_date = new Date();
  var gmt_offset = current_date.getTimezoneOffset();

  // if we want to round it. Ex : 30 or 60 minutes
  if (roundingFactor != null) {
    gmt_offset = RoundNumber(gmt_offset, roundingFactor);
  }

  return gmt_offset;
}

//function ChangeToUTCTime(dateTime, minuteDiff) {
//    var utcTime = CopyDate(dateTime);

//    // Explaination: If time zone is earlier, the minute diff is negative.
//    // Ex: minute diff of East Asia is -420
//    utcTime.setMinutes(utcTime.getMinutes() + minuteDiff);

//    return utcTime;
//}

//function ChangeToLocalTime(dateTime, minuteDiff) {
//    var localTime = CopyDate(dateTime);

//    // Explaination: If time zone is earlier, the minute diff is negative.
//    // Ex: minute diff of East Asia is -420
//    localTime.setMinutes(localTime.getMinutes() - minuteDiff);

//    return localTime;
//}

// TIME ZONE -->

function UpdateProfilePicture(newSrc) {
  // updates profiles picture in top left of main page
  $(".imgProfileMain").attr("src", newSrc);
}

// <!-- DATE TIME 

function CopyDate(date) {
  var newDate = new Date();
  newDate.setTime(date.getTime());
  return newDate;
}

// JSONString : date in yyyyMMdd format
function JSONStringToDate(JSONString) {
  //constructor : var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
  var date = new Date(
        eval(JSONString.substring(0, 4)),
        eval(JSONString.substring(4, 6)) - 1,  // month is 0 - 11
        eval(JSONString.substring(6, 8)),
        0, 0, 0);
  return date;
}

// JSONString : date time in yyyyMMddHHmm format
function JSONStringToDateTime(JSONString) {
  //constructor : var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

  var date = new Date(
        eval(JSONString.substring(0, 4)),
        eval(JSONString.substring(4, 6)) - 1,  // month is 0 - 11
        eval(JSONString.substring(6, 8)),
        eval(JSONString.substring(8, 10)), eval(JSONString.substring(10, 12)), 0
    );

  return date;
}

function DateTimeToJSONString(datetime) {
  var str = datetime.format("yyyyMMddHHmm");
  return str;
}

function DateToJSON(date) {
  var json = date.format('yyyyMMdd');
  return json;
}

// Sets the time to last moment of the current day
function setEndOfDay(date) {
  date.setHours(23);
  date.setMinutes(59);
  date.setSeconds(59);
  date.setMilliseconds(999);
}

// Returns number of days in one month
function daysInMonth(month, year) {
  var dd = new Date(year, month, 0);
  return dd.getDate();
}

function moveBackToMonday(date) {
  if (date.getDay() == 0) {
    // if it's Sunday, move back 6 days to Monday
    date.setDate(date.getDate() - 6);
  }
  else {
    // in the week, so move back to the Monday
    date.setDate(date.getDate() - (date.getDay() - 1));
  }
}

// convert a date obj to a Unix time Stamp number
function ConvertToUnixTimeStamp(date) {
  var ms = date.getTime();
  var s = Math.round(ms / 1000);
  return s;
}

// convert date to iso8601
function ISODateString(d) {
  function pad(n) {
    return n < 10 ? '0' + n : n
  }
  return d.getFullYear() + '-'
    + pad(d.getMonth() + 1) + '-'
    + pad(d.getDate()) + 'T'
    + pad(d.getHours()) + ':'
    + pad(d.getMinutes()) + ':'
    + pad(d.getSeconds()) + 'Z'
}

// DATE TIME -->

// <!-- NUMBER

function RoundNumber(number, roundFactor) {
  // ex: RoundNumber(374, 30) --> 360
  // ex: RoundNumber(375, 30)-- > 390

  var roundedNumber = number / roundFactor;
  roundedNumber = Math.round(roundedNumber);
  roundedNumber = roundedNumber * roundFactor;
  return roundedNumber;
}

// NUMBER -->





/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function () {
  var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
		  val = String(val);
		  len = len || 2;
		  while (val.length < len) val = "0" + val;
		  return val;
		};

  // Regexes and supporting functions are cached through closure
  return function (date, mask, utc) {
    var dF = dateFormat;

    // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
    if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
      mask = date;
      date = undefined;
    }

    // Passing date through Date applies Date.parse, if necessary
    date = date ? new Date(date) : new Date;
    if (isNaN(date)) throw SyntaxError("invalid date");

    mask = String(dF.masks[mask] || mask || dF.masks["default"]);

    // Allow setting the utc argument via the mask
    if (mask.slice(0, 4) == "UTC:") {
      mask = mask.slice(4);
      utc = true;
    }

    var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			  d: d,
			  dd: pad(d),
			  ddd: dF.i18n.dayNames[D],
			  dddd: dF.i18n.dayNames[D + 7],
			  m: m + 1,
			  mm: pad(m + 1),
			  mmm: dF.i18n.monthNames[m],
			  mmmm: dF.i18n.monthNames[m + 12],
			  yy: String(y).slice(2),
			  yyyy: y,
			  h: H % 12 || 12,
			  hh: pad(H % 12 || 12),
			  H: H,
			  HH: pad(H),
			  M: M,
			  MM: pad(M),
			  s: s,
			  ss: pad(s),
			  l: pad(L, 3),
			  L: pad(L > 99 ? Math.round(L / 10) : L),
			  t: H < 12 ? "a" : "p",
			  tt: H < 12 ? "am" : "pm",
			  T: H < 12 ? "A" : "P",
			  TT: H < 12 ? "AM" : "PM",
			  Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			  o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			  S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

    return mask.replace(token, function ($0) {
      return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
    });
  };
} ();

// Some common format strings => dateFormat.masks moved to Messages.js

// Internationalization strings ==> dateFormat.i18n moved to Messages.js 

// For convenience...
Date.prototype.format = function (mask, utc) {
  return dateFormat(this, mask, utc);
};

// find a obj in an array. 
// the id property of the obj type MUST be "id"
function FindObjectInArray(arr, id) {
  for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];

    if (obj.id == id) {
      return obj;
    }
  }

  return null;
}

// find index of an obj in an array. 
// The id property of the obj type MUST be "id"
function FindIndexInArray(arr, id) {
  for (var i = 0; i < arr.length; i++) {
    var obj = arr[i];


    if (obj.id == id) {
      return i;
    }
  }

  return -1;
}

// remove an obj out of an array. 
// The id property of the obj type MUST be "id"
function RemoveObjectFromArray(arr, id) {
  var index = FindIndexInArray(arr, id);
  if (index >= 0) {
    arr.splice(index, 1);
  }
}

function HelpMessage(text) {
  $.jGrowl(text, { life: 1500 });
}

function ShowLoginPopup(eventId) {
  var width = 600;
  var height = 500;
  var url = 'FrmUserLogin.aspx?ReturnUrl=PopupWaitPage.htm&random=' + Math.random();
  topWin.showPopWin(url, GetPopupWidth(width), GetPopupHeight(height), null, window, true, 'Login');
}

function ShowInvitePopup(email, name, callback) {
  var width = 800;
  var height = 280;
  var url = 'FrmContactInvitation.aspx?random=' + Math.random();
  if (name) {
    url += '&name=' + name;
  }
  if (email) {
    url += '&email=' + email;
  }
  topWin.showPopWin(url, GetPopupWidth(width), GetPopupHeight(height), callback, this, true, TITLE_CONTACT_INVITATION);
}


/************************************************
*    GET CLASS NAME FOR ROW/ALTERNATING ROW 
*************************************************/

var IsAlternateRow = false;
function InitRowClassName() {
  IsAlternateRow = true
}

function GetRowClassName() {
  IsAlternateRow = !IsAlternateRow;
  if (IsAlternateRow)
    return 'even_row';
  else
    return '';
}


/************************************************
*    FILE EXTENSION UTILS
*************************************************/

function GetFileIconByExtension(extension, idTaskMessage) {
  var iconFolder = 'images/ico/';
  switch (extension) {
    case 'doc':
    case 'docx':
      return iconFolder + 'document_word.png';
      break;
    case 'xls':
    case 'xlsx':
    case 'csv':
      return iconFolder + 'document_excel.png';
    case 'pdf':
      return iconFolder + 'document_pdf.png';
    case 'txt':
      return iconFolder + 'document_text.png';
    case 'ppt':
    case 'pptx':
      return iconFolder + 'document_ppt.png';
    case 'jpeg':
    case 'jpg':
    case 'gif':
    case 'png':
      return 'ImageHandler.ashx?idMsg=' + idTaskMessage + '&type=thumb';
    case 'avi':
    case 'wmv':
    case 'divx':
    case 'mov':
    case 'ogm':
    case 'mpg':
      return iconFolder + 'document_video.png';
    default:
      return iconFolder + 'document_file.png';

  }
}

function GetFileExtension(fileName) {
  var fileExtension = '';
  if (fileName != '' && fileName.lastIndexOf('.') > 0) {
    fileExtension = fileName.substr(fileName.lastIndexOf('.') + 1);
  }
  return fileExtension.toLowerCase();
}

function IsImageExtension(extension) {
  return (extension == 'jpeg') ||
          (extension == 'jpg') ||
          (extension == 'png') ||
          (extension == 'gif');
}

function IsVideoExtension(extension) {
  return (extension == 'avi') ||
        (extension == 'wmv') ||
        (extension == 'divx') ||
        (extension == 'mov') ||
        (extension == 'ogm') ||
        (extension == 'mpg');
}

function IsVideoFile(fileName) {
  var extension = GetFileExtension(fileName);
  return IsVideoExtension(extension);
}

function ReplaceDeleteFlagInMessage(taskMsg) {
  // Used to put in task message when a file is deleted, it will be replaced by localized string when showing the list

  var DeletedFileFlag = "%DELETED%";
  if (taskMsg.indexOf(DeletedFileFlag) <= 0)
    return taskMsg;
  var replaceMsg = '<p class="fileDeleted">( ' + MSG_TASK_FILE_DELETED;
  replaceMsg = taskMsg.replace(DeletedFileFlag, replaceMsg);
  replaceMsg += ' )</p>';
  return replaceMsg;
}
