﻿Array.prototype.hasValue = function(v) {
	var i;
	
	for(i = 0; i < this.length; i++)
		if(this[i] == v)
			return true;
			
	return false; 
}

String.prototype.trim = function(value)
{
    return this.replace(/^\s*|\s*$/gi, ""); 
}

var browserInfo;

(function() {

    if(browserInfo == null) 
    {
        browserInfo = new Object();
    }

    // Browser check
    ua = navigator.userAgent;
    browserInfo.isMSIE = (navigator.appName == "Microsoft Internet Explorer");
    browserInfo.isMSIE5 = browserInfo.isMSIE && (ua.indexOf('MSIE 5') != -1);
    browserInfo.isMSIE50 = browserInfo.isMSIE && (ua.indexOf('MSIE 5.0') != -1);
    browserInfo.isMSIE55 = browserInfo.isMSIE && (ua.indexOf('MSIE 5.5') != -1);
    browserInfo.isMSIE60 = browserInfo.isMSIE && (ua.indexOf('MSIE 6.0') != -1);
    browserInfo.isMSIE70 = browserInfo.isMSIE && (ua.indexOf('MSIE 7') != -1);
    browserInfo.isMSIE80 = browserInfo.isMSIE && (ua.indexOf('MSIE 8') != -1);
    browserInfo.isMSIE90 = browserInfo.isMSIE && (ua.indexOf('MSIE 9') != -1); // lol
    browserInfo.isGecko = ua.indexOf('Gecko') != -1;
    browserInfo.isSafari = ua.indexOf('Safari') != -1;
    browserInfo.isOpera = ua.indexOf('Opera') != -1;
    browserInfo.isWebKit = BonaPage.Browser.isWebKit;
    browserInfo.isMac = ua.indexOf('Mac') != -1;
    browserInfo.isFirefox = ua.indexOf('Firefox') != -1;
    
    if (browserInfo.isFirefox)
    {
      var reVersion = /Firefox\/(\d)*\./;
      reVersion.test(ua);
      browserInfo.firefoxMajorVersion = RegExp.$1;
    }
    
    browserInfo.isNS7 = ua.indexOf('Netscape/7') != -1;
    browserInfo.isNS71 = ua.indexOf('Netscape/7.1') != -1;

    // Fake MSIE on Opera and if Opera fakes IE, Gecko or Safari cancel those
    if (browserInfo.isOpera) 
    {
        browserInfo.isMSIE = true;
        browserInfo.isGecko = false;
        browserInfo.isSafari =  false;
    }

    browserInfo.isIE = browserInfo.isMSIE;
    browserInfo.isRealIE = browserInfo.isMSIE && !browserInfo.isOpera;

    // Check if valid browser has execcommand support
    browserInfo.execCommand = (typeof(document.execCommand) != 'undefined');
    
}) ();


var globalUtils;

(function()
{

  if (globalUtils == null)
  {
    globalUtils = new Object();
  }

  var _UdDomainNames = ['NET', 'COM', 'BIZ', 'ORG', 'EDU', 'MIL', 'GOV', 'PRO', 'INT', 'COOP', 'NAME', 'INFO', 'AERO', 'ARPA', 'TRAVEL', 'MUSEUM', 'US', 'CA', 'UK', 'GB', 'FR', 'RU', 'AC', 'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AN', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BM', 'BN', 'BO', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'ER', 'ES', 'ET', 'EU', 'FI', 'FJ', 'FK', 'FM', 'FO', 'GA', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'ST', 'SU', 'SV', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TP', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'YU', 'ZA', 'ZM', 'ZW'];
  function _udTrim(s)
  {
    var m = s.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    return m == null ? '' : m[1];
  }

  globalUtils.ValidateEmailFormat = function(source, args)
  {
    var s, m, i;
    args.IsValid = true;
    s = _udTrim(args.Value);
    if (s == '')
      return;
    m = s.match(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/);
    if (m != null && m.length > 0)
    {
      s = s.substr(s.lastIndexOf('.') + 1).toUpperCase();
      for (i = 0; i < _UdDomainNames.length; i++)
      {
        if (s == _UdDomainNames[i])
          return;
      }
    }
    args.IsValid = false;
  }
  globalUtils.validateCheckBoxList = function(validator)
  {
    var list = document.getElementById(validator.controltovalidate);
    var items = list.getElementsByTagName('INPUT');

    if (items != null)
    {
      for (var i = 0; i < items.length; i++)
      {
        if (items[i].checked)
          return true;
      }

      return false;
    }

    return true;
  }
  globalUtils.$ = function(id)
  {
    return (document.all) ? document.all[id] : document.getElementById(id);
  }

  globalUtils.handleCancalClick = function(myValidationGroup)
  {
    if (!DataChangeWatcher.confirmIfDataChanged())
    {
      globalUtils.updateValidators(myValidationGroup);
      return false;
    }
    else
    {
      Page_IsValid = true;
      Page_BlockSubmit = false;
      return true;
    }
  }

  globalUtils.updateValidators = function(myValidationGroup)
  {
    for (var i = 0; i < Page_Validators.length; i++)
    {
      ValidatorValidate(Page_Validators[i], myValidationGroup, null);
    }
  }

  globalUtils.stopEventPropogation = function(e)
  {
    if (document.all)
    {
      e.cancelBubble = true;
    }
    else
    {
      e.stopPropagation();
    }
  }

  globalUtils.addHandler = function(obj, event, handler)
  {
    if (typeof (obj.addEventListener) != 'undefined')
    {
      obj.addEventListener(event, handler, false);
    }
    else if (typeof (obj.attachEvent) != 'undefined')
    {
      obj.attachEvent('on' + event, handler);
    }
    else
    {
      var hProp = '_handlerStack_' + event;
      var eProp = 'on' + event;
      if (typeof (obj[hProp]) == 'undefined')
      {
        obj[hProp] = new Array();
        if (typeof (obj[eProp]) != 'undefined')
        {
          obj[hProp].push(object[eProp]);
        }
        obj[eProp] = function(e)
        {
          var ret = true;
          for (var i = 0; ret != false && i < obj[hProp].length; i++)
          {
            ret = obj[hProp][i](e);
          }
          return ret;
        }
      }
      obj[hProp].push(handler);
    }
  }

  globalUtils.removeHandler = function(obj, event, handler)
  {
    if (typeof (obj.removeEventListener) != 'undefined')
    {
      obj.removeEventListener(event, handler, false);
    }
    else if (typeof (obj.detachEvent) != 'undefined')
    {
      obj.detachEvent('on' + event, handler);
    }
    else
    {
      var hProp = '_handlerStack_' + event;
      if (typeof (obj[hProp]) != 'undefined')
      {
        for (var i = 0; i < obj[hProp].length; i++)
        {
          if (obj[hProp][i] == handler)
          {
            obj[hProp].splice(i, 1);
            return;
          }
        }
      }
    }
  }

  var scrollBarWidth = null;

  globalUtils.getScrollBarWidth = function()
  {
    if (!scrollBarWidth)
    {
      var objDiv = document.createElement('DIV');

      if (objDiv)
      {
        objDiv.style.position = 'absolute';
        objDiv.style.left = objDiv.style.top = '-1000px';
        objDiv.style.width = objDiv.style.height = '100px';
        objDiv.style.overflow = 'scroll';
        objDiv.style.visibility = 'hidden';

        if (document.body)
        {
          document.body.appendChild(objDiv);

          if (objDiv && objDiv.offsetWidth && objDiv.clientWidth)
          {
            scrollBarWidth = objDiv.offsetWidth - objDiv.clientWidth;
          }
        }
      }
    }

    if (objDiv)
    {
      objDiv.parentNode.removeChild(objDiv);
    }

    return scrollBarWidth;
  }

  globalUtils.isSetAdminViewMainContainerSizeHandler = false;
  globalUtils.timeoutSetAdminViewMainContainerSize = null;

  globalUtils.setAdminViewMainContainerSize = function()
  {
    if (globalUtils.timeoutSetAdminViewMainContainerSize)
      clearTimeout(globalUtils.timeoutSetAdminViewMainContainerSize);

    globalUtils.timeoutSetAdminViewMainContainerSize = setTimeout(globalUtils.setAdminViewMainContainerSizeDo, 100);
  }

  globalUtils.setAdminViewMainContainerSizeDo = function()
  {
    var isIE = (document.all) ? true : false;
    var adminViewMainContainer = document.getElementById('idAdminViewMainContainer');
    var adminViewPanelHolder = document.getElementById('idAdminPanelHolder');
    var adminViewContentFrame = document.getElementById('contentFrame');

    if (adminViewMainContainer && adminViewPanelHolder && adminViewContentFrame)
    {
      var newWidth = isIE ? globalUtils.getVisibleClientWidth() : window.innerWidth;
      var newHeight = isIE ? globalUtils.getVisibleClientHeight() : window.innerHeight;

      if (newWidth > 1)
        adminViewContentFrame.style.width = (newWidth - 1) + 'px';

      newHeight -= adminViewPanelHolder.offsetHeight;

      if (newHeight > 0)
        adminViewContentFrame.style.height = newHeight + 'px';

      if (!globalUtils.isSetAdminViewMainContainerSizeHandler)
      {
        if (isIE)
        {
          window.attachEvent('onresize', globalUtils.setAdminViewMainContainerSize);
        }
        else
        {
          window.addEventListener('resize', globalUtils.setAdminViewMainContainerSize, false);
        }

        globalUtils.isSetAdminViewMainContainerSizeHandler = true;
      }
    }
    else
    {
      setTimeout(globalUtils.setAdminViewMainContainerSizeDo, 10);
    }
  }

  globalUtils.docForSize = null;

  globalUtils.getDocForSize = function()
  {
    if (globalUtils.docForSize == null)
    {
      globalUtils.docForSize = document.getElementsByTagName('HTML');

      if (globalUtils.docForSize && globalUtils.docForSize.length)
        globalUtils.docForSize = globalUtils.docForSize[0];
      else
        globalUtils.docForSize = document.body;
    }

    return globalUtils.docForSize;
  }

  globalUtils.getVisibleClientWidth = function()
  {
    var docForSize = globalUtils.getDocForSize();
    return ((docForSize.clientWidth > 0) ? docForSize.clientWidth : document.body.clientWidth);
  }

  globalUtils.getVisibleClientHeight = function()
  {
    var docForSize = globalUtils.getDocForSize();
    return ((docForSize.clientHeight > 0) ? docForSize.clientHeight : document.body.clientHeight);
  }

  globalUtils.scrollIntoView = function(container, target)
  {
    if (typeof (container) == 'window')
    {
      globalUtils.getXY(target);
      container.scrollTo(0, target.Y + 20);
    }
    else
    {
      globalUtils.getXY(container);
      globalUtils.getXY(target);
      container.scrollTop = (target.Y - container.Y);
    }
  }



  globalUtils.getTextareaLength = function(obj)
  {
    var value = obj.value;

    value = value.replace(/\r\n/g, "\n");
    value = value.replace(/\n/g, "\r\n");

    return value.length;
  }

  globalUtils.getXY = function(obj)
  {
    var parTemp;
    obj.X = 0;
    obj.Y = 0;

    if (obj.offsetParent)
    {
      parTemp = obj;

      while (parTemp.offsetParent)
      {
        parTemp = parTemp.offsetParent;
        obj.X += parTemp.offsetLeft;
        obj.Y += parTemp.offsetTop;
      }
    }

    obj.X += obj.offsetLeft;
    obj.Y += obj.offsetTop;

    return { x: obj.X, y: obj.Y };
  }

  globalUtils.getAbsoluteXY = function(obj)
  {
    var parTemp;
    obj.X = 0;
    obj.Y = 0;

    if (obj.parentNode)
    {
      parTemp = obj;

      while (parTemp.nodeName.toUpperCase() != 'BODY')
      {
        parTemp = parTemp.parentNode;
        var position = BonaPage.getElementStyle(parTemp, 'position').toLowerCase();

        if (position == 'absolute' || position == 'relative')
        {
          obj.X += parTemp.offsetLeft;
          obj.Y += parTemp.offsetTop;
        }
      }
    }

    obj.X += obj.offsetLeft;
    obj.Y += obj.offsetTop;

    return { x: obj.X, y: obj.Y };
  }


  globalUtils.validateIntType = function(source, args)
  {
    var data = args.Value;
    args.IsValid = true;

    if (data.charAt(0) == '-')
    {
      args.IsValid = false;
    }
    if (args.IsValid && isNaN(data))
    {
      args.IsValid = false;
    }
  }

  globalUtils.validateIntTypePositive = function(source, args)
  {
    globalUtils.validateIntType(source, args);

    if (!args.IsValid)
    {
      return;
    }

    var data = args.Value;
    args.IsValid = data > 0;
  }

  globalUtils.validatePriceType = function(source, args)
  {
    var maxPrice = 922337203685477.5807;
    // accepted patterns
    var money_exp1 = /^\s*-?(\d+\,?)*\.?\d*$/;
    var money_exp2 = /^\s*\((\d+\,?)*\.?\d*\)$/;
    if (args.Value.search(money_exp1) == -1 &&
		args.Value.search(money_exp2) == -1)
    {
      args.IsValid = false;
      return args.IsValid;
    }
    var val, ndx, data;
    var pos1 = -1, pos2 = -1;
    val = '';
    data = args.Value;
    // skip white spaces
    ndx = 0;
    while (ndx < data.length &&
			(data.charAt(ndx) == '(' || data.charAt(ndx) == ' '))
    {
      ndx++;
    }

    if (data.charAt(ndx - 1) == '(')
    {
      // negative value
      val += '-';
    }
    while (ndx < data.length)
    {
      if (data.charAt(ndx) != ',' && data.charAt(ndx) != ')')
        val += data.charAt(ndx);
      ndx++;
    }
    if (data.charAt(0) == '-')
    {
      args.IsValid = false;
    }
    if (data == '')
    {
      args.IsValid = true;
    }
    if (args.IsValid)
    {
      var digitsPrice = parseFloat(val);
      if (isNaN(digitsPrice))
      {
        args.IsValid = false;
      }
      if (digitsPrice > maxPrice)
      {
        args.IsValid = false;
      }
    }
    return args.IsValid;
  }
  globalUtils.collectContainerDataState = function(containerId)
  {
    var control = document.getElementById(containerId);

    if (!control)
    {
      return '';
    }

    var state = '';
    var inputs = control.getElementsByTagName('INPUT');

    for (var i = 0; i < inputs.length; i++)
    {
      var input = inputs[i];

      if ((input.type == 'checkbox' || input.type == 'radio') && input.checked)
      {
        state += input.value;
      }
      else if (input.type == 'text')
      {
        state += input.value;
      }
    }

    var textAreas = control.getElementsByTagName('TEXTAREA');

    for (var i = 0; i < textAreas.length; i++)
    {
      state += textAreas[i].value;
    }

    var selects = control.getElementsByTagName('SELECT');

    for (var i = 0; i < selects.length; i++)
    {
      state += selects[i].selectedIndex;
    }

    return state;
  }
  globalUtils.validateStateChanged = function(args, containerId)
  {
    var control = document.getElementById(containerId);

    if (!control)
    {
      return '';
    }

    var state = globalUtils.collectContainerDataState(containerId);

    DataChangeWatcher.changeValidatorCustom(containerId, state, args);
  }
  var stopReplaceLinksForPreview = false;
  var intervalReplaceLinksForPreview = null;
  var countReplaceLinksForPreview = 0;

  globalUtils.replaceLinksForPreview = function()
  {
    var docLinks, linksHref;
    var emulModeMatch = window.location.search.match(/emulatemode=(\d+)/i);
    var emulMode = (emulModeMatch && emulModeMatch.length == 2) ? emulModeMatch[1] : 1;

    if (document.links && document.links.length > countReplaceLinksForPreview)
    {
      while (countReplaceLinksForPreview < document.links.length)
      {
        if (document.links[countReplaceLinksForPreview] && document.links[countReplaceLinksForPreview].href)
        {
          linksHref = document.links[countReplaceLinksForPreview].href;

          if (linksHref.indexOf('javascript:') == -1 && linksHref.indexOf('emulatemode=') == -1)
          {
            var filterRegex = /^([^#]+)(#?.*)$/ig;
            var querySeparator = (linksHref.indexOf('?') == -1) ? '?' : '&';

            document.links[countReplaceLinksForPreview].href = linksHref.replace(filterRegex, '$1' + querySeparator + 'emulatemode=' + emulMode + '$2');
          }
        }

        countReplaceLinksForPreview++;
      }
    }

    if (stopReplaceLinksForPreview)
    {
      if (intervalReplaceLinksForPreview)
      {
        clearInterval(intervalReplaceLinksForPreview);
      }

      return;
    }
  }

  globalUtils.startReplaceLinksForPreview = function()
  {
    if (document.all)
    {
      window.attachEvent('onload', function() { stopReplaceLinksForPreview = true; });
    }
    else
    {
      window.addEventListener('load', function() { stopReplaceLinksForPreview = true; }, false);
    }

    intervalReplaceLinksForPreview = setInterval(globalUtils.replaceLinksForPreview, 250);
  }

  globalUtils.getBrowserCapabilitiesData = function()
  {
    var clientCookiesEnabled = false;
    var javascriptEnabled = true;
    var isPlatformCompatible = false;

    setCookie("TestClientCookie", "TestClientCookieValue");
    clientCookiesEnabled = (getCookie("TestClientCookie") == "TestClientCookieValue");
    setCookie("TestClientCookie", "", (new Date("1/1/2000")).toGMTString());
    isPlatformCompatible = javascriptEnabled && (browserInfo.isMSIE60 || browserInfo.isMSIE70 || browserInfo.isMSIE80 || browserInfo.isMSIE90 || browserInfo.isFirefox || browserInfo.isWebKit) && browserInfo.execCommand;

    return (browserInfo.isMSIE60 ? "MSIE 6.0;" : "") +
           (browserInfo.isMSIE70 ? "MSIE 7.0;" : "") +
           (browserInfo.isMSIE80 ? "MSIE 8.0;" : "") +
           (browserInfo.isMSIE90 ? "MSIE 9.0;" : "") +
           (browserInfo.isWebKit ? "WebKit;" : "") +
           (browserInfo.isFirefox ? "Firefox;" : "") +
           (browserInfo.firefoxMajorVersion ? "FirefoxMajorVersion:" + browserInfo.firefoxMajorVersion + ";" : "") +
           (browserInfo.execCommand ? "Exec Command;" : "") +
           (clientCookiesEnabled ? "Client Cookies Enabled;" : "") +
           (isPlatformCompatible ? "Platform Compatible;" : "") +
           (javascriptEnabled ? "Javascript Enabled;" : "");
  }

  function setCookie(name, value, expires, path, domain, secure)
  {
    document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
  }

  function getCookie(name)
  {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";
    var setStr = null;
    var offset = 0;
    var end = 0;
    if (cookie.length > 0)
    {
      offset = cookie.indexOf(search);
      if (offset != -1)
      {
        offset += search.length;
        end = cookie.indexOf(";", offset)
        if (end == -1)
        {
          end = cookie.length;
        }
        setStr = unescape(cookie.substring(offset, end));
      }
    }
    return (setStr);
  }

  globalUtils.nop = function()
  {
  }

})();

if(typeof(Sys) !== "undefined")
  Sys.Application.notifyScriptLoaded();
