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) {
	  var dv=document.createElement("div");
	  dv.innerHTML = resp;
	 var el=document.getElementById(self.innerID);
	 if (el!=null) {
	   if (dv.firstChild.nodeType==1 && dv.firstChild.tagName.toLowerCase() == "html") dv=dv.firstChild;
	   for (var i=0; i<dv.childNodes.length; i++) {
		if (dv.childNodes[i].nodeType==1 && dv.childNodes[i].tagName.toLowerCase() != "script") {
		  el.appendChild(dv.childNodes[i].cloneNode(true));
		}
	   }
	   //now try to set the javascript
	   for (var i=0; i<dv.childNodes.length; i++) {
		if (dv.childNodes[i].nodeType==1 && dv.childNodes[i].tagName.toLowerCase() == "script") {
		  eval(dv.childNodes[i].text);
		}
	   }
	  }
	  dv=el=null;
	}
	 if (typeof self.handleResp === 'function') self.handleResp(resp);
	 else if (self.handleResp==="alert") alert(resp);
    } else {
            self.handleErr(resp);
        }
    }
  };
  try {
    this.req.send(this.postData);
    } catch (e) {
    }
    resp=null;
}

Ajax.prototype.clearUp = function() {
	
}

Ajax.prototype.handleErr = function(str) {
  if (this.tries < this.maxtries) {
	this.tries++;
	this.abort();
	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.async=false;
	 ajax.doGet("/function/setstats.php?" + clstr);
	 ajax=null;
    endtime=clstr=wid=he=sttime=ajax=null;
	}
}

var _bas = {
  'setHandle' : function(unset, type) {
    if (_obs==null) return false;
    var el;
	for (var i in _obs) {
	  if (type=="inner" && _obs[i].type!="inner") continue;
	   if (_obs[i].handles) {
	     if (_obs[i].loop=="1") {
			var y=0;
			var ct=true;
			while(ct) {
				el=document.getElementById(i +  y);
				if (!el) {
					ct=false;
					break;
				}
				for (var x=0; x<_obs[i].handles.length; x++) {
				if (unset) el["on" + _obs[i].handles[x].type] = null;
		    	else {
			  	  el["on" + _obs[i].handles[x].type] = _obs[i].handles[x].func;
			  	  if (_obs[i].handles[x].type=="click") el.style.cursor="pointer";
			 	}
			 	}
			   el=null;
				y++;
			}
		 } else {
		  el=document.getElementById(i);
		  for (var x=0; x<_obs[i].handles.length; x++) {
		   try {
		    if (unset) el["on" + _obs[i].handles[x].type] = null;
		    else {
			  el["on" + _obs[i].handles[x].type] = _obs[i].handles[x].func;
			  if (_obs[i].handles[x].type=="click") el.style.cursor="pointer";
			}
		   } catch(e) {}	
		  }
		  el=null;
	     }
	    }
	 }	  
 },
'_openFunc' : function() {
    window.open(_obs[this.id].win.pageName, "view_photo", "toolbar=no,location=no,directories=no,status=yes,menubar=no,resizable=yes,copyhistory=no,scrollbars=yes,width=" + _obs[this.id].win.width + ",height=" + _obs[this.id].win.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;
  },
  'scrollOut' : function(id,x, y) {
    ob=_bas.drop.cob;
    if (x > parseInt(_obs[id].width)) x=parseInt(_obs[id].width);
    if (y > parseInt(_obs[id].height)) y = parseInt(_obs[id].height);
	ob.style.overflow="hidden";
	ob.style.width = x + "px";
	ob.style.minHeight= y + "px";
	x+=10;
	y+=10;
	if (x < parseInt(_obs[id].width) || y < parseInt(_obs[id].height)) {
		window.setTimeout("_bas.drop.scrollOut('" + id + "', " + x + ", " + y + ");", 10);
	}
  },
  'startDrop' : function(id) {
    //if curmenu is not false then clear it out
    _bas.drop.curLevel = (isNaN(parseInt(_obs[id].drop.level)))? 0:  _obs[id].drop.level;
    if (!_obs[id].drop.status) {
      _bas.drop.checkTime();
      _bas.drop.openMens[id] = true;
      _bas.drop.shDiv(_obs[id].drop._dropMenu, true);
      if (_obs[id].drop.align) {
           //get the offset of the parent and then the child node
           var el=document.getElementById(id);
           var dropel=document.getElementById(_obs[id].drop._dropMenu);
           var lef,top,plef,ptop,pel;
           lef=top=plef=ptop=0;
           do {
              lef += el.offsetLeft;
              top += el.offsetTop
           } while (el=el.offsetParent);
              pel=dropel.parentNode;
              do {
                 plef += pel.offsetLeft;
                 ptop += pel.offsetTop
              } while (pel=pel.offsetParent);
              plef = lef - plef;
              ptop = top - ptop;
              dropel.style.left = (plef + _obs[id].drop.align[0]) + "px";
              dropel.style.top = (ptop + _obs[id].drop.align[1]) + "px";
              plef=ptop=dropel=lef=top=pel=el=null;
    }
      _bas.drop.cob=document.getElementById(_obs[id].drop._dropMenu);
      if (_obs[id].type == "scrollin") _bas.drop.scrollOut(id, 0, 0);
      
    } 
	_obs[id].drop.status=1;
    //finally start timer
  },

  'unSet' : function(el) {
	var id = el.id.replace(/_dropdown/g, "");
	_obs[id].drop.status=2;
	_obs[id].drop.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 (_obs[i].drop.status==2 && _obs[i].drop.level >= _bas.drop.curLevel) {
      //this means to check whether we should be hiding this
    	var del = _obs[i].drop._delay;
    	var now = new Date();
    	var difference = now.getTime() - _obs[i].drop.offsetTime.getTime();
    	if (difference > del) {
		  _bas.drop.shDiv(_obs[i].drop._dropMenu, false);
		  _obs[i].drop.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 (_obs[this.id].mouseO) this.src = _obs[this.id].mouseO;
    var id = this.id.replace(/_dropdown/g, "");
    if (_obs[id].drop) _bas.drop.startDrop(id);
    id=null;
  },
  'mouseOt' : function() {
    if (_obs[this.id].mouseO) this.src = _obs[this.id].src;
    var id = this.id.replace(/_dropdown/g, "");
	if (_obs[id].drop) _bas.drop.unSet(this);
	id=null;
  },
  //this is very useful is we are ever dealing with any xml
  '_clickBlur' : function() {
	if (this.value=="") this.value =_obs[this.id].clickRemove;
  },

  '_clickFocus' : function() {
	if (this.value==_obs[this.id].clickRemove) this.value = "";
   },
   
   '_hideErr' : function(fm, fmName) {
     var el;
	 for (var i in _obs[fmName].fields) {
		if (!_obs[fmName].fields[i].okay) {
		 if (_obs[fmName].fields[i].type=="radio") {
			
		  } else {
			document[fmName][i].style.border=_obs[fmName].fields[i].border;
			_obs[fmName].fields[i].okay=true;
		  }	
		}
	 } 
   },
   '_showErr' : function(fm, fmName) {
     var el;
	  for (var i in _obs[fmName].fields) {
		if (!_obs[fmName].fields[i].okay) {
			if (_obs[fmName].fields[i].type=="radio") {
			
		  } else {
		    _obs[fmName].fields[i].border = fm[i].style.border;
			fm[i].style.border="2px solid red";
		  }	
		}
	  }
	  el=null; 
    }, 
    '_chkForm' : function(fmName, del) {
       if (del==="1") {
		var ok=confirm("Are you sure you want to delete this?\nClicking ok will permanently delete this from the database. If you do not want to delete this, click cancel");
		return ok;
	  } else {
  		var ob, ck;
  		var fm = document[fmName];
		_bas._hideErr(fm, fmName); 
  		var okay=true;
  		for (var i in _obs[fmName].fields) {
	  		ob=_obs[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 (_obs[fmName].ajax[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 + "=" + 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!="") {
		    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;
		_bas._cal.close();
	},	
	'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 = (_obs[id].ajax.inner == "") ? null : _obs[id].ajax.inner;
	var logout = (_obs[id].ajax.logout == "") ? null : _obs[id].ajax.logout;
	var file = _obs[id].ajax.action;
	var method= _obs[id].ajax.method;
	var func = _obs[id].ajax.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.doGet(file, func, format, inner, logout);
	if (!isNaN(parseInt(_obs[id].ajax.time))) window.setTimeout("makeAjax('" + id + "', '" + format + "', '" + data + "');");
	inner=logout=file=method=func=format=data=ajax=null;
}

function popOver(ob, col) {
  if (document.getElementById("popover") != null) closePopOver();
	var dv = document.createElement("div");
	dv.style.zIndex=6000;
	dv.setAttribute("id", "popover");
	dv.style.width="100%";
	dv.style.height="100%";
	dv.style.position="fixed";
	dv.style.margin="0px";
	dv.style.padding="0px";
	dv.style.top="0px";
	dv.style.left="0px";
	dv.style.backgroundImage="url(/img/grey_popup_fade.png)";
	dv.style.backgroundRepeat="repeat";
	var href= (ob.href.indexOf("?") > -1) ? ob.href + "&popover=true" : ob.href + "?popover=true";
	var htm = "<iframe id='popovercontent' src='" + href + "' FRAMEBORDER=0 style='position:absolute;margin:0px;padding:0px;top:10px;left:0px;border:0px;visibility:hidden;'></iframe></div>";
	dv.innerHTML = htm;
	document.body.appendChild(dv);
	dv=null;
	return false;
}

function resizePop(wid, he) {
 var sWid,sHe;
  if( typeof( window.innerWidth ) === 'number' ) {
    sWid = window.innerWidth;
    sHe = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    sWid  = document.documentElement.clientWidth;
    sHe = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    sWid  = document.body.clientWidth;
    sHe = document.body.clientHeight;
  }
  var ob=document.getElementById("popovercontent");
  if (!ob) return false;
  ob.style.left=((sWid / 2) - (wid / 2)) + "px";
  ob.style.top=((sHe / 2) - (he / 2)) + "px";
  ob.style.width=(wid + 20) + "px";
  ob.style.height=(he + 20) + "px";
  ob.style.visibility="visible";
  sHe=sWid=left=top=pwid=phe=sp=hsp=ob=null;
}

function closePopOver() {
  document.body.removeChild(document.getElementById("popover"));
}

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.setHandle(true);
}
