// naamespace
lms = {};
// core class
lms.Core = {

  /*
   **  Shortcut to document.getElementById
   **  Returns an object given its id as a string.
   **  Return value ref to the object or null
  */
  $ : function(id) {
    return document.getElementById(id);
  },
  
  
  /*
   **  Helper to get elements by class name
   **  param: o = optional parent element.
   **  param: tn = optional only search within specific html tag .
   **  param: cn = css class name to search for.
   **  Returns an array of objects given of the given css class name
  */
  $cn : function(obj, tagName, className){
    var el = (tagName == "*" && obj.all)? obj.all : obj.getElementsByTagName(tagName);
    var ret = [];
    className = className.replace(/\-/g, "\\-");
    var re = new RegExp("(^|\\s)" + className + "(\\s|$)");
    var e;
    for(var i=0; i<el.length; i++){
      e = el[i];
      if(re.test(e.className)){
        ret.push(e);
      }
    }
    return (ret)
  },
  
  $cn2 : function(node,tag,className) {
    var classElements = [];
    if ( node == null ) { node = document; }
    if ( tag == null ) { tag = '*'; }
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+className+"(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
      if ( pattern.test(els[i].className) ) {
        classElements[j] = els[i];
        j++;
      }
    }
    return classElements;
  },
  
  
  GetNextSibling : function(startBrother){
    endBrother=startBrother.nextSibling;
    while(endBrother.nodeType!=1){
      endBrother = endBrother.nextSibling;
    }
    return endBrother;
  },
  


  /*
   ** Shortcut to create input element
   ** param: type = type of input to create i.e. text, button submit etc.
   ** param: id = id of the new input.
   ** param: className = css className for the new input.
   ** param: name = name of the new input.
   ** param: value = value of the new input.
  */
  Input : function(type, id, className, name, value) {
    var o = document.createElement("input");
    o.type=type?type:'text';

    if(id) { o.id=id };
    if(className) { o.className=className };
    if(name) { o.name=name };
    if(value) { o.value=value };

    return o;
  },


  /*
   ** Shortcut to create input element
   ** param: type = type of input to create i.e. text, button submit etc.
   ** param: id = id of the new input.
   ** param: className = css className for the new input.
   ** param: name = name of the new input.
   ** param: value = value of the new input.
  */
  Element : function(type, id, className, name, value) {
    if(type) {
      var o = document.createElement(type);
      if(id) { o.id=id };
      if(className) { o.className=className };
      if(name) { o.name=name };
      if(value) { o.value=value };
      return o;
    }
    return null;
  },
  
  
  /*
   ** Shortcut to create cross browser radio button
   ** param: name = name of the new input.
   ** param: value = value of the new input.
   ** param: checked = true if button state is checked.
  */
  Radio : function(name, value, checked) {    
    var r = '<input type="radio" name="' + name + '"'; 
    if (value) { r += ' value="' + value + '"'; };       
    //if (checked) { r += ' checked="checked"'; };
    r += '/>';    
    var o = document.createElement('div');    
    o.innerHTML = r;    
    return o.firstChild;
  },
  
  /*
   ** Create cross browser xmlhttprequest object
   ** 
  */
  XmlHttp : function() {
    var x;
    try {
      x = new XMLHttpRequest();
    } catch (e) {
      var m = new Array();
      m.push('MSXML2.XMLHTTP.6.0');
      m.push('MSXML2.XMLHTTP.5.0');
      m.push('MSXML2.XMLHTTP.4.0');
      m.push('MSXML2.XMLHTTP.3.0');
      m.push('MSXML2.XMLHTTP');
      m.push('Microsoft.XMLHTTP');    
      var success = false;
      for (var i=0;i < m.length && !success; i++) {
        try {
          x = new ActiveXObject(m[i]);
          success = true;
        } catch (e) {}
      }
      if (!success) {
        throw new Error('Unable to create XMLHttpRequest.');
      }
    }
    return x;
  },
  
  
  /*
   **  Returns the objects selected text
   **  Returns an object given its id as a string.
   **  param: obj = object that has selected text.
  */
  Selection : function(el) {
    if (el.setSelectionRange)
      return el.value.substring(el.selectionStart, el.selectionEnd)
    else if (document.selection && document.selection.createRange)
	  return document.selection.createRange().text.replace(/(^\s+|\s+$)/g,'');
  },
  
  
  /*
   **  Returns nothing
   **  param: col = array of element id to make equal.
  */
  EqualizeColumns : function(col, reset) { 
    var columns=col;
    var tallest=0;
    var resetit=(typeof reset=='string')? true : false;
    
    // find the tallest
    for (var i=0; i<columns.length; i++){
      var c = $c.$(columns[i]);
      if (c!=null){
        if (resetit) {c.style.height='auto';}        
        if (c.offsetHeight>tallest) {tallest=c.offsetHeight;}
      }
    }
    
    //alert('header 280px + tallest ' + tallest +'px = ' + (tallest+280));
    var cs = $c.ClientSize();
    var h = 280;
    tallest = (cs[1]-h-5)>tallest?(cs[1]-h-5):tallest;
    // set to same size
    if (tallest>0){
      for (var i=0; i<columns.length; i++){
        var c = $c.$(columns[i])
        if (c!=null){c.style.height=tallest+'px'}
      }
    }
  },
  
  ClientSize : function() {
  var myWidth = 0;
  var myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  //window.alert( 'Width = ' + myWidth );
  //window.alert( 'Height = ' + myHeight );
  return [myWidth, myHeight] ;
}, 

  
  
  // event opject
  Event : {
    Add : function(obj,type,fn) {
      if (obj.attachEvent) {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function() { obj['e'+type+fn](window.event); }
        obj.attachEvent('on'+type,obj[type+fn]);
      } else
        obj.addEventListener(type,fn,false);
      },

    Remove : function(obj,type,fn) {
      if (obj.detachEvent) {
        obj.detachEvent('on'+type,obj[type+fn]);
        obj[type+fn] = null;
      } else
      obj.removeEventListener(type,fn,false);
    },
    
    PreventDefault : function(e) {
      if (e && e.preventDefault) e.preventDefault();
      else if (window.event) window.event.returnValue = false;
    },
    
    Custom: function() {
      var events = {};
      return {
        Subscribe: function(eventName, callback) {
          var e = events[eventName];
          if(e) {
            for (i = 0; i < e.length; i++) {
              if(e[i] == callback) { return; }
            }
          } 
          events[eventName] = events[eventName] || [];
          events[eventName].push(callback);
        },
        
        UnSubscribe: function(eventName, callback) {
          var e = events[eventName];
          if(e) {
            for (i = 0; i < e.length; i++) {
              if(e[i] == callback) { 
                delete events[eventName]; 
                return; 
              }
            }
          } 
        },
        
        Publish: function(eventName) {
          var i, callbacks = events[eventName], args;
          if (callbacks) {
            args = Array.prototype.slice.call(arguments, 1);
            for (i = 0; i < callbacks.length; i++) {
              callbacks[i].apply(null, args);
            }
          }
        }
      }
    } ()

  }, // event end
  
  
  // object to hold screen size
  Bounds : {
    Top : function() {
      var o=this.GetScrollXY();
      var t = o[0];
      return t;
    },
    
    Left : function() {
      var o=this.GetScrollXY();
      return o[1];
    },
    
    Width : function() {
      var o=this.GetWidthHeight();
      var w = o[0];
      return w;
    },
    
    Height : function() {
      var o=this.GetWidthHeight();
      return o[1];
    },
    
    
    DocumentSize : function() {
      var o = [];
      var wh = this.GetWidthHeight();
      var xy = this.GetScrollXY();
      o.push(wh[0]);
      o.push(wh[1]);
      o.push(xy[0]);
      o.push(xy[1]);
      return o;
    },
    
    GetWidthHeight : function() {
      var w = 0, h = 0;
      if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        w = window.innerWidth;
        h = window.innerHeight;
      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        w = document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        w = document.body.clientWidth;
        h = document.body.clientHeight;
      }
      return [ w, h ];
    },
    
    GetScrollXY : function() {
      var x = 0, y = 0;
      if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        y = window.pageYOffset;
        x = window.pageXOffset;
      } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        x = document.body.scrollTop;
        y = document.body.scrollLeft;
      } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        y = document.documentElement.scrollTop;
        x = document.documentElement.scrollLeft;
      }
      return [ x, y ];
    },
    
    GetElementWidthHeight : function(elm) {
      var w = 0, h = 0;
      if( typeof( elm.innerWidth ) == 'number' ) {
        w = elm.innerWidth;
        h = elm.innerHeight;
      } else if(elm.clientWidth || elm.clientHeight ) {
        w = elm.clientWidth;
        h = elm.clientHeight;
      }
      return [ w, h ];
    }
  } // end bounds object
  
  
}; // end core class

// dialog class
lms.Dialog = function() { 
  var me=this;  
  this.Modal=false;
  this.Draggable=false;
  this.CancelButton=false;
  this.DoneButton=false;
  this.HeaderText='Dialog Header';
  this.Content=null;
  this.StaticContent=null;
  this.Width=600;
  this.Height=0;
  
  this.CreateDialog=function() {
    var o=$c.Element('div', 'dialog', 'dialog', '', '');
    var h=me.CreateHeader();
    o.appendChild(h);
    var c=$c.Element('div', '', 'content-outer', '', '');
    var s=$c.Element('span', 'content-inner', 'content-inner', '', '');

    if(this.StaticContent) { s.appendChild(this.StaticContent); }
      
    if(this.Content) { s.appendChild(this.Content); }
    else { s.appendChild($c.Element('div', 'content', 'empty-content', '', '')); }
    
    if(this.CancelButton || this.DoneButton) 
      s.appendChild(this.CreateButtons(this.CancelButton, this.DoneButton));  
      
    c.appendChild(s);
    o.appendChild(c);
    o.appendChild(this.CreateFooter());
            
    document.body.appendChild(o);
      
    var d = $c.$('dialog');
    var ds = $c.Bounds.GetElementWidthHeight(d);
    d.style.left = ((($c.Bounds.Width() - ds[0])  / 2) + $c.Bounds.Left()) + 'px';
    d.style.top  = ((($c.Bounds.Height() - ds[1]) / 2) + $c.Bounds.Top()) + 'px';
  };
  
  this.CreateHeader=function() {
    var o=$c.Element('div', 'dialog-header', 'dialog-header', '', '')
    var b=$c.Element('div', 'dialog-header-close', 'dialog-header-close', '', '')
    var e=['click','mouseover','mouseout','mousedown'];
    for(var i=0; i<e.length; i++) { $c.Event.Add(b, e[i], this.OnCloseMouseEvent); }
    o.appendChild(b);
    var s=$c.Element('span', '', 'dialog-header-content', '', '')
    s.innerHTML = this.HeaderText;
    o.appendChild(s);
    if(this.Draggable) {
      var e=['mousemove','mouseup','mousedown'];
      for(var i=0; i<e.length; i++) { $c.Event.Add(o, e[i], this.OnMouseDragEvent); }
    }
      return o;
  };
  
  this.CreateButtons=function(cancel, done) {
    var o=$c.Element('div', 'dialog-buttonbar', '', '', '')              
    if(done) {
      var db=$c.Input('button', 'done', '', '', 'Done') 
      $c.Event.Add(db, 'click', this.OnButtonClick);
      o.appendChild(db);    
    }
    if(cancel) {
      var cb=$c.Input('button', 'cancel', '', '', 'Cancel')
      $c.Event.Add(cb, 'click', this.OnButtonClick);
      o.appendChild(cb);     
    }       
    return o;
  };
  
  this.CreateFooter=function() {
    var o=$c.Element('div', '', 'dialog-footer', '', '')
    var s=$c.Element('span', '', 'dialog-footer-content', '', '')
    o.appendChild(s);
    return o;
  };
  
  this.Dispose=function() {
    $c.Event.Custom.Publish('OnDialogClosing', null);
    this.RemoveEvents();
      document.body.removeChild($c.$('dialog'));
    },
    
    
  this.RemoveEvents=function(e) {
    // remove drag events for header
    if(this.Draggable) {
      var h = $c.$('dialog-header');
      var e=['mousemove','mouseup','mousedown'];
      for(var i=0; i<e.length; i++) { $c.Event.Add(h, e[i], this.OnMouseDragEvent); }
    }
      
    // remove events for cancel button
    if(this.CancelButton)
      $c.Event.Remove($c.$('cancel'), 'click', this.OnButtonClick);
      
    // remove events for done button
    if(this.DoneButton)
      $c.Event.Remove($c.$('done'), 'click', this.OnButtonClick);
        
    // remove events for close button  
    var o=$c.$('dialog-header-close');
    var e=['click','mouseover','mouseout','mousedown'];
    for(var i=0; i<e.length; i++)
    {
      $c.Event.Remove(o, e[i], this.OnCloseMouseEvent);
    } 
  };
    
    
  this.OnClose=function(e) {
    this.Dispose();  
  };
  
  // events 
  this.OnCloseMouseEvent=function(e) {
    var p=0
    switch(e.type)
    {
      case 'click':
        me.Dispose();
      break;
      case 'mouseover':
        p= -18;
        break;
      case 'mousedown':
        p= -36;
      break;
      case 'mouseout':
        p=0; 
      break;
    }
    this.style.backgroundPosition='0px ' + p + 'px';
  };
  
  this.OnButtonClick=function(e) {
    if(this.value=='Cancel') { me.Dispose(); } 
    else { $c.Event.Custom.Publish('OnButtonClick', { Sender:me, EventArgs:e }); }  
  };
  
  this.OnMouseDragEvent=function(e) {
    switch(e.type)
    {
      case 'mouseup':

        break;
      case 'mousedown':

        break;
      case 'mousemove':
      
      break;
    }
  };      
};

// slideshow class
lms.Slideshow = function(container) {
  var me = this;
  this.currentImage = null;
  this.newImage = null;
  this.paused = false;
  this.parent = container;
  
  this.Init = function() {
    this.ChangeSlide();    
  };

  this.ChangeSlide = function() {
    var d=document;
	if(!d.getElementById || !d.createElement)
	  return;

	var p =$c.$(this.parent);
    this.currentImage = p.getElementsByTagName("img")[0];
	this.currentImage.xOpacity = 1;	
	this.newImage = this.GetNewImage();	
	p.insertBefore(this.newImage, this.currentImage);
	 
	setTimeout(this.OnCrossFade,10000);
  };
  
  this.GetNewImage = function() {
    var i = new Image(); 
    //i.src='callback.ashx?sender=slideshow&r=' + Math.random();
    i.src='/resources/slideshow/' +  Math.floor(Math.random()*8) + '.jpg';
    i.style.display = "none"; 
    i.xOpacity = 0;
    return i;
  };
  
  this.CrossFade = function() {
    var cio = this.currentImage.xOpacity;
    var nio = this.newImage.xOpacity;
    this.newImage.style.display = "block";
    cio-=.05; 
    nio+=.05;
    this.currentImage.xOpacity = cio;
    this.newImage.xOpacity = nio;
    
    this.SetOpacity(this.currentImage); 
    this.SetOpacity(this.newImage);
    
    //if(cio<=0 && nio >=.99) {
    if(cio<=0 && nio >=1) {
      this.currentImage.style.display = "none";
      var p = $c.$(this.parent);
      p.removeChild(this.currentImage);
      
      if(!this.paused)
        setTimeout(this.OnChangeSlide,10000);
    } else {
      setTimeout(this.OnCrossFade,50);
    }
  };

  this.SetOpacity = function(obj) {
    if(obj.xOpacity>1) {
      obj.xOpacity = 1;
      //return;
    } else if (obj.xOpacity<0) {
      obj.xOpacity = 0;
      //return;
    }
    obj.style.opacity = obj.xOpacity;
    obj.style.MozOpacity = obj.xOpacity;
    obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")";
  };
  
  this.OnChangeSlide = function() {
    me.ChangeSlide();
  };
  
  this.OnCrossFade = function() {
    me.CrossFade();
  };
} // end slideshow class


Init = function() {
  // global reference to core
  $c = lms.Core;
 
  
  $c.EqualizeColumns(['leftcolumn', 'rightcolumn', 'contentwrapper'], 'reset');
  var ss = new lms.Slideshow('header-logo-band');
  ss.Init(); 
  
  // call init on other page
  if(lms.Page) {
    if(typeof lms.Page.Init == 'function')
      lms.Page.Init();
  }
}

window.onload = Init;