// -- Inializers -- //
var url = location.href; url = url.slice(8,url.length);
var page = url.split("index.html");
var request = null;
var fadesize = null, hideNav = null, hidePor = null, hideCal = null;
var text = "";

// -- Browser Test -- //
var isIE = navigator.appName == 'Microsoft Internet Explorer' && navigator.userAgent.indexOf('Opera') < 1 ? 1 : 0;
var isOp = navigator.userAgent.indexOf('Opera') > -1 ? 1 : 0;
var isGe = navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('Safari') < 1 ? 1 : 0;

function browserFix() {
  if (isGe) { }
  if (isIE && document.styleSheets && document.styleSheets[0]) { 
    document.styleSheets[0].addRule('img', 'behavior: url(http://housing.uah.edu/scripts/iepngfix.htc)');
    document.styleSheets[0].addRule('div', 'behavior: url(http://housing.uah.edu/scripts/iepngfix.htc)');
  }
}
function reloadPreview() {
    var Title = $('Title'); var Msg = $('Comment'); var Time = $('Time'); var User = $('User');
    if(!Msg && !Time && !User) return;
    var message = Msg.value; var title = Title.value;
    var citation = "<h3>"+ title.stripTags() +"</h3>";
    var posted = " <h4>Posted: "+ Time.value +" by "+ User.value +"</h4>\n";
    $('previewComment').innerHTML = citation + posted + message.stripTags();
    $('previewComment').innerHTML = citation + posted + message.stripTags(); 
    Title.onkeyup = function(){ reloadPreview(); }
    Msg.onkeyup = function(){ reloadPreview(); }
}
function allowCheckInTest() {
    var currentInitial = document.getElementById('DAInitials').value;
    var nameRegex = /(.+)\s(.+)/; //var raInitials = ["MM","BK","RB","BS"];
    var guest = new Array(3); var coed = new Array(3); var submit = ''; var i; var result;
    guest[0] = ($('guest1').value != '' ? $('guest1').value : null);
    guest[1] = ($('guest2').value != '' ? $('guest2').value : null);
    guest[2] = ($('guest3').value != '' ? $('guest3').value : null);

    coed[0] = $('coed1').value;
    coed[1] = $('coed2').value;
    coed[2] = $('coed3').value;

    //for(i=0; i< raInitials.length; i++){
      if(currentInitial != ''){
         submit = "<span class='submit'><input type='submit' name='submit' id='submit' value='&nbsp;Check In&nbsp;' /></span>\n";
         //break;
      }
      else{
       //  submit = "<cite>That Is Not A Valid DA Signature</cite>\n";
        submit = "<cite>Please Supply A DA Signature</cite>\n";
      }
    for(i=0; i<3; i++){
      if(guest[i] != null){
        result = nameRegex.exec(guest[i]);
        if(result != null){
          if(coed[i] == 0){
            submit = "<cite>Please Set The Coed Option For Guest "+(i+1)+"</cite>\n";
          }
        }
        else {
          submit = "<cite>Please Supply A First And Last Name For Guest"+(i+1)+"</cite>\n";
        }
      }
    }
    $('AllowCheckIn').innerHTML = submit;
}

//////////////////////////////////
// -- Table Toggle Functions -- //
//////////////////////////////////

function hideRow (rowHead, cellValue) {
  var table = document.all ? document.all.hideTable : document.getElementById('hideTable');
  for (var i = 0; i < table.rows[0].cells.length; i++){
    if(table.rows[0].cells[i].innerHTML == rowHead)
       break;
  }
  for (var r = 0; r < table.rows.length; r++) {
    if(table.rows[r].cells[i].innerHTML == cellValue) {
       table.rows[r].style.display = 'none';
    }
  }
}
function showRow (rowHead, cellValue) {
  var table = document.all ? document.all.hideTable : document.getElementById('hideTable');
  for (var i = 0; i < table.rows[0].cells.length; i++){
    if(table.rows[0].cells[i].innerHTML == rowHead)
       break;
  }
  for (var r = 0; r < table.rows.length; r++) {
    if(table.rows[r].cells[i].innerHTML == cellValue)
       table.rows[r].style.display = '';
  }
}
function hideColumn (colIndex) {
  var table = document.all ? document.all.hideTable : document.getElementById('hideTable');
  for (var r = 0; r < table.rows.length; r++)
    table.rows[r].cells[colIndex].style.display = 'none';
}
function showColumn (colIndex) {
  var table = document.all ? document.all.hideTable : document.getElementById('hideTable');
  for (var r = 0; r < table.rows.length; r++)
    table.rows[r].cells[colIndex].style.display = '';
}
function tableToggle (test, item, box, value) {
  if(test == "row"){
    if($(box).checked)
      hideRow(item,value);
    else
      showRow(item,value);
  }
  else{
    if($(box).checked)
      hideColumn(item);
    else
      showColumn(item);
  }
}

///////////////////////////
// -- Popup Functions -- //
///////////////////////////

function openMediaWindow() {
  var webPage = prompt("What Webpage Would You Like To Play?");
  var link = 'http://playr.hubmed.org/xspf_player.swf?repeat_playlist=false&amp;autoplay=true&amp;playlist_url='+encodeURIComponent('playlistc461.html?url=')+encodeURIComponent(encodeURIComponent(webPage))+encodeURIComponent('&format=.xspf');
  window.open(link,webPage,'width=500,height=211')
}
function openNewWindow(PrintData,Title,height,width) {
  if (isIE) {var screenW = document.body.clientWidth/2, screenH = document.body.clientHeight/2;}
  else      {var screenW = window.outerWidth/2, screenH = window.outerHeight/2;}
  newWindow = window.open("","Title",
                          'width=' + width +
                          ',height=' + height +
                          ',toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no' +
                          ',top=' + (screenH-(height/2)) +
                          ',left=' + (screenW-(width/2)));
  newWindow.document.write(PrintData);
}
function openCheckOutWindow(ID,guest) {
 var CheckOut  = "<body bgcolor='#FFFFFF'>\n"
     + "<form method='post' action='http://housing.uah.edu/Housing/CheckIn/Guests/CheckOut/'>\n"
     + "  <div id='CommentForm' style='background: #EEE; border: solid 1px #888; width: 320px; text-align: center;'>\n"
     + "   <input type='hidden' id='ID' name='ID' value='"+ID+"' />\n"
     + "   <input type='hidden' id='GuestName' name='GuestName' value='"+guest+"' />\n"
     + "<h3>Are You Sure You Want To Check Out "+guest+"?</h3>\n"
     + "    <span class='submit'>\n"
     + "     <input type='submit' id='Yes' name='Yes' value='&nbsp;Yes&nbsp;' onclick=\"setTimeour('opener.location.reload()',500)\" "
     + "style='font-color: #FFF; background: #4CBAE8; padding: 3px; border: solid 1px #419EC5;'/>\n"
     + "     <input type='reset' id='No' name='No' value='&nbsp;No&nbsp;' onClick=\"window.close()\" "
     + "style='font-color: #FFF; background: #4CBAE8; padding: 3px; border: solid 1px #419EC5;'/>\n"
     + "    </span>\n"
     + " </div>\n"
     + "</form>\n"
     + "</body>\n";
     openNewWindow(CheckOut,guest,140,340);
}
function addGuestNote(id, guest, notes) {
 var data  = "<body bgcolor='#FFFFFF'>\n"
     + "<style>\n"
     + "   #commentForm { margin: 1em auto; background: #EEE; border: solid 1px #888; padding: 10px; width: 55%; } "
     + "   #commentForm span, .quickForm span, .maintForm span "
     + "   { display: block; margin: 0; background: #F6F6F6; padding: 2px 4px; border: solid 1px #E6E6E6; border-width: 1px 0; } "
     + "   #commentForm label { width: 150px; float:left; } "
     + "   #commentForm h3, #commentForm p { text-align: center; margin: 0; }"
     + "   #commentForm textarea { width: 315px; }"
     + "   #comment { clear: left; padding: 0 0 0 5px; }"
     + "   .submit input { border: solid 1px #419EC5; color: #FFF; background: #4CBAE8; padding: 3px; float: none; } "
     + "</style> "
     + "<form method='post' action='http://housing.uah.edu/Housing/CheckIn/Guests/EditNotes'>\n"
     + "  <div id='commentForm' style='background: #EEE; border: solid 1px #888; width: 320px; text-align: center;'>\n"
     + "   <input type='hidden' id='ID' name='ID' value='"+id+"' />\n"
     + "   <input type='hidden' id='Guest' name='Guest' value='"+guest+"' />\n"
     + "<h3>Editing Notes For "+guest+"</h3>\n"
     + "    <span class='submit'>\n"
     + "    <textarea rows='4' id='Notes' name='Notes'>" + notes + "</textarea>\n"
     + "    </span>\n"
     + "    <span class='submit'>\n"
     + "     <input type='submit' value='&nbsp;Update&nbsp;' onclick=\"setTimeout('opener.location.reload()',500)\" />"
     + "     <input type='reset' value='&nbsp;Cancel&nbsp;' onClick=\"window.close()\" />"
     + "    </span>\n"
     + " </div>\n"
     + "</form>\n"
     + "</body>\n";
     openNewWindow(data,guest,200,360);
}

//////////////////////////////////////
// -- Specific Housing Functions -- //
//////////////////////////////////////

function makeRequest(feed) {
  document.getElementById('feedHead').innerHTML = "";
  document.getElementById('feedVerbose').innerHTML = "";
  document.getElementById('feedStatus').innerHTML = "";
  var url = "scripts/request8951.php?feed="+feed;
  var action = feedResponse;
  retrieveURL(url, action);
  document.getElementById('feedStatus').innerHTML = "<img src='images/buttons/searching.gif' /> Loading";
}
function feedResponse() {
  if (request.readyState==4) {
    if (request.responseText.indexOf('invalid') == -1) { 	
      var node = request.responseXML.documentElement; 
      var channel = node.getElementsByTagName('channel').item(0);
      var title = channel.getElementsByTagName('title').item(0).firstChild.data;
      var link = channel.getElementsByTagName('link').item(0).firstChild.data;
      document.getElementById('feedStatus').innerHTML = '<div class="channelTitle"><a href="'+link+'">'+title+'</a></div>';
      var content = '<ul>';
      var items = channel.getElementsByTagName('item');
      for (var n=0; n < items.length; n++)
      {
        var itemTitle = items[n].getElementsByTagName('title').item(0).firstChild.data;
        var itemLink = items[n].getElementsByTagName('link').item(0).firstChild.data;
        try { 
          var itemPubDate = '<span>['+ splitDate(items[n].getElementsByTagName('pubDate').item(0).firstChild.data) +']</span>';
        } catch (e) { 
          var itemPubDate = '';
        }
        content += '<li>'+itemPubDate+'<a href="'+itemLink+'">'+itemTitle+'</a></li>';
      }
      content += '</ul>';
      document.getElementById('feedHead').innerHTML = content;
    }
    else {
      document.getElementById('feedStatus').innerHTML = "<span class=error>Error requesting data.</span>";
    }
  }
}
function splitDate(string){
  var dates = string.match(/^(.+),\s(\d+)\s(.+)\s(\d+)\s(\d\d):(\d\d):(\d\d).*/);
  var time;
  var date = RegExp.$3+' '+RegExp.$2+', '+RegExp.$4;
  if (RegExp.$5 > 12)
      time = (RegExp.$5-12) + ':' + RegExp.$6 + ' pm';
  else if (RegExp.$5 == 00)
      time = '12:' + RegExp.$6 + ' am';
  else
     time = parseFloat(RegExp.$5) + ':' + RegExp.$6 + ' am';
  return(time);
}

function createMarker(point, icon, description) {
  var marker = new GMarker(point, icon);
  GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(description);
  });
  return marker;
}
function addEditControls() {
  var items = document.getElementsByClassName('edit'); var hider = null;
  if (!items) return;
  for(i=0; i<items.length; i++){
    //items[i].innerHTML = 'edit delete';
    //items[i].parentNode.onMouseOver = toggle(this);
    //items[i].parentNode.onMouseOut  = toggle(this);
  }
}

/////////////////////////////
// -- Common Javascript -- //
/////////////////////////////

function toggle(obj) {
  obj.style.visibility = (obj.style.visibility == 'visible') ? 'hidden' : 'visible';
}
function retrieveURL(url, action) {
  if(window.XMLHttpRequest) { // Non-IE browsers
     request = new XMLHttpRequest();
     request.onreadystatechange = action;
     try {
       request.open("GET", url, true);
     } catch (e) {
       alert(e);
     }
     request.send(null);
  } else if (window.ActiveXObject) { // IE
    request = new ActiveXObject("Microsoft.XMLHTTP");
    if (request) {
      request.onreadystatechange = action;
      request.open("GET", url, true);
      request.send();
    }
  }
}
function hasValue(object, value) {
  if (!object) return false;
  return (object.search('(^|\\s)' + value + '(\\s|$)') != -1);
}
function hasClass(object, className) {
  if (!object.className) return false;
  return (object.className.search('(^|\\s)' + className + '(\\s|$)') != -1);
}
function removeClass(object,className) {
  if (!object) return;
  object.className = object.className.replace(new RegExp('(^|\\s)'+className+'(\\s|$)'), RegExp.$1+RegExp.$2);
}
function addClass(object,className) {
  if (!object || hasClass(object, className)) return;
  if (object.className) {
      object.className += ' '+className;
  } else {
      object.className = className;
  }
}

/* -- Cookie Functions -- */
function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
		( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

///////////////////////////
// -- Function Loader -- //
///////////////////////////

function startup() {
  if (!isOp){ browserFix(); }
//  addEditControls();
  hideNav = new fx.Height('hideNav', {duration: 400});
  hidePor = new fx.Height('hidePor', {duration: 400});
  hideCal = new fx.Height('calendarMenu', {duration: 400});
  //fadeSize = new fx.Opacity('pageHeader', {duration: 400});
  reloadPreview();
}
window.onload = setTimeout("startup()", 500);


var pop = document.getElementById('popup');

var xoffset = 15;
var yoffset = 10;

document.onmousemove = function(e) {
  var x, y, right, bottom;
  
  try { x = e.pageX; y = e.pageY; } // FF
  catch(e) { x = event.x; y = event.y; } // IE

  right = (document.documentElement.clientWidth || document.body.clientWidth || document.body.scrollWidth);
  bottom = (window.scrollY || document.documentElement.scrollTop || document.body.scrollTop) + (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || document.body.scrollHeight);

  x += xoffset;
  y += yoffset;

  if(x > right-pop.offsetWidth)
    x = right-pop.offsetWidth;
 
  if(y > bottom-pop.offsetHeight)
    y = bottom-pop.offsetHeight;
  
  pop.style.top = y+'px';
  pop.style.left = x+'px';

}

function popup(text) {
  pop.innerHTML = text;
  pop.style.display = 'block';
}

function popout() {
  pop.style.display = 'none';
}
