
/*--------------- START BEHAVIOUR LIB -------------------*/

/*
   Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
   of Simon Willison (see comments by Simon below).

   Description:
   	
   	Uses css selectors to apply javascript behaviours to enable
   	unobtrusive javascript in html documents.
   	
   Usage:   
   
	var myrules = {
		'b.someclass' : function(element){
			element.onclick = function(){
				alert(this.innerHTML);
			}
		},
		'#someid u' : function(element){
			element.onmouseover = function(){
				this.innerHTML = "BLAH!";
			}
		}
	};
	
	Behaviour.register(myrules);
	
	// Call Behaviour.apply() to re-apply the rules (if you
	// update the dom, etc).

   License:
   
   	This file is entirely BSD licensed.
   	
   More information:
   	
   	http://ripcord.co.nz/behaviour/
   
*/   

var Behaviour = {
	list : new Array,
	
	register : function(sheet){
		Behaviour.list.push(sheet);
	},
	
	start : function(){
		Behaviour.addLoadEvent(function(){
			Behaviour.apply();
		});
	},
	
	apply : function(){
		for (h=0;sheet=Behaviour.list[h];h++){
			for (selector in sheet){
				list = document.getElementsBySelector(selector);
				
				if (!list){
					continue;
				}

				for (i=0;element=list[i];i++){
					sheet[selector](element);
				}
			}
		}
	},
	
	addLoadEvent : function(func){
		var oldonload = window.onload;
		
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				oldonload();
				func();
			}
		}
	}
}

Behaviour.start();

/*
   The following code is Copyright (C) Simon Willison 2004.

   document.getElementsBySelector(selector)
   - returns an array of element objects from the current document
     matching the CSS selector. Selectors can contain element names, 
     class names and ids and can be nested. For example:
     
       elements = document.getElementsBySelect('div#main p a.external')
     
     Will return an array of all 'a' elements with 'external' in their 
     class attribute that are contained inside 'p' elements that are 
     contained inside the 'div' element which has id="main"

   New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
   See http://www.w3.org/TR/css3-selectors/#attribute-selectors

   Version 0.4 - Simon Willison, March 25th 2003
   -- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
   -- Opera 7 fails 
*/

function getAllChildren(e) {
  // Returns all children of element. Workaround required for IE5/Windows. Ugh.
  return e.all ? e.all : e.getElementsByTagName('*');
}

document.getElementsBySelector = function(selector) {
  // Attempt to fail gracefully in lesser browsers
  if (!document.getElementsByTagName) {
    return new Array();
  }
  // Split selector in to tokens
  var tokens = selector.split(' ');
  var currentContext = new Array(document);
  for (var i = 0; i < tokens.length; i++) {
    token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
    if (token.indexOf('#') > -1) {
      // Token is an ID selector
      var bits = token.split('#');
      var tagName = bits[0];
      var id = bits[1];
      var element = document.getElementById(id);
      if (tagName && element.nodeName.toLowerCase() != tagName) {
        // tag with that ID not found, return false
        return new Array();
      }
      // Set currentContext to contain just this element
      currentContext = new Array(element);
      continue; // Skip to next token
    }
    if (token.indexOf('.') > -1) {
      // Token contains a class selector
      var bits = token.split('.');
      var tagName = bits[0];
      var className = bits[1];
      if (!tagName) {
        tagName = '*';
      }
      // Get elements matching tag, filter them for class selector
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      continue; // Skip to next token
    }
    // Code to deal with attribute selectors
    if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
      var tagName = RegExp.$1;
      var attrName = RegExp.$2;
      var attrOperator = RegExp.$3;
      var attrValue = RegExp.$4;
      if (!tagName) {
        tagName = '*';
      }
      // Grab all of the tagName elements within current context
      var found = new Array;
      var foundCount = 0;
      for (var h = 0; h < currentContext.length; h++) {
        var elements;
        if (tagName == '*') {
            elements = getAllChildren(currentContext[h]);
        } else {
            elements = currentContext[h].getElementsByTagName(tagName);
        }
        for (var j = 0; j < elements.length; j++) {
          found[foundCount++] = elements[j];
        }
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      var checkFunction; // This function will be used to filter the elements
      switch (attrOperator) {
        case '=': // Equality
          checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
          break;
        case '~': // Match one of space seperated words 
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
          break;
        case '|': // Match start with value followed by optional hyphen
          checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
          break;
        case '^': // Match starts with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
          break;
        case '$': // Match ends with value - fails with "Warning" in Opera 7
          checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
          break;
        case '*': // Match ends with value
          checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
          break;
        default :
          // Just test for existence of attribute
          checkFunction = function(e) { return e.getAttribute(attrName); };
      }
      currentContext = new Array;
      var currentContextIndex = 0;
      for (var k = 0; k < found.length; k++) {
        if (checkFunction(found[k])) {
          currentContext[currentContextIndex++] = found[k];
        }
      }
      // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
      continue; // Skip to next token
    }
    
    if (!currentContext[0]){
    	return;
    }
    
    // If we get here, token is JUST an element (not a class or ID selector)
    tagName = token;
    var found = new Array;
    var foundCount = 0;
    for (var h = 0; h < currentContext.length; h++) {
      var elements = currentContext[h].getElementsByTagName(tagName);
      for (var j = 0; j < elements.length; j++) {
        found[foundCount++] = elements[j];
      }
    }
    currentContext = found;
  }
  return currentContext;
}

/* That revolting regular expression explained 
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
  \---/  \---/\-------------/    \-------/
    |      |         |               |
    |      |         |           The value
    |      |    ~,|,^,$,* or =
    |   Attribute 
   Tag
*/

/*--------------- END BEHAVIOUR LIB -------------------*/

/*--------------- START WEATHER WIDGET LIB ------------*/

var myrules = {
	'#weeklyTag' : function(element){
		element.onmouseover = function(){
			this.style.backgroundColor = "#8291af";
		}
		element.onmouseout = function(){
			if(document.getElementById('weekly').style.display == 'block') {
				this.style.backgroundColor = "#2c3d5e";
			} else {
				this.style.backgroundColor = "#586a8d";
			}
		}
		element.onclick = function(){
			changeTag('weeklyTag','currentTag','mapsTag');
			changePane('weekly','weathermaps','currentConditions');
		}
	},
	'#currentTag' : function(element){
		element.onmouseover = function(){
			this.style.backgroundColor = "#8291af";
		}
		element.onmouseout = function(){
			if(document.getElementById('currentConditions').style.display == 'block' | document.getElementById('currentConditions').style.display == '') {
				this.style.backgroundColor = "#2c3d5e";
			} else {
				this.style.backgroundColor = "#586a8d";
			}
		}
		element.onclick = function(){
			changeTag('currentTag','weeklyTag','mapsTag');
			changePane('currentConditions','weekly','weathermaps');
		}
	},
	'#mapsTag' : function(element){
		element.onmouseover = function(){
			this.style.backgroundColor = "#8291af";
		}
		element.onmouseout = function(){
			if(document.getElementById('weathermaps').style.display == 'block') {
				this.style.backgroundColor = "#2c3d5e";
			} else {
				this.style.backgroundColor = "#586a8d";
			}
		}
		element.onclick = function(){
			changeTag('mapsTag','weeklyTag','currentTag');
			changePane('weathermaps','weekly','currentConditions');
		}
	}	
	
};

Behaviour.register(myrules);

function changeTag(tagID,inactiveTag1,inactiveTag2) {

	document.getElementById(tagID).style.fontWeight = "bold";
	document.getElementById(tagID).style.backgroundColor = "#2c3d5e";
	document.getElementById(inactiveTag1).style.fontWeight = "normal";
	document.getElementById(inactiveTag1).style.backgroundColor = "#586a8d";
	document.getElementById(inactiveTag2).style.fontWeight = "normal";
	document.getElementById(inactiveTag2).style.backgroundColor = "#586a8d";
			
}

inactiveDiv1 = "currentConditions";
inactiveDiv2 = "currentConditions";

function changePane(divID,inactiveDiv1,inactiveDiv2) {
			
			hidePane(inactiveDiv1,inactiveDiv2);
			document.getElementById(divID).style.display = "block";
}

function hidePane(closeDiv1,closeDiv2) {
	
	document.getElementById(closeDiv1).style.display = "none";
	document.getElementById(closeDiv2).style.display = "none";
	
}

function changeLocaton(zipcode) {

	getNewLocation("change_cc.php?zipcode=" + zipcode,zipcode,'currentConditions','weekly','weathermaps');
}

var xmlhttp;
var element_id;
var welement_id;
var zelement_id;
var zip;

function getNewLocation(url,theZip,ccID,weekID,changezipID) {
	
	element_id = ccID;
	welement_id = weekID;
	zelement_id = changezipID;
	zip = theZip;
		
	if (window.XMLHttpRequest) {
  
  		xmlhttp=new XMLHttpRequest();
		xmlhttp.onreadystatechange=weather_state;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
  
  } else if (window.ActiveXObject) {
	  
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    
	if (xmlhttp) {
		
		xmlhttp.onreadystatechange=weather_state;
		xmlhttp.open("GET",url,true);
		xmlhttp.send();
	}
  
  }

}

function weather_state() {
	
	if(xmlhttp.readyState==1) {
		document.getElementById(element_id).innerHTML = "<p class=\"error\">Please Wait. Changing To (" + zip + ").</p>";
	}
	
	if (xmlhttp.readyState==4&&xmlhttp.responseText) {
		
		if (xmlhttp.status==200) {
			
			write_content(element_id,xmlhttp.responseText,zip);
			
			if(element_id == "currentConditions") {
				setTimeout("getNewLocation('change_dayf.php?zipcode=" + zip + "','" + zip + "','weekly','currentConditions','weathermaps')", 50);
			}
			
			if(element_id == "weekly") {
					setTimeout("getNewLocation('weather_maps.php?zipcode=" + zip + "','','weathermaps','','')", 50);
			}
			
			contentLoaded=true;

		}
		
	}
	
}

function write_content(divID,content,zipcode) {

	
	document.getElementById(divID).innerHTML = content;
	
	if(divID == "currentConditions") {
		changePane('currentConditions','weekly','weathermaps');
		changeTag('currentTag','weeklyTag','mapsTag');
		SetCookie('zipcode',zipcode,'30');
	}
}

function SetCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}


/*--------------- END WEATHER WIDGET LIB -------------------*/

function ieformhack(obj) {
		document.getElementById(obj).style.display = "none";
}

function announceAlert(obj,obj2,browser) {
		
		document.getElementById(obj).style.display = browser;
		document.getElementById(obj2).style.display = browser;
		
		if(obj == "otherBox") {
				document.getElementById(obj2).style.backgroundColor = "#fff8bb";
		}
		
}

function searchCheck(obj,obj2) {
		
	if(obj == "1") { document.searchweb.q.value = obj2 + " site:semo.net"; }
	   
}

function toggleBox(obj) {
		
		if(document.getElementById(obj).style.display == "none" | document.getElementById(obj).style.display == "") {
			if(window.XMLHttpRequest) {
				document.getElementById(obj).style.display = "table";
			} else {
				document.getElementById(obj).style.display = "block";
			}
		} else {			
			document.getElementById(obj).style.display = "none";
		}
}

var hide;
var show;

function changeLink() {
		
		show = '<a href="javascript:void(toggleBox(\'calinstruct\'));void(changeLink());">Show Calendar Instructions</a>';
		hide = '<a href="javascript:void(toggleBox(\'calinstruct\'));void(changeLink());">Hide Calendar Instructions</a>';

		if(document.getElementById('calinstruct').style.display == "block") {
			document.getElementById('showinstruct').innerHTML = hide;
		} else {
			document.getElementById('showinstruct').innerHTML = show;
		}
}

function changeContent(content,contentVars,elementID) {
		
	loadXMLDoc(content,contentVars,elementID,"","","","1");
	
}

function changeMonth(month_num,year_num,elementID) {
	
	loadXMLDoc("calendar.php","month=" + encodeURI(month_num) + "&year=" + encodeURI(year_num),elementID,month_num,year_num,"","1");
	
}
function changeDay(month_num,day_num,year_num,elementID) {
	
	loadXMLDoc("changeday.php","month=" + encodeURI(month_num) + "&day=" + encodeURI(day_num) + "&year=" + encodeURI(year_num),elementID);
	
}

function removeEvent(event_id,month_num,day_num,year_num,elementID,calendarID) {
	
	loadXMLDoc("removeevent.php","event_id=" + encodeURI(event_id) + "&month=" + encodeURI(month_num) + "&day=" + encodeURI(day_num) + "&year=" + encodeURI(year_num),elementID,month_num,year_num,calendarID);

}

function sendForm(month_num,year_num,day_num,event_title,event_body,email,elementID,calendarID) {
	
	contentLoaded=false;
	loadXMLDoc("addevent.php","month=" + escape(month_num) + "&day=" + escape(day_num) + "&year=" + escape(year_num) + "&event_title=" + escape(event_title) + "&event_body=" + escape(event_body) + "&email=" + escape(email),elementID,month_num,year_num,calendarID);	
	document.addEventForm.reset();
	
}

function refreshCalendar(month,year,isItTrue,divID) {

	if(isItTrue == true) {
		setTimeout("refreshCalendar('"+month+"','"+year+"','false','"+divID+"');",50);
	} else {
		changeMonth(month,year,divID);
	}

}

var xmlhttp;
var element_id;
var contentLoaded;
var newMonth;
var calID;
var newYear;
var nullStat;

function loadXMLDoc(url,eventVar,theElementID,month,year,divID,stat) {
	
	element_id = theElementID;
	newMonth = month;
	newYear = year;
	calID = divID;
	nullStat = stat;
	
	if (window.XMLHttpRequest) {
  
  		xmlhttp=new XMLHttpRequest();
		xmlhttp.onreadystatechange=state_Change;
		xmlhttp.open("POST",url,true);
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		xmlhttp.send(eventVar);
  
  } else if (window.ActiveXObject) {
	  
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    
	if (xmlhttp) {
		
		xmlhttp.onreadystatechange=state_Change;
		xmlhttp.open("POST",url,true);
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		xmlhttp.send(eventVar);
	}
  
  }

}

function state_Change() {

	if (xmlhttp.readyState==4&&xmlhttp.responseText) {
		
		if (xmlhttp.status==200) {
			
			document.getElementById(element_id).innerHTML = xmlhttp.responseText;
			contentLoaded=true;
			
			if(nullStat == 1) {
				return;
			} else if(contentLoaded == true) {
				changeMonth(newMonth,newYear,calID);			
			}

		}
		
	}
	
}

// Auto Tab function
function autoTab(len,Element,nextElement) {
		if(Element == 3) {
			nextElement.focus();
		}
}

function validateEmail(address) {
	email = address.split("@");
	switch (email[1]) {
		
		case "semo.net":
		break;
		
		case "sheltonbbs.com":
		break;
		
		default:
			alert("Sorry, you must input a valid semo.net or sheltonbbs.com email address.");
	}
}

function checkBoxes(obj) {
	
	checks = obj.split(",");
	for(i=0;i < 4;i++) {
			document.getElementById(checks[i]).checked = false;
			if (checks[i] == "operator") {
				document.getElementById('opermessage').style.display = "none";
			} else if (checks[i] == "busy") {
				document.getElementById('busyoption').style.display = "none";
			}
	}		
}


function logmac(url,eventVar,theElementID) {
	
	element_id = theElementID;

	if (window.XMLHttpRequest) {
  
  		xmlhttp=new XMLHttpRequest();
		xmlhttp.onreadystatechange=mac_changer;
		xmlhttp.open("POST",url,true);
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		xmlhttp.send(eventVar);
  
  } else if (window.ActiveXObject) {
	  
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    
	if (xmlhttp) {
		
		xmlhttp.onreadystatechange=mac_changer;
		xmlhttp.open("POST",url,true);
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
		xmlhttp.send(eventVar);
	}
  
  }

}

function mac_changer() {

	if (xmlhttp.readyState==4&&xmlhttp.responseText) {
		
		if (xmlhttp.status==200) {
			
			if(xmlhttp.responseText === "false") {
				document.getElementById('invalid').innerHTML = '<span style="color: #f00; margin: 0 0 0 20px; padding: 0;">*** Sorry, but you entered an invalid e-mail address.</span>';
			} else {
				document.getElementById(element_id).innerHTML = xmlhttp.responseText;
				setTimeout("document.getElementById('dslverify').style.display = 'none';", 2000);
			}


		}
		
	}
	
}

function newschanger(url,theElementID) {
	
	element_id = theElementID;
	
	if (window.XMLHttpRequest) {
  
  		xmlhttp=new XMLHttpRequest();
		xmlhttp.onreadystatechange=state_Change;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
  
  } else if (window.ActiveXObject) {
	  
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    
	if (xmlhttp) {
		
		xmlhttp.onreadystatechange=state_Change;
		xmlhttp.open("GET",url,true);
		xmlhttp.send();
	}
  
  }

}

function change_news() {
	if (xmlhttp.readyState==4&&xmlhttp.responseText) {
		if (xmlhttp.status==200) {
			document.getElementById(element_id).innerHTML = xmlhttp.responseText;
		}
	}
}

function showMap(obj) {
	if(document.getElementById(obj).style.display == "none" | document.getElementById(obj).style.display == "") {
			document.getElementById(obj).style.display = "block";
	} else {			
		document.getElementById(obj).style.display = "none";
	}
}

function element(obj) {
	return document.getElementById(obj);
}

function toggleBox2(elementID) {
	if(document.getElementById(elementID).style.display == "" || document.getElementById(elementID).style.display == "none") {
		document.getElementById(elementID).style.display = "block";
	} else {
		document.getElementById(elementID).style.display = "none";
	}
}

function searchEngine(engine) {
	document.searchBox.engine.value = engine;
	if(engine == "ask.com") {
		engine = "ask";
	}
	document.getElementById('engine-selection').innerHTML = '<img src=\"images/searchicons/' + engine + 'icon.png\" width=\"20\" height=\"18\" border=\"0\" />';
	document.getElementById('search-engines').style.display = 'none';
}

function hideSearch() {
	if (document.getElementById('search-engines').style.display == "block"){
		s = setTimeout('toggleBox2(\'search-engines\')', 200);
	}
}



/*----------------------- AJAX ----------------------------*/
var element_id;
var xmlhttp;
var eVars;

function getContent(url,elementID) {
	element_id = elementID;

	if (window.XMLHttpRequest) {
		xmlhttp=new XMLHttpRequest();
		xmlhttp.onreadystatechange=state_Changer;
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
		} else if (window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		
		if (xmlhttp) {	
			xmlhttp.onreadystatechange=state_Changer;
			xmlhttp.open("GET",url,true);
			xmlhttp.send();
		}
	}
}

function postContent(url,elementID,elementVars) {
	element_id = elementID;
	eVars = encodeURI(elementVars);

	if (window.XMLHttpRequest) {
		xmlhttp=new XMLHttpRequest();
		xmlhttp.onreadystatechange=state_Changer;
		xmlhttp.open("POST",url,true);
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');		
		xmlhttp.send(eVars);
	} else if (window.ActiveXObject) {
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

		if (xmlhttp) {	
			xmlhttp.onreadystatechange=state_Changer;
			xmlhttp.open("POST",url,true);
			xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');		
			xmlhttp.send(eVars);
		}
	}
}

function state_Changer() {
	if (xmlhttp.readyState==4&&xmlhttp.responseText) {
		if (xmlhttp.status==200) {
			if(xmlhttp.responseText == "false") {
				document.getElementById('auth').innerHTML = "** Invalid username/password.";
			} else {
				document.getElementById(element_id).innerHTML = xmlhttp.responseText;
			}
		}	
	}
}


/*---------------------- Google Maps API -----------------------------*/

function loadMap() {
	
	var address_cloud = '<div id="address"><p><span>Semo.net</span><br />(Poplar Bluff Internet, Inc)<br />1877 N Westwood Blvd<br />Poplar Bluff, MO 63901</p><p>573.686.9114<br />877.686.9114</p></div>';
	
	if (GBrowserIsCompatible()) {
	  var map = new GMap2(document.getElementById("map"));
	  map.addControl(new GSmallMapControl());
	  map.setCenter(new GLatLng(36.77403, -90.42027), 15);
	  var marker = new GMarker(new GLatLng(36.77403, -90.42027));
	  map.addOverlay(marker);
	  GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(address_cloud);
	  });
	  marker.openInfoWindowHtml(address_cloud);
	}
}
