﻿var Helper = {
  Browser : {
    getBrowser: function(){ if(!this.browser) this.Detect(); return this.browser; },
    getVersion: function(){ if(!this.version) this.Detect(); return this.version; },
    getOs:      function(){ if(!this.os)      this.Detect(); return this.os; },

    Detect: function () {
      this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
      this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
      this.os = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
      for (var i=0;i<data.length;i++)	{
        var dataString = data[i].string;
        var dataProp = data[i].prop;
        this.versionSearchString = data[i].versionSearch || data[i].identity;
        if (dataString) {
          if (dataString.indexOf(data[i].subString) != -1)
            return data[i].identity;
        }
        else if (dataProp)
          return data[i].identity;
      }
    },
    searchVersion: function (dataString) {
      var index = dataString.indexOf(this.versionSearchString);
      if(index == -1) return;      
      var begin  = index + this.versionSearchString.length + 1;      
      var length = Helper.String.IndexOf(dataString.substring(begin), [" ", ";"]);    
      return dataString.substring(begin, begin + (length>0 ? length : dataString.length - begin + 1));
    },
    dataBrowser: [
      {
        string: navigator.userAgent,
        subString: "Chrome",
        identity: "Chrome"
      },
      { 
        string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
      },
      {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari",
        versionSearch: "Version"
      },
      {
        prop: window.opera,
        identity: "Opera"
      },
      {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
      },
      {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
      },
      {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox"
      },
      {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
      },
      {	// for newer Netscapes (6+)
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
      },
      {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE"
      },
      {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
      },
      { // for older Netscapes (4-)
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
      }
    ],
    dataOS : [
      {
        string: navigator.platform,
        subString: "Win",
        identity: "Windows"
      },
      {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
      },
      {
        string: navigator.userAgent,
        subString: "iPhone",
        identity: "iPhone/iPod"
      },
      {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
      }
    ]
  },
  Dom : {
    AddEvent : function(elem, type, fn, rnd){
      var elem = ((typeof elem == "object")    ? elem : document.getElementById(elem));
      var rnd  = ((typeof elem != "undefined") ? rnd  : null);
      var set  = elem;
      if(!(elem instanceof Array)){
        set = [];
        set[0] = elem;
      }  
      for(var i=0; i<set.length; i++){
        Helper.Dom.AddEventT(set[i], type, fn, rnd);
      }
    },
    AddEventT : function(elem, type, fn, rnd){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      rnd = (rnd ? rnd : "");
      if(elem.attachEvent){
        elem["e"+type+fn+rnd] = fn;
        elem[type+fn+rnd] = function(){
          elem["e"+type+fn+rnd](window.event);
        }
        elem.attachEvent("on"+type, elem[type+fn+rnd]);
      }
      else{
        elem.addEventListener(type, fn, false);
      }
    }, 
    AddAttribute : function(elem, attrName, attrValue){
      var elem = ((typeof elem == "object")    ? elem : document.getElementById(elem));
      var rnd  = ((typeof elem != "undefined") ? rnd  : null);
      var set  = elem;
      if(!(elem instanceof Array)){
        set = [];
        set[0] = elem;
      }  
      for(var i=0; i<set.length; i++){
        Helper.Dom.AddAttributeT(set[i], attrName, attrValue);
      }
    },
    AddAttributeT : function(elem, attrName, attrValue){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));     
      newAttribute = document.createAttribute(attrName);
      newAttribute.nodeValue = (attrValue != "" ? attrValue : "");
      elem.setAttributeNode(newAttribute);
    },    
    GetAttribute : function(elem, attrName){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));     
      return (elem.getAttribute(attrName) != null ? elem.getAttribute(attrName) : null);
    }
  },
  Ajax : {
    Send : function(url, method, type, callbackFunction, errorFunction){
      method = (method != null ? method : "GET");
      type   = (type   != null ? type   : true);
      
      var req = Helper.Ajax.CreateHttpRequest();
      req.open(method, url, type);
      req.onreadystatechange = function(){
        if(req.readyState == 4){
          callbackFunction(req.responseText); 
        }
      }    
      req.send(null);
    },
    SendAPI : function(url, method, type, ctrl, callbackFunction, errorFunction){
      method = (method != null ? method : "GET");
      type   = (type   != null ? type   : true);
      
      var req = Helper.Ajax.CreateHttpRequest();
      req.open(method, url, type);
      req.onreadystatechange = function(){
        if(req.readyState == 4){
          callbackFunction({control: ctrl, response: req.responseText}); 
        }
      }    
      req.send(null);
    },
    CreateHttpRequest : function(){
      if(typeof XMLHttpRequest != "undefined"){   
        return new XMLHttpRequest();
      }
      else if(typeof ActiveXObject != "undefined" ){
        try{       
          return new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e){
          try{
            return new ActiveXObject("Microsoft.XMLHTTP");
          }
          catch(e){
            return null;
          }
        }
      }
      else{
        return null;
      }
    }
	},
	Url : {
    GetParam : function(paramName){  
      query = window.location.search.substring(1);
      paramValue = "";
      pairs = query.split("&");
      for(i=0; i<pairs.length; i++) {
        pos = pairs[i].indexOf("=");
        argname = pairs[i].substring(0,pos).toLowerCase();
        value = pairs[i].substring(pos+1);
        if(argname == paramName) paramValue = value;
      }
      return paramValue;
    },
    Encode : function(pValue){
       var str = escape(pValue);
       str = str.replace(/\+/g,"%2B");
       str = str.replace(/%20/g,"+");
       return str;
    },
    Decode : function(pValue){
       var str = pValue.replace(/\+/g," ");
       str = unescape(str);
       return str;
    }
	},
  Gui : {
    AddActiveX : function(id, classId, type, url, params, container, width, height){
      container = ((typeof container == "object") ? container : document.getElementById(container));
      newObj = '';
      if(container){
        width  = ((width  != null) ? width  : "100%");
        height = ((height != null) ? height : container.clientHeight);
        
        newObj = '<object id="'+id+'" classid="'+classId+'" type="'+type+'" width="'+width+'" height="'+height+'">';
        newObj+= '<param name="src" value="'+url+'">';   // FF
        newObj+= '<param name="url" value="'+url+'">';   // IE     
        for(p in params) if(params[p])	newObj += '<param name="'+p+'" value="'+params[p]+'">';
        newObj+= '<embed id="'+id+'Embad" width="'+width+'" height="'+height+'" src="'+url+'"';
        for(p in params) if(params[p])	newObj += ' ' + p+'="'+(params[p] == "true" ? "1" : (params[p] == false ? "0" : params[p]))+'"';
        newObj+= '><\/embed><\/object>';
        container.innerHTML = newObj;
      }
      else{ alert("Exception: Component does not exists"); }
      return newObj;
    },
    CreateActiveX : function(id, classId, type, url, params, width, height){
      width  = ((width  != null) ? width  : "100%");
      height = ((height != null) ? height : "100%");
      
      newObj = '<object id="'+id+'" classid="'+classId+'" type="'+type+'" width="'+width+'" height="'+height+'">';
      newObj+= '<param name="src" value="'+url+'">';
      for(p in params) if(params[p])	newObj += '<param name="'+p+'" value="'+params[p]+'">';
      newObj+= '<embed id="'+id+'Embad" width="'+width+'" height="'+height+'" src="'+url+'"';
      for(p in params) if(params[p])	newObj += ' ' + p+'="'+(params[p] == "true" ? "1" : (params[p] == false ? "0" : params[p]))+'"';
      newObj+= '><\/embed><\/object>';
      container.innerHTML = newObj;
      return newObj;
    },
    GetElementPosition : function(elem){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));     
      var point = {x: 0, y: 0};	  
      point.x = elem.offsetLeft; 
      point.y = elem.offsetTop;
      return point;
    },
    HasHScrollbar : function(elem){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      return (elem.offsetHeight - elem.scrollHeight < 0);
    },
    SetStyle : function(elem, property, value){
      if (!property) return false;
      var map = property;
      if(typeof property != "object"){
        map = {};
        map[property] = value;
      }
      for(property in map) {
        if((value = map[property]) != null){
          elem.style[property] = value;
        }
      }
    },
    SetClass : function(elem, className){
      var elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      elem.className = className;
    },
    IsVisible : function(elem){
      var elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      return (elem.style.display != "none" || elem.style.visibility != "hidden") ? "true" : "false";
    },
    SetVisible : function(elem, visible){
      var elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      var set = elem;
      if(!(elem instanceof Array)){
        set = [];
        set[0] = elem;
      }
      for(i=0; i<set.length; i++){
        Helper.Gui.SetVisibleT(set[i], visible)
      }
    },
    SetVisibleT : function(elem, visible){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem)); 
      if(visible == true){
        elem.style.display = 'block';
        elem.style.visibility = "visible";
      }	  
      else{
        elem.style.display = 'none';
        elem.style.visibility = "hidden";	  
      }
    },
    ToggleVisible : function(elem){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      if(elem.style.display == 'none'){
        elem.style.display = '';
        elem.style.visibility = "visible";	  
      }	  
      else{
        elem.style.display = 'none';
        elem.style.visibility = "hidden";	  
      }
    },
    SetOpacity : function(elem, value){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      var value = (value < 0 ? 0 : (value > 100 ? 100 : value));
      elem.style.opacity = value / 100;
      elem.style.filter = 'alpha(opacity=' + value + ')';
    },
    SetEnabled : function(elem, isEnabled){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));  
      function ds(e){return false;}
      function ra(){return true;}
      if(isEnabled == false){
        elem.disabled = false;
        elem.style.color = elem.style.colorDisabled = (elem.style.colorDisabled ? elem.style.colorDisabled : "#888");
        elem.style.cursor = "wait";
        elem.onclick = ds;
      }	  
      else{
        elem.disabled = false;
        elem.style.color = elem.style.colorEnabled = (elem.style.colorEnabled ? elem.style.colorEnabled : "#000");
        elem.style.cursor = "pointer";
        elem.onclick = ra;
      }
    },
    SetUnselectable : function(elem, isUnselectable){
      var elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      var set = elem;
      if(!(elem instanceof Array)){
        set = [];
        set[0] = elem;
      }
      for(i=0; i<set.length; i++){
        Helper.Gui.SetUnselectableT(set[i], isUnselectable)
      }
    },
    SetUnselectableT : function(elem, isUnselectable){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));          
      function ds(e){return false;}
      function ra(){return true;}
      elem.onselectstart = new Function('return false');      
      elem.onmousedown = ds;
      if(isUnselectable == true) elem.onclick = ra;
    },
    SetText : function(elem, text){
      var elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      var set = elem;
      if(!(elem instanceof Array)){
        set = [];
        set[0] = elem;
      }
      for(i=0; i<set.length; i++){
        Helper.Gui.SetTextT(set[i], text)
      }
    },  
    SetTextT : function(elem, text){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      elem.innerHTML = text;   
    },
    SetLink : function(elem, url){
      var elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      var set = elem;
      if(!(elem instanceof Array)){
        set = [];
        set[0] = elem;
      }
      for(i=0; i<set.length; i++){
        Helper.Gui.SetLinkT(set[i], url)
      }
    },    
    SetLinkT : function(elem, url){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem));
      elem.href = url;   
    },
    ToggleHeight : function(elem, h1, h2){
      elem = ((typeof elem == "object") ? elem : document.getElementById(elem)); 
      elem.style.height = ((elem.style.height == (h1 + 'px')) ? h2 : h1) + 'px';
    },
    DlgCloneValue : function(target, dest){
      target = ((typeof target == "object") ? target : document.getElementById(target));    
      dest = ((typeof dest == "object") ? dest : document.getElementById(dest));    
      for(i=0; i<dest.length; i++) document.getElementById(dest[i]).value = target.value;  
    },
    DlgFillCmb : function(combo, value, text, defValue){
      combo = (typeof(combo) == 'object' ? combo : document.getElementById(combo));      
      for(i=0; i<value.length; i++){  
        if(value[i] == defValue){
          combo.options[i] = new Option(value[i], text[i]);  
          combo.options[i].selected = true;
        }
        else{
          combo.options[i] = new Option(value[i], text[i]);
        }
      }  
    },
    DlgSelectItem : function(combo, value){
      combo = (typeof(combo) == 'object' ? combo : document.getElementById(combo));          
      for(i=0; i<combo.options.length; i++){  
        if(combo.options[i].value == value){
          combo.options[i].selected = true;
          return true;
        }
      }  
    } 
  },
  Controls : {
    DataBind : function(dataSourceType, dataSourceDetails, ctrl, callbackFunction){
      dataSourceType    = (typeof dataSourceType != 'undefined'     ? dataSourceType    : "url");
      dataSourceDetails = (typeof dataSourceDetails != 'undefined'  ? dataSourceDetails : null);
      
      if(dataSourceType == "url"){
        dataSourceDetails.url = (typeof dataSourceDetails.url != 'undefined'  ? dataSourceDetails.url : null);
        if(dataSourceDetails.url){
          Helper.Ajax.SendAPI(dataSourceDetails.url, "GET", true, ctrl, callbackFunction);
        }
      }
      else{
        dataSourceDetails.enumeration = (typeof dataSourceDetails.enumeration != 'undefined'  ? dataSourceDetails.enumeration : null);
        if(dataSourceDetails.enumeration){       
          source = dataSourceDetails.enumeration;
          var _value = new Array();
          var _name = new Array();
          var i = 0;
          for(var item in source) {
            _value[i] = source[item].VALUE.substr(0, 1).toUpperCase() + source[item].VALUE.substr(1, source[item].VALUE.length-1);
            _name[i]  = source[item].TITLE.substr(0, 1).toUpperCase() + source[item].TITLE.substr(1, source[item].TITLE.length-1);
            i++;
          }      
          callbackFunction({control: ctrl, response: {name: _name, value: _value}});
        }
      }
    },
    Combobox : {
      Fill : function(AJAXCallback){
        AJAXCallback.control  = (typeof AJAXCallback.control == 'object'      ? AJAXCallback.control  : document.getElementById(AJAXCallback.control));
        AJAXCallback.response = (typeof AJAXCallback.response != 'undefined'  ? AJAXCallback.response : null);
        
        var name  = null;
        var value = null;
        if(AJAXCallback.response){
          if(typeof AJAXCallback.response.name != "undefined" && typeof AJAXCallback.response.value != "undefined"){
            name  = AJAXCallback.response.name;
            value = AJAXCallback.response.value;
          }
          else{
            name = value = AJAXCallback.response.split(';');          
          }
        }
        Helper.Debug.Assert.IsNull(AJAXCallback.control, "Exception: Combobox does not exists");
        
        for(var i=0; i<name.length; i++)
          AJAXCallback.control.options[i] = new Option(name[i], value[i]);
      }      
    }
  },
  Mouse : {
    GetLocation : function(e){
      var point = {x:0, y:0};
      if (!e) var e = window.event;
      if (e.pageX || e.pageY){
        point.x = e.pageX;
        point.y = e.pageY;
      }
      else if (e.clientX || e.clientY){
        point.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
        point.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
      }
      return point;
    }
  },
  Time : {
    Get : function(){
      d = new Date();
      return d.getTime();    
    }
  },
  Integer : {
    ParseInt : function(text, delimiter){
      peaces = text.split(delimiter);
      integer = peaces[0];
      return integer;
    },
    Rnd : function(max, zeroBased){
      zeroBased = (typeof zeroBased != "undefind" ? zeroBased : false); 
      rnd = Math.round(Math.random() * max);
      return (zeroBased == true ? rnd : rnd + 1);
    }
  },
  String : {
    IndexOf : function(text, delimiter){
      distance = new Array();
      for(var i=0; i<delimiter.length; i++){
        d = text.indexOf(delimiter[i]);
        if(d > 0) distance.push(d);
      }
      return (distance.length > 0 ? Helper.Array.Min(distance, true) : -1);
    },
    Pad : function(ch, length){	
      str = new String();
      for(var i=0; i<length; i++) str += ch;
      return str;
    },
    LiteralWrite : function(obj, outputIfNull) {
      return ((typeof obj  != 'undefined') || (obj != null)) ? obj : (typeof outputIfNull != 'undefined' ? outputIfNull : "");
    }
  },
  Array : {
    Min : function(array, positiveOnly){	
      positiveOnly = (typeof positiveOnly != "undefined") ? positiveOnly : null;
      min = array[0];
      for(var i=0; i<array.length; i++)
        if(array[i] < min && (positiveOnly && array[i]>0))
          min = array[i];
      return min;
    },
    Max : function(array, positiveOnly){
      positiveOnly = (typeof positiveOnly != "undefined") ? positiveOnly : null;
      max = array[0];
      for(var i=0; i<array.length; i++)
        if(array[i] > max && (positiveOnly && array[i]>0))
          max = array[i];
      return max;
    },
    Unique : function(array){
      var a = [];
      var l = array.length;
      for(var i=0; i<l; i++) {
        for(var j=i+1; j<l; j++) {
          // If this[i] is found later in the array
          if (array[i] === array[j])
            j = ++i;
        }
        a.push(array[i]);
      }
      return a;
    },
    UniqueA : function(array){
      var unique = new Array(); 
      var uniqueCount = new Array();
      var isUnique = true;
                  
      for(i=0; i<array.length; i++){
        isUnique = true;
        for(j=0; j<unique.length; j++){
          if(array[i] === unique[j]){
            uniqueCount[j]++;
            isUnique = false;              
          }
        }// add as unique
        if(isUnique == true){
          unique.push(array[i]);
          uniqueCount.push(1);
        }
      }
      return {array: unique, arrayCount: uniqueCount};
    }  
  },
  Debug : {
    TypeInfo : function(obj){
      objType = typeof(obj);
      
      isObject = obj instanceof Object;
      isArray = obj instanceof Array;
      isString = obj instanceof String;

      instanceOf  = new String();
      instanceOf += (isObject ? "Object, " : "");
      instanceOf += (isArray  ? "Array, "  : "");
      instanceOf += (isString ? "String, " : "");
      instanceOf = instanceOf.RTrim(", ");
     
      contents = "";
      if(isString || objType == "string")
        contents = obj;
      else if(isArray)
        for(i=0; i<obj.length; i++)
          contents += i + " : " + obj[i] + "\n";
      else if(isObject)
        for(property in obj)
          contents += property + " : " + obj[property] + "\n";
      else
        contents = "Unknown object type";
        
      return ("Object type: " + objType + "\nInstance of: " + instanceOf + "\n\nContents:\n" + contents);
    },
    Assert : {
      IsNull : function(obj, errMsg){
        obj = ((typeof obj == "object" || (typeof obj == "string")) ? obj : document.getElementById(obj));
        if(obj == null){
          alert(errMsg);
        }
      }
    }
  }
};

var ClassId = {
  MediaPlayer: "CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6",
  QuickTime: "clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B",
  Flash: "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
};
var MimeType = {
  MediaPlayer: "application/x-ms-wmp",
  QuickTime: "video/quicktime",
  Flash: "application/x-shockwave-flash"
};
