String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

function Ajax() {
  this.req = null;
  this.url = null;
  this.method = 'GET';
  this.async = true;
  this.status = null;
  this.statusText = '';
  this.postData = null;
  this.readyState = null;
  this.responseText = null;
  this.responseXML = null;
  this.handleResp = null;
  this.responseFormat = 'text', // 'text', 'xml' or object
  this.innerID = null;
  this.logout = null;
  this.tries=0;
  this.maxtries=2;
}

Ajax.prototype.init = function() {
    if (!this.req) {
       try {
         //Try to create object for firefox / safari etc
         this.req = new XMLHttpRequest();
        }
        catch (e) {
         try {
           //try to create object for later versions of IE
           this.req = new ActiveXObject("MSXML2.XMLHTTP");
         }
         catch(e) {
            try {
             //try to create object for earlier versions of IE
             this.req = new ActiveObject('Microsoft.XMLHTTP');
          } catch (e) {
            //could not create the object so return false
            return false;
         }
       }
    }
  }
  return this.req;
}

Ajax.prototype.doReq = function() {
  if (!this.init()) {
    alert("Could not create XMLHttp Object");
    return;
  }
 this.req.open(this.method, this.url, this.async);
  if (this.method == "POST") {
    this.req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    this.req.setRequestHeader("Content-length", this.postData.length);
    this.req.setRequestHeader("Connection", "close");
  }
  var self = this;
  this.req.onreadystatechange = function() {
    if (self.req.readyState == 4) {
        switch(self.responseFormat) {
            case 'text':
                resp = self.req.responseText;
                break;
            case 'xml':
                resp = self.req.responseXML;
                break;
            case 'object':
                resp = req;
                break;
       }
        if (self.req.status >= 200 && self.req.status <= 299) {
            //find out what status resp is
            if (self.logout) {
               if (self.responseFormat=="xml") {
				var tgs = resp.getElementsByTagName("_logout_");
				 if (tgs.length > 1) {
					tgs=null;
					href.location = self.logout;
				 } 
			   } else if (resp.indexOf("_logout_=true ") > -1) {
				href.location=self.logout;
			   } 
			} 
			if (self.innerID) document.getElementById(self.innerID) = resp;
			if (typeof self.handleResp == 'function') self.handleResp(resp);
        } else {
            self.handleErr(resp);
        }
    }
  };
  try {
    this.req.send(this.postData);
    } catch (e) {
      alert("there is an error with the req send");
    }
}


Ajax.prototype.handleErr = function(str) {
  if (this.tries < this.maxtries) {
	this.tries++;
	this.doReq();
 } else {
    alert ('An error has occured, Status code: ' + this.req.status + '\n Status description: ' + this.req.statusText + ' URL: ' + this.url);
  }
}

Ajax.prototype.abort = function() {
  if (this.req) {
    this.req.onreadystatechange = function () {};
    this.req.abort();
    this.req = null;
  }
}

Ajax.prototype.doGet = function(url, hand, format, innerID, logout) {
  this.url = url;
  this.handleResp = hand;
  this.innerID = innerID;
  this.logout=logout;
  this.responseFormat = format || 'text';
  this.doReq();
}

var _stRead = {
	'clicks' : [],
	'start' : new Date(),
	'load' : new Date(),
	'setXY' : function(e) {
		if (!e) var e = window.event;
		_stRead.clicks[_stRead.clicks.length] = {'x' : e.clientX, 'y' : e.clientY, 'srcId' : 0};
	},
	'endPage' : function() {
		var clstr='', endtime, sttime;
		for (var i=0; i<_stRead.clicks.length; i++) {
		clstr += "&link_" + i + "_x=" + _stRead.clicks[i].x;
		clstr += "&link_" + i + "_y=" + _stRead.clicks[i].y;
		clstr += "&link_" + i + "_srcid=" + encodeURI(_stRead.clicks[i].srcId);
	    }
	    endtime = new Date().getTime() - _stRead.start.getTime();
	    sttime = _stRead.load.getTime() - _stRead.start.getTime();
	 var wid, he;
    if (typeof window.innerWidth != 'undefined') {
      wid = window.innerWidth,
      he = window.innerHeight
    } else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) {
       wid = document.documentElement.clientWidth,
       he = document.documentElement.clientHeight
    } else {
       wid = document.getElementsByTagName('body')[0].clientWidth,
       he = document.getElementsByTagName('body')[0].clientHeight
    }
	 clstr = (clstr == "") ?  "starttime=" + sttime + "&endtime=" + endtime + "&wid=" + wid + "&he=" + he : "starttime=" + sttime + "&endtime=" + endtime + "&wid=" + wid + "&he=" + he  + clstr;
	 var ajax = new Ajax();
	 ajax.doGet("/function/setstats.php?" + clstr);
	 ajax=null;
    endtime=clstr=wid=he=sttime=ajax=null;
	}
}

var _bas = {
'_handles' : {'onclick' : {}, 'onfocus' : {}, 'onblur' : {}, 'onmouseover' : {}, 'onmouseout' : {}, 'onchange' : {},
  'setHandle' : function(unset) {
    var el;
	for (var i in _bas._handles) {
	  for (var x in _bas._handles[i]) {
	    el = document.getElementById(x);
	    if (el!=null) {
	      if (unset) el[i] = null;
	      else {
		    el[i] = _bas._handles[i][x].func;
		    if (i=="onclick") el.style.cursor="pointer";
		  }
	    }
	  }
	}
    el=null;
  }
 },
'clickRemove' : {},
'_forms' : {},
'_mouseover' : {},
'_ops' : {},
'_imgs' : [],
'_syncs' : {},
'_openFunc' : function() {
    window.open(_bs._ops[this.id].pageName, "view_photo", "toolbar=no,location=no,directories=no,status=yes,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=" + _bs._ops[this.id].width + ",height=" + _bs._ops[this.id].height + ",top=100,left=50");
    return false;
},
'drop' : {
  'drops' : {},
  'openMens' : {},
  'curLevel' : 0,
  'shDiv' : function(id, typ) {
    var el = document.getElementById(id);
    if (el==null) return false;
    el.style.display = (typ) ? "block" : "none";
    el.style.visibility = (typ) ? "visible" : "hidden";
    el=null;
  },
  'startDrop' : function(id) {
    //if curmenu is not false then clear it out
    if (isNaN(parseInt(_bas.drop.drops[id].level))) _bas.drop.drops[id].level = 0;
    _bas.drop.curLevel = _bas.drop.drops[id].level;
    if (!_bas.drop.drops[id].status) {
      _bas.drop.checkTime();
      _bas.drop.openMens[id] = true;
      _bas.drop.shDiv(_bas.drop.drops[id]._dropMenu, true);
    } 
	_bas.drop.drops[id].status=1;
    //finally start timer
  },

  'unSet' : function(el) {
	var id = el.id.replace(/_dropdown/g, "");
	_bas.drop.drops[id].status=2;
	_bas.drop.drops[id].offsetTime = new Date();
	setTimeout("_bas.drop.checkTime();",200);
  },
  'checkTime' : function() {
    var recheck=false;
    var delArr=new Array();
    for (var i in _bas.drop.openMens) {
      if (_bas.drop.drops[i].status==2 && _bas.drop.drops[i].level >= _bas.drop.curLevel) {
      //this means to check whether we should be hiding this
    	var del = _bas.drop.drops[i]._delay;
    	var now = new Date();
    	var difference = now.getTime() - _bas.drop.drops[i].offsetTime.getTime();
    	if (difference > del) {
		  _bas.drop.shDiv(_bas.drop.drops[i]._dropMenu, false);
		  _bas.drop.drops[i].status=null;
		  delArr[delArr.length] = i;
    	} else recheck=true;
      } 
    }

    for (var i =0; i<delArr.length; i++) {
		delete _bas.drop.openMens[delArr[i]];
	}

    if (recheck) setTimeout("_bas.drop.checkTime()", 100);
    delArr=null;
   }
 },
 'mouseO' : function(){
    if (_bas._mouseover[this.id]) this.src = _bas._mouseover[this.id].mOver;
    var id = this.id.replace(/_dropdown/g, "");
    if (_bas.drop.drops[id]) _bas.drop.startDrop(id);
  },
  'mouseOt' : function() {
    if (_bas._mouseover[this.id]) this.src = _bas._mouseover[this.id].mOut;
    var id = this.id.replace(/_dropdown/g, "");
	if (_bas.drop.drops[id]) _bas.drop.unSet(this);
  },
  //this is very useful is we are ever dealing with any xml
  '_clickBlur' : function() {
	if (this.value=="") this.value =_bas._clickRemove[this.id];
  },

  '_clickFocus' : function() {
	if (this.value==_bas._clickRemove[this.id]) this.value = "";
   },
   
   '_hideErr' : function(fmName) {
     var el;
	 for (var i in _bas._forms[fmName].fields) {
		if (!_bas._forms[fmName].fields[i].okay) {
			//insert the cross next to the error message
			document[fmName][i].style.cssText = '';
			_bas._forms[fmName].fields[i].okay=true;
			el = document.getElementById(document[fmName][i].id + "_error");
			if (el != null) el.style.cssText="visibility:hidden;display:none;";
		}
	 }
	el=null; 
   },
   '_showErr' : function(fm, fmName) {
     var el;
	  for (var i in _bas._forms[fmName].fields) {
		if (!_bas._forms[fmName].fields[i].okay) {
			//insert the cross next to the error message
			_bas._forms[fmName].fields[i].border = fm[i].style.border;
			fm[i].style.border="2px solid red";
			el = document.getElementById(fm[i].id + "_error");
			if (el != null) el.style.cssText = "visibility:visible;display:block;width:14px;height:14px;";
		}
	  }
	  el=null; 
    }, 
    '_chkForm' : function(fmName) {
       _bas._hideErr(fmName);
  		var ob, ck;
  		var fm = document[fmName]; 
  		var okay=true;
   		for (var i in _bas._forms[fmName].fields) {
	  		ob=_bas._forms[fmName].fields[i];
	  		ob.okay=true;
	  		if (ob.type=="checkbox" && !fm[i].checked) okay=ob.okay=false;
	  		else if (ob.type=="radio") {
	   		ck=false;
			for (var x=0; x<fm[i].length; x++) {
				if (fm[i].checked) {
					ck=true;
					break;
				}
			}
				if (!ck) ob.okay=okay=false;
	 		} else if (fm[i].value.trim() == ob.def) ob.okay=okay=false;
  		 }
  		if (!okay) {
		    _bas._showErr(fm, fmName);
		    alert("You have not entered all the required information, please check the form and try again");
  		} else if (_bas._syncs[fm.id]) {
  		  var data = "";
			//make an ajax object of the data
			var tg = ["input", "textarea", "select"];
			for (var i=0; i<tg.length; i++) {
			 var tgs = fm.getElementsByTagName(tg[i]);
			  for (var x=0; x<tgs.length; x++) { 
			   if (data != "") data += "&";
			   data += tgs[x].name + "=" + urlencode(escape(tgs[x].value));
			  }
			}
		  makeAjax(fm.id, "text", data);
		  tg=tgs=data=null;
		  return false;
		}
 		return okay;
   },
  '_cal' : {
	'date' : null,
	'day' : ((1000 * 60) * 60) * 24,
	'curmonth' : null,
	'month' : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	'setDateId' : null,
	'origFunc' : false,
	'runCal' : function(e) {
		//get offset left and top
	  stopBub(e);
	  _bas._cal.close();
	  _bas._cal.setDateId = this.id;
	  _bas._cal.date = new Date();
	  var curleft=curtop=0;
	  var obj=this;
	  curleft = this.offsetWidth;
	   if (obj.offsetParent) {
		 do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		 } while (obj = obj.offsetParent);
	   }
      var dv = document.createElement("div");
      dv.style.position="absolute";
      curleft += 15;
      curtop += 15;
      dv.style.top=curtop + "px";
      dv.style.left=curleft + "px";
      dv.setAttribute("id", "calendar");
      dv.onclick=stopBub;
      dv.style.backgroundColor="#ffffff";
      dv.style.border="1px solid #000000";
      dv.style.zIndex="400";
      document.body.appendChild(dv);
      _bas._cal.setCal();
      _bas._cal.origFunc = document.body.onclick;
      dv=null;
	},
	'setCal' : function() {
	  var el = document.getElementById("calendar");
	  if (el==null) return false;
	    var mon, htm, st, day, dt;
	    this.curmonth = this.date.getMonth()
	    mon = this.month[this.curmonth];
	    htm = "<table style='font-size:12px;font-family:Arial;'><tr><td colspan='7' style='text-align:right;cursor:pointer;' onclick='_bas._cal.close();'>close</td></tr>";
		htm += "<tr><td colspan='7' style='text-align:center;'><span id='back' style='cursor:pointer;position:absolute;left:0px;'>&lt;&lt;</span><span>" + mon + " - " + _bas._cal.date.getFullYear() + "</span><span id='next' style='cursor:pointer;position:absolute;right:0px;'>&gt;&gt;</span></td></tr>";
		htm += "<tr><td id='sun'>Sun</td><td id='mon'>Mon</td><td id='tue'>Tue</td><td id='wed'>Wed</td><td id='thu'>Thu</td><td id='fri'>Fri</td><td id='sat'>Sat</td></tr>";
		var dto = new Date();
		dto.setDate(1);
		dto.setFullYear(this.date.getFullYear());
		dto.setMonth(this.date.getMonth());
		day = dto.getDay();
		st=0;
		while (dto.getMonth() == this.curmonth) {
		  for (var i=0; i<7; i++) {
		    if (i==0) htm += "<tr>";
		    if (i==day && st==0) st=1;
		    if (st==1) {
		     dt = dto.getDate();
		     htm += "<td id='date/" + dt + "' style='text-align:center;cursor:pointer;'>" + dt + "</td>";
		      dto.setTime(dto.getTime() + this.day);
			} else {
			 htm += "<td>&nbsp;</td>";
			}
		    if (i==6) htm += "<tr>";
		    if (dto.getMonth() != this.curmonth) st=2;
		  }
		}	 
	   el.innerHTML = htm;
	   var tgs =el.getElementsByTagName("td");
       for (var i=0; i<tgs.length; i++) {
		if (tgs[i].id!=null && tgs[i].id!="") {
		   if (i==0) alert(tgs[i].id);
		    tgs[i].onclick=_bas._cal.postDate;
		}
	  } 
	  document.getElementById("back").onclick=_bas._cal.prevMonth;
	  document.getElementById("next").onclick=_bas._cal.nextMonth;
	  mon=htm=st=day=dt=dto=tgs=el=null;
	},	
	'setDate' : function(time) {
		this.date.setTime(time);
	},
   'postDate' : function(e) {
       stopBub(e);
		var day = this.id.split("/");
		var mon = _bas._cal.date.getMonth() + 1;
		if (mon < 10) mon = "0" + mon;
		if (day[1] < 10) day[1] = "0" + day[1];
		document.getElementById(_bas._cal.setDateId).value = day[1] + "/" + mon + "/" + _bas._cal.date.getFullYear();
		day=mon=null;
	},	
	'nextMonth' : function() {
		var mon = _bas._cal.date.getMonth() + 1;
		if (mon>=12) {
			_bas._cal.date.setFullYear(_bas._cal.date.getFullYear() + 1);
			_bas._cal.date.setMonth(0);
		} else {
		    _bas._cal.date.setMonth(mon);
	    }
	  _bas._cal.setCal();
	},	
	'prevMonth' : function() {
		var mon = _bas._cal.date.getMonth() - 1;
		if (mon==-1) {
		   _bas._cal.date.setFullYear(_bas._cal.date.getFullYear() - 1);
		   _bas._cal.date.setMonth(11);
		} else {
		    _bas._cal.date.setMonth(mon);
	    }
	  _bas._cal.setCal();
	},
	'close' : function() {
	   var el = document.getElementById("calendar");
	   if (el!=null) document.body.removeChild(el);
	   el=null;
	   if (_bas._cal.origFunc != false) {
	       document.body.onclick=_bas._cal.origFunc;
	   	   _bas._cal.origFunc=null;
	   }
	} 
  }
}

function makeAjax(id, format, data) {
	var ajax = new Ajax();
	//check which files we are using now
	var inner = (_bas._syncs[id].inner == "") ? null : _bas._syncs[id].inner;
	var logout = (_bas._syncs[id].logout == "") ? null : _bas._syncs[id].logout;
	var file = _bas._syncs[id].action;
	var method= _bas._syncs[id].method;
	var func = _bas._syncs[id].func;
	var format = format;
	if (!format || format == '') format = "GET";
	if (data && data != '') {
		 if (method=="GET") file += "?" + data;
		 else {
			ajax.postData = data;
			ajax.method="POST";
		}
	}
	ajax.async=false;
	ajax.doGet(file, func, format, inner, logout);
	if (!isNaN(parseInt(_bas._syncs[id].time))) window.setTimeout("makeAjax('" + id + "', '" + format + "', '" + data + "');");
	inner=logout=file=method=func=format=data=ajax=null;
}

function checkVal(res) {
  if (res.textContent) return res.textContent;
  else if (res.text) return res.text;
  else if (res.nodeValue) return res.nodeValue
  else if (res.firstChild) return res.firstChild.nodeValue;
  else return "";
}

function stopBub(e) {
  if (!e) var e = window.event;
   e.cancelBubble=true;
  if (e.stopPropagation) e.stopPropagation();
  return e;
}

document.onclick = _stRead.setXY;
window.onbeforeunload = function() {
     _stRead.endPage();
     _bas._handles.setHandle(true);
}