var isIE = (document.all ? true : false); // Is IE browser?

var searchBar = null;

window.onresize = function() 
{
	if( isIE )
	{
		window.status = "IE";
		var popup = document.getElementById( 'popup');
		var body = document.body;
		if(popup && body)
		{
			popup.style.width = ( body.scrollWidth > body.offsetWidth ? body.scrollWidth : body.offsetWidth + "px");
			popup.style.height = ( body.scrollHeight > body.offsetHeight ? body.scrollHeight : body.offsetHeight + "px");
			
			var form = document.getElementById("newengine");
			// Create one, if not found.
			if(!form) return(false);

			if(form.style.display == 'block')
				form.style.left = body.offsetLeft + (( body.offsetWidth - form.offsetWidth )/2);
		}
	}
}

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return { x:scrOfX, y:scrOfY };
}

function getIEVersionNumber() {
    var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE ");
    
    if (MSIEOffset == -1) {
        return 0;
    } else {
        return parseFloat(ua.substring(MSIEOffset + 5, ua.indexOf(";", MSIEOffset)));
    }
}

function mouseFromWindow(evt) 
{
	var scroll = getScrollXY();
	var mX = isIE ? (window.event.clientX + document.body.scrollLeft + scroll.x) : evt.pageX;
	var mY = isIE ? (window.event.clientY + document.body.scrollTop + scroll.y) : evt.pageY;
	return { x:mX, y:mY };
}

function isUrl(s) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	return regexp.test(s);
}

function isEmail(s) {
	var regexp = /^[_+a-z0-9-]+(\.[_+a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{1,})*\.([a-z]{2,}){1}$/
	return regexp.test(s);
}

function isAlphaNum(s) {
	var regexp = /^([0-9a-z])+$/
	return regexp.test(s);
}

function isNull(val) {
	if(!val)
		return 0;
	else
		return val;
}

function initXMLHTTPRequest()
{
	var xRequest=null;
	if(window.XMLHttpRequest) {
		xRequest=new XMLHttpRequest();
	}
	else if(window.ActiveXObject) {
		xRequest=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xRequest;
}

function onReadyState()
{
	var ready=search.req.readyState;
	if(ready==4) {
		var data=search.req.responseText;
		var urls=data.split('||');
		var cols;
		var output = [];
		for (var index=0;index<urls.length ;index++ )
		{
			var splits = urls[index].split('|');
			if(splits[0]!="") output.push({caption : splits[0], url : splits[1], left : splits[2], top : splits[3], img : splits[4]});
		}
		search.engines = output;
		for(var x in search.engines) {
			var itm = search.engines[x];
			search.display(itm.caption, itm.url, itm.left, itm.top, itm.img);
		}
	}
}


function search() {
	//System Variables
	this.source = null;
	this.clipBoard;
	this.OnFocus = '';
	this.holders = [];
	this.selects = new Array("editurl", "delurl");
	this.mX;
	this.mY;
	this.element;
	this.layover;
	this.form;
	this.bkImg;
	this.req;
	//Function declarations
	this.go = init;
	this.display = showOutput;
	this._get = getData;
	this._set = updateData;
	this.click = gotoUrl;
	this.mouseup = mouseUp;
	this.mousedown = mouseDown;
	this.mousemove = mouseMove;
	this.toElem = HTMLtoElement;
	this.updateHolder = updateFocusHolder;
	this.createClip = createClipboard;
	this.panel = showPanel;
	this.close = closePanel;
	this.setImage = setBgImage;
	this.load = loadElementData;
	///////////////////////////
	this.popup = 0;
	this.drag = true;
	this.OnFocus=null;
	this.iconsDir = "images/"
	
	this.menu = 0;
	this.New = 1;
	this.Edit = 2;
	this.Delete = 3;
	this.Join = 4;
	this.Login = 5;
	
	this.engines = new Array;

	function init()
	{
		this.OnFocus=document.getElementById('holderfocus');

		var elements=document.getElementsByTagName('*');

		for (var index=0;index<elements.length ;index++ )
		{
			if(elements[index].className=="holder")
				this.holders[this.holders.length]=elements[index];
			if(elements[index].className=="commandbutton")
				this.okbutton=elements[index];
		}

		this._get();
	}
		
	function getData()
	{	
		this.req = initXMLHTTPRequest();
		this.req.open("POST","includes/db.php",true);
		this.req.send('');
		this.req.onreadystatechange=onReadyState;
	}
	
	function updateData() 
	{
		var outstring='';
		for(var x in this.selects) {
			var select=document.getElementById(this.selects[x]);
			if(select) {
				select.options.length=0;
			}
		}
		for(var e in this.holders) {
			if(this.holders[e].innerHTML!="") {
				var caption = this.holders[e].getElementsByTagName('a').item(0).getAttribute('sename');
				var url = this.holders[e].getElementsByTagName('a').item(0).getAttribute('value');
				var left = this.holders[e].style.left;
				left = left.substring(0,left.length-2);
				var top = this.holders[e].style.top;
				top = top.substring(0,top.length-2);
				if (document.layers){
					var img = document.layers(this.holders[e].id).style.backgroundImage;
				}else if (document.getElementById){
					var img = document.getElementById(this.holders[e].id).style.backgroundImage;
				}else if (document.all){
					var img = document.all(this.holders[e].id).style.backgroundImage;
				}
				var imgs = img.split(this.iconsDir);
				imgs[1] = imgs[1] ? imgs[1].replace('"', '') : "";
				var imgout = imgs[1] ? imgs[1].substring(0,(imgs[1].length-1)) : "";
				//var img = this.holders[e].style.backgroundImage;
				outstring += caption+"|"+url+"|"+left+"|"+top+"|"+imgout+"||";
				for(var x in this.selects) {
					var select=document.getElementById(this.selects[x]);
					select.options.length=0;
					if(select)
					{
						var option=new Option(caption,left+"_"+top);
						select.options[select.options.length] = option;
						select.selectedIndex=-1;
					}
				}
			}
		}
		if(!outstring) outstring = "empty";
		//alert(outstring);
		this.req.open("POST","includes/db.php?out=" + outstring,true);
		this.req.send('');
		this.req.onreadystatechange=onReadyState;
		if(this.layover) {
			this.layover.style.display="none";
			this.form.style.display="none";
		 	this.layover=null;
			this.setImage("");
		}
	}
	
	function showOutput(caption,url,left,top,img)
	{
		if(left < 0 && top < 0) return (true);
		if(img == null) img = "";
	
		left = left - (left % 90);
		top = top - (top % 90);
		var id = left + '_' + top;
		
		this.element=document.getElementById("i" + id);
		if(!this.element) return (false);
		if(this.element.className == "" || this.element.className == null) return (false);
		if(this.element.className!='holder') return (false);
		
		if(img != "") 
			if (img.indexOf( this.iconsDir ) >= 0 )
				this.element.style.backgroundImage = "url(" + img + ")";
			else
				this.element.style.backgroundImage = "url(" + this.iconsDir + img + ")";
		else
			this.element.style.backgroundImage = "";
		
		if(this.element) this.element.innerHTML="";
		if(caption!="")
		{
			var lnk = document.createElement('a');
	
			lnk.className = 'selink';
			lnk.href = "javascript:search.click('"+url+"');"
			lnk.setAttribute('value', url);
			lnk.setAttribute('sename',caption);
			if( img.indexOf("icons/") < 0 ) lnk.innerHTML = caption;
	
			lnk.style.display = 'block';
			this.element.appendChild(lnk);				
			lnk.style.top = (this.element.offsetHeight-lnk.offsetHeight)/2;
			lnk.style.left = (this.element.offsetWidth-lnk.offsetWidth)/2;
		}	
		this.element.setAttribute("icon",img);

		for(var x in this.selects) {
			var select=document.getElementById(this.selects[x]);
			if(select)
			{
				var option=new Option(caption,id);
				select.options[select.options.length] = option;
				select.selectedIndex=-1;
			}
		}
	}
	
	function gotoUrl(url) {
		if(this.clipBoard) this.clipBoard.style.display = 'none';
		if(this.OnFocus) this.OnFocus.style.display = 'none';
		window.open(url);	
	}
	
	function createClipboard() {
		return document.getElementById('clipboard');
	}
	
	function mouseUp(evnt) 
	{
		var mouse=mouseFromWindow(evnt);
		this.element=hoverHolder(mouse);
		/*
		if (!evnt) var evnt = window.event;
		var tg = (evnt) ? evnt.srcElement : evnt.target;
		if (tg.nodeName != 'DIV') {
			if(this.clipBoard) this.clipBoard.style.display = 'none';
			this.clipBoard = null;
			return;
		}
		*/
		//alert(this.element);
		if(this.source && this.element && this.clipBoard!=null) {
			var src = this.toElem(this.source);
			var elm = this.toElem(this.element);
			this.display(src.caption, src.url, elm.left, elm.top, src.img);
			if(elm.caption)
				this.display(elm.caption, elm.url, src.left, src.top, elm.img);
			else
				this.display("", "", src.left, src.top, "");
			this.source = null;
			this.OnFocus.style.display = 'none';
			this._set();
		}
		if(this.clipBoard) this.clipBoard.style.display = 'none';
		this.clipBoard = null;
	}
	
	function mouseDown(evnt) 
	{
		var mouse=mouseFromWindow(evnt);
		this.element=hoverHolder(mouse);
		if(this.element==null) return(0);
		if(this.OnFocus.style.display=='block') {
			this.OnFocus.style.display="none";
			this.panel(1);
		}
		if (!evnt) var evnt = window.event;
		var tg = (window.event) ? evnt.srcElement : evnt.target;
		if (tg.nodeName != 'DIV') {
			this.element = null;
			this.clipBoard = null;
			return;
		}
		if(this.element && !this.layover) {
			this.clipBoard = this.createClip();
			this.clipBoard.innerHTML = this.element.innerHTML;
			this.clipBoard.style.backgroundImage = this.element.style.backgroundImage;
			this.source = this.element;
		}
	}

	function mouseMove(evnt)
	{	
		if(!this.drag) return (0);
		// Get mouse co-ordinates and element beneath the mouse.
		var mouse=mouseFromWindow(evnt);
		//Adjust element position on mouse center
		var mousex = mouse.x-40;
		var mousey = mouse.y-15;
		if (this.clipBoard)
		{
			//Update clipBoard co-ordinates.
			this.clipBoard.style.left = (isNull(parseInt(this.clipBoard.style.left)) + mousex - isNull(this.mX))+"px";
			this.clipBoard.style.top = (isNull(parseInt(this.clipBoard.style.top)) + mousey - isNull(this.mY))+"px";

			this.mX=mousex;
			this.mY=mousey;
			
			this.clipBoard.style.display='block';
		} 
		this.element=hoverHolder(mouse);

		if(this.element && this.OnFocus) 
		{
			this.OnFocus.style.left=this.element.offsetLeft-3+"px";
			this.OnFocus.style.top=this.element.offsetTop-3+"px";
			if(this.OnFocus.style.display=='none') this.OnFocus.style.display='block';
		}
		else if (this.OnFocus)
			this.OnFocus.style.display='none';
		
		this.updateHolder();
	}

	function updateFocusHolder()
	{
		if(this.element && this.OnFocus) 
			if(this.element == this.OnFocus) return(true);
		
		var FocusElement = this.toElem(this.element);
		
		if(this.OnFocus)	
			if(FocusElement.caption == "" || FocusElement.caption == null)
				this.OnFocus.innerHTML = "";
		
		if(this.element==null) return (true);
	
		if (this.element.className.toLowerCase()!="holder")
			return true;
	
		if(FocusElement.caption == "" || FocusElement.caption == null)
			if(this.clipBoard == null || this.source == null) 
				this.OnFocus.innerHTML='<img id="class" src="images/bgadd.png">';
			else
				this.OnFocus.style.backgroundColor = "#e6f1f8";
		else this.OnFocus.style.display = 'none';
	}

	function HTMLtoElement(elem)
	{
		var se;	var se_url;	var se_image; var se_top; var se_left; var coor;
		if(elem) {
			for(var index = 0; index < elem.childNodes.length; index++)
			{
				if(elem.childNodes[index].tagName.toLowerCase() == "a") {
					se = elem.childNodes[index].getAttribute("sename");
					se_url = elem.childNodes[index].getAttribute("value");
				}
			}
			if(elem) coor = elem.id.substring(1,elem.id.length).split("_");
			if(se != ""){	
				se_image = elem.getAttribute('icon');
				return { caption : se , url : se_url , img : se_image , left : coor[0] , top : coor[1] };
			}
			else
				return { caption : "" , url : "" , img : "" , left : coor[0] , top : coor[1] };
		}
		return "";
	}
	
	function setBgImage(image)
	{
		this.bkImg = image;
		var elements=document.getElementsByTagName('img');

		for (var index=0;index<elements.length ;index++ )
		{
			if(elements[index].className=="urlimage") {
				if(elements[index].id==image)
					elements[index].style.borderColor = "black";
				else
					elements[index].style.borderColor = "white"
			}
		}
		
	}
	
	function showPanel(action) 
	{
		var body=document.body;
		this.drag=false;

		// Set popup attributes.
		if(!this.layover) {
			this.layover=document.createElement('div');
			this.layover.id="popup";
			this.layover.className="popup";
			this.layover.style.left = body.offsetLeft;
			this.layover.style.top = body.offsetTop;
			this.layover.style.width = ( body.scrollWidth > body.offsetWidth ? body.scrollWidth : body.offsetWidth + "px");
			this.layover.style.height = ( body.scrollHeight > body.offsetHeight ? body.scrollHeight : body.offsetHeight + "px");
			if(this.layover.style.display!='block') body.appendChild(this.layover);
			this.layover.style.display='block';
		}
		
		// Get form that is used to read new bookmark details.
		if(action == this.Join) var theForm = document.getElementById("join");
		else if(action == this.Login) var theForm = document.getElementById("login");
		else var theForm = document.getElementById("newengine");
		
		this.form = theForm;
		this.form.style.zIndex=1;
		if(this.element) this.form.setAttribute("element",this.element.id);
		else {
			for(var x in this.holders) {
				if(this.holders[x].innerHTML == "") {
					this.form.setAttribute("element",this.holders[x].id);
					break;
				}
			}
		}
		this.form.style.display = 'block';
		this.form.style.left = body.offsetLeft + (( body.offsetWidth - this.form.offsetWidth)/2)+"px";
		if(action != this.Edit) document.getElementById('edfields').style.visibility = 'hidden';
	
		switch(action) {
			case this.New:
				document.getElementById('new').style.display="block";
				document.getElementById('edit').style.display="none";
				document.getElementById('del').style.display="none";
				var temp=document.getElementById('se_name');
				if(temp) temp.value="";
				temp=document.getElementById('se_url');
				if(temp) temp.value="http://";
				this.okbutton.innerHTML="Save";
				this.okbutton.href = "javascript:search.close(1)";
			break;
			case this.Edit:
				document.getElementById('new').style.display="none";
				document.getElementById('edit').style.display="block";
				document.getElementById('del').style.display="none";
				var temp=document.getElementById('editurl');
				if(temp) temp.selectedIndex=-1;
				var temp=document.getElementById('ed_name');
				if(temp) temp.value="";
				temp=document.getElementById('ed_url');
				if(temp) temp.value="http://";
				this.okbutton.innerHTML="Save";
				this.okbutton.href = "javascript:search.close(2)";
			break;
			case this.Delete:
				document.getElementById('new').style.display="none";
				document.getElementById('edit').style.display="none";
				document.getElementById('del').style.display="block";
				this.okbutton.innerHTML="Delete";
				this.okbutton.href = "javascript:search.close(3)";
			break;
		}
	}
	
	function loadElementData(id)
	{
		var element = document.getElementById('i'+id);
		if(!element) { document.getElementById('edfields').style.visibility = 'hidden'; return }
		this.element = this.toElem(element);
		document.getElementById('edfields').style.visibility = 'visible';
		document.getElementById('ed_name').value = this.element.caption;
		document.getElementById('ed_url').value = this.element.url;
		this.form.setAttribute("bkImg",this.element.img);
		//alert(this.element.caption);
	}

	function closePanel(action) {
		switch(action) {
			default:
				this.layover.style.display="none";
				this.form.style.display="none";
				if(this.layover) this.layover=null;
				this.setImage("");
			break;
			case this.New:
				var id = this.form.getAttribute('element');
				this.element = document.getElementById(id);
				var name = document.getElementById('se_name');
				var url = document.getElementById('se_url');
				if(name.value=="")
				{
					name.focus();
					alert("Bookmark name is empty.\nPlease enter a bookmark name.");
					return;
				}
				if(url.value=="" || !isUrl(url.value))
				{
					url.focus();
					alert("Bookmark's url is empty or invalid.\nPlease enter a valid bookmark's url.");
					return;
				}
				if(!this.bkImg) this.bkImg = "bgblack.png";
				this.display(name.value, url.value, parseInt(this.element.style.left), parseInt(this.element.style.top), this.bkImg);
				this._set();
				this.bkImg = null;
			break;
			case this.Edit:
				var id = document.getElementById('editurl').value;
				this.element = document.getElementById("i" + id);
				if(document.getElementById('editurl').value=="") {
					document.getElementById('editurl').focus();
					alert("Please select a bookmark name.");
					return;
				}
				var name = document.getElementById('ed_name');
				var url = document.getElementById('ed_url');
				if(name.value=="")
				{
					name.focus();
					alert("Bookmark name is empty.\nPlease enter a bookmark name.");
					return;
				}
				if(url.value=="" || !isUrl(url.value))
				{
					url.focus();
					alert("Bookmark's url is empty or invalid.\nPlease enter a valid bookmark's url.");
					return;
				}
				if(!this.bkImg) this.bkImg = this.form.getAttribute('bkImg');
				this.display(name.value, url.value, parseInt(this.element.style.left), parseInt(this.element.style.top), this.bkImg);
				this._set();
			break;
			case this.Delete:
				if(document.getElementById('delurl').value=="") {
					document.getElementById('delurl').focus();
					alert("Bookmark name is empty.\nPlease select a bookmark name.");
					return;
				}
				var id = document.getElementById('delurl').value;
				this.element = document.getElementById("i" + id);
				this.element.style.backgroundImage = ""
				this.element.innerHTML = "";
				this._set();
			break;
			case this.Join:
				var id = this.form.getAttribute('element');
				this.element = document.getElementById(id);
				var name = document.getElementById('jo_name');
				var email = document.getElementById('jo_email');
				var pass = document.getElementById('jo_pass');
				var repass = document.getElementById('jo_repass');
				
				if(name.value=="" || name.value.length<4 || name.value.length>20 || !isAlphaNum(name.value) )//
				{
					name.focus();
					alert("Desired user name is empty or invalid.\nPlease enter a user name.");
					return false;
				}
				if(email.value=="" || !isEmail(email.value))//
				{
					email.focus();
					alert("E-Mail address is empty or invalid.\nPlease enter a valid e-mail address.");
					return false;
				}
				if(pass.value=="" || pass.value.length<4 || !isAlphaNum(pass.value))//
				{
					pass.focus();
					alert("Password is empty or short.\nPlease enter a valid password.");
					return false;
				}
				if(repass.value=="" || repass.value!=pass.value)
				{
					repass.focus();
					alert("Passwords not matching.\nPlease re-enter password.");
					return false;
				}
			break;
			case this.Login:
				var id = this.form.getAttribute('element');
				this.element = document.getElementById(id);
				var name = document.getElementById('lo_name');
				var pass = document.getElementById('lo_pass');
				if(name.value=="" || name.value.length<4 || name.value.length>20 || !isAlphaNum(name.value) )//
				{
					name.focus();
					alert("User name is empty or invalid. Please enter a valid user name.");
					return false;
				}
				if(pass.value=="" || pass.value.length<4 || !isAlphaNum(pass.value))//
				{
					pass.focus();
					alert("Password is empty or short. Please enter a valid password.");
					return false;
				}
			break;
		}
		this.drag=true;
	}
}

function hoverHolder(pos)
{
	var returnHolder=null;
	for (var index=0;index<search.holders.length ;index++ )
	{
		if(isMouseHover(search.holders[index],pos))
			returnHolder= search.holders[index];
	}
	return(returnHolder);
}

function isMouseHover(element,mousepos)
{
	if(!element) return false;
	var position=getElementPosition(element);
	var isIE7Min = getIEVersionNumber() < 8;
	if (isIE && isIE7Min) {
		position.left = position.left - 880;
		position.top = position.top + 355;
	}	
	if(mousepos.x<position.left || mousepos.x>(position.left+element.offsetWidth))
		return false;
	if(mousepos.y<position.top || mousepos.y>(position.top+element.offsetHeight))
		return false;
	return true;
}

function getElementPosition(element)
{	
	var elementCurrent=element;
	var left=0;  
	var top = 0; 
	while(elementCurrent)
	{   
		left += elementCurrent.offsetLeft;    
		top += elementCurrent.offsetTop;   
		elementCurrent = elementCurrent.offsetParent;  
	}
	return {left:left,top:top};
}

var search = new search();

