var BasicFunctions = {
	init: function () {
	   if (BrowserDetect.browser == "Explorer") {
               attachEvent("onload", PersonalBookmarks.init);
	   } else {
              addEventListener("load",PersonalBookmarks.init,false);
	   }
	},
	addEvent: function (objRef, eventType, functionToCall, captureSwitch) {
	   if (objRef.addEventListener) {
	      objRef.addEventListener(eventType, functionToCall, captureSwitch);
	      return true;
	   } else if (objRef.attachEvent) {
	      return objRef.attachEvent("on"+eventType, functionToCall);
	   } else {
	      // error handling
	      return false;
	   }
	},
	findPos: function(obj){
	   var curleft = curtop = 0;
	   if(obj.offsetParent){
	      curleft = obj.offsetLeft
	      curtop = obj.offsetTop
	      while(obj = obj.offsetParent){
	         curleft += obj.offsetLeft;
	         curtop  += obj.offsetTop;
	      }
	   }
	   return [curleft,curtop];
	},
	calcPopupPosition: function(mcoords,winsize){
	   var xoff = yoff = xwin = ywin = xpos = ypos = 0;

	   if(window.pageYOffset){
	      yoff = window.pageYOffset;
	   }else if(document.documentElement && document.documentElement.scrollTop){
	      yoff = document.documentElement.scrollTop;
	   }else if(document.body && document.body.scrollTop){
	      yoff = document.body.scrollTop;
	   }

	   if(window.pageXOffset){
	      xoff = window.pageXOffset;
	   }else if(document.documentElement && document.documentElement.scrollLeft){
	      xoff = document.documentElement.scrollLeft;
	   }else if(document.body && document.body.scrollLeft){
	      xoff = document.body.scrollLeft;
	   }

	   if(self.innerHeight){
	      xwin = self.innerWidth;
	      ywin = self.innerHeight;
	   }else if (document.documentElement && document.documentElement.clientHeight){
	      xwin = document.documentElement.clientWidth;
	      ywin = document.documentElement.clientHeight;
	   }else if(document.body){
	      xwin = document.body.clientWidth;
	      ywin = document.body.clientHeight;
	   }

	   if((mcoords[1] - yoff - winsize[1] - 25) < 0){
	      ypos = mcoords[1] + 25;
	   } else {
	      ypos = (mcoords[1] - (20 + winsize[1]));
	   }

	   if((mcoords[0] - xoff + (winsize[0] / 2)) > xwin){
	      xpos = (xwin - 20 - winsize[0] + xoff);	
	   } else if((mcoords[0] - xoff - (winsize[0] / 2)) < 0){
	      xpos =  20 + xoff;
	   } else{
	      xpos = mcoords[0] - (winsize[0] / 2);
	   }

	   return [xpos,ypos];
	},
	uriEncodeString: function(txt){
	   if(typeof encodeURIComponent=="function"){
	      return encodeURIComponent(txt);
	   }else{
	      return escape(txt);
	   }
	}
};

var PersonalBookmarks = {
	init: function () {
	   this.mainDiv = document.getElementById("personal_bookmarks");
	   this.rows    = PersonalBookmarks.load();	   
	   this.ready   = PersonalBookmarks.show();	   
	},
	dispatchAll: function(arg) {
	   if(!arg){
	      return;
	   } else if(arg == "undef"){
	      return undef;
	   } else if(arg == "true"){
	      return true;
	   }else{
	      return;
	   }
	},
	unload: function() {
	   var mainDiv = document.getElementById("mybookmarks");
	   var len     = mainDiv.childNodes.length;
	   for(var i = 0; i < len; i++){
	      var node = mainDiv.firstChild;
	      mainDiv.removeChild(node);
	   }
	   return true;	   
	},
	load: function() {
	   this.http_request  = false;
	   this.url           = ajax_url;
	   this.cmd           = ajax_cmd;
	   this.personal_id   = personal_id;
	   if(window.XMLHttpRequest){
	      http_request = new XMLHttpRequest();
	         if (http_request.overrideMimeType) {
	            http_request.overrideMimeType('text/xml');
	         }
	      } else if (window.ActiveXObject) {
	         try {
		    http_request = new ActiveXObject("Msxml2.XMLHTTP");
	         } catch (e) {
		    try {
		        http_request = new ActiveXObject("Microsoft.XMLHTTP");
		    } catch (e) {}
	         }
	    }

	    if(!http_request){
	       //  error handling
	       return false;
	    }
	    http_request.onreadystatechange = function(){
	       if (http_request.readyState == 4) {
                  if (http_request.status == 200) {
		     var xmldoc      = http_request.responseXML;
		     var root_node   = xmldoc.documentElement;
		     var iChildren   = root_node.childNodes.length;
		     var iAttributes = root_node.attributes.length;

		     var cat_nodes   = new Array;

		     var cat_nodes  = root_node.getElementsByTagName('bookmark');
		     var i          = 0; 
		     var cat_node   = false;
		     var opt_url    = false;
		     var opt_title  = false;

		     var mainDiv    = document.getElementById("mybookmarks");	   

	             var description_text = root_node.getElementsByTagName('description_text')[0].firstChild.nodeValue;
	             var edit_text        = root_node.getElementsByTagName('edit_text')[0].firstChild.nodeValue;

	             PersonalBookmarks.close_form  = root_node.getElementsByTagName('close_form')[0].firstChild.nodeValue;
	             PersonalBookmarks.title_text  = root_node.getElementsByTagName('title_text')[0].firstChild.nodeValue;
	             PersonalBookmarks.url_text    = root_node.getElementsByTagName('url_text')[0].firstChild.nodeValue;
	             PersonalBookmarks.button_text = root_node.getElementsByTagName('button_text')[0].firstChild.nodeValue;

		     var thisTable = document.createElement("div");
		     thisTable.className = "BmTable";

		     var thisTr = document.createElement("div");
		     thisTr.className = "BmTr";


		     for(i = 0; i < cat_nodes.length; i++){

		        cat_node  = cat_nodes[i];
			opt_url   = cat_node.getElementsByTagName('url')[0].firstChild.nodeValue;
			opt_title = cat_node.getElementsByTagName('title')[0].firstChild.nodeValue;

			var thisTd = document.createElement("div");
			thisTd.className = "BmTd";    	    

			if(BrowserDetect.browser == 'Explorer'){
			   thisTd.style.display  = "inline";
			   thisTd.style.float    = "left";
			}else if(BrowserDetect.browser == 'Firefox'){
	      		   thisTd.setAttribute("style","display: table-cell;");
			}else{
	      		   thisTd.setAttribute("style","display: table-cell;");
			}

			var thisDiv = document.createElement("div");
			thisDiv.className = "mybookmark";    	    
			
			var thisP   = document.createElement("p");
			thisP.className = "edit";

			var thisA   = document.createElement("a");
			thisA.href  = "javascript: PersonalBookmarks.dispatchAll()";
			thisA.id    = "bm_" + i;

			var thisTXT = document.createTextNode(edit_text);	    		
			thisA.appendChild(thisTXT);			

			BasicFunctions.addEvent(thisA, "click", PersonalBookmarks.showFormPopup, false);

			thisP.appendChild(thisA);
			thisA.className = "edit";
			thisDiv.appendChild(thisP);

			
			var thisP   = document.createElement("p");
			thisP.className = "thumbshot";
			var thisA   = document.createElement("a");
			thisA.href  = opt_url;
			var thisImg = document.createElement("img");
			thisImg.alt = opt_title;
			/*
			thisImg.src = "http://www.thumbshots.de/cgi-bin/show.cgi?url=" + encodeURIComponent(opt_url);
			*/

			thisImg.src = external_thumbshot_url + encodeURIComponent(opt_url);

			thisA.appendChild(thisImg);
			thisP.appendChild(thisA);
			thisDiv.appendChild(thisP);
			
			var thisP   = document.createElement("p");
			thisP.className = "title";
			var thisTXT = document.createTextNode(opt_title);	    
			thisP.appendChild(thisTXT);
			thisDiv.appendChild(thisP);
			

			thisTd.appendChild(thisDiv);
			thisTr.appendChild(thisTd);
		     }
		     thisTable.appendChild(thisTr);
		     mainDiv.appendChild(thisTable);
		     var thisTextDiv = document.createElement("div");
		     thisTextDiv.className = "Bmdesc";
		     var thisTXT = document.createTextNode(description_text);	    		
		     thisTextDiv.appendChild(thisTXT);			
		     mainDiv.appendChild(thisTextDiv);
	          }else {
		      alert(http_request.status);
		     // error handling
		  }
               } else {
	          // error handling
               }
	    };

	    var thisDate = new Date();
	    var epoch = thisDate.getTime(); 
	    http_request.open('GET', PersonalBookmarks.url + "?cmd=" + PersonalBookmarks.cmd + "&act=bookmarks&bookmarks_id=" + PersonalBookmarks.personal_id + "&epoch=" + epoch, true);
	    http_request.send(null);
	    return true;
	},
	show: function() {
	   if(this.rows < 1){
	      alert("No data");
	   }
	},
	showFormPopup: function(e) {
	   var targ;
	   if(!e){
	      var e = window.event;
	   }
	   if(e.target){
	      targ = e.target;
	   }else if(e.srcElement){
	      targ = e.srcElement;
	   }
	   if(targ.nodeType == 3){
	      targ  = targ.parentNode;
	   }

	   var closed = PersonalBookmarks.closeFormPopup();

	   var form_win_width  = 330;
	   var form_win_height = 100;

	   var coords  = BasicFunctions.findPos(targ);   
	   var pcoords = BasicFunctions.calcPopupPosition(coords,[form_win_width,form_win_height]);

	   var pos_x = pcoords[0]  + "px";
	   var pos_y = pcoords[1]  + "px";

	   var thisDiv = document.createElement("div");
	   thisDiv.className = "bookmarkform";

	   if(BrowserDetect.browser == 'Explorer'){
	      thisDiv.style.position = "absolute";
	      thisDiv.style.width    =  form_win_width + "px";
	      thisDiv.style.height   =  form_win_height + "px";
	      thisDiv.style.top      = pos_y;
	      thisDiv.style.left     = pos_x;
	      thisDiv.style.display  = "inline";
	   }else{
	      thisDiv.setAttribute("style","display: inline; position: absolute; width: " + form_win_width + "px; height: " + form_win_height + "px; top: " + pos_y + "; left: " + pos_x + "; padding: 0; margin: 0;");
	   }

	   /* alert("Clicked " + e); */

	   var thisP   = document.createElement("p");
	   thisP.className = "bm_close";
	   var thisA   = document.createElement("a");
	   thisA.href  = "javascript: PersonalBookmarks.dispatchAll()";
	   var thisTXT = document.createTextNode(PersonalBookmarks.close_form);	   
	   BasicFunctions.addEvent(thisA, "click", PersonalBookmarks.closeFormPopup, false);
	   thisA.appendChild(thisTXT);
	   thisP.appendChild(thisA);
	   thisDiv.appendChild(thisP);

	   var thisForm = document.createElement("form");
	   thisForm.className = "bm_form";
	   thisForm.action = "javascript: PersonalBookmarks.dispatchAll()";

	   var thisPsub = document.createElement("p");
	   thisPsub.className = "form_row";

	   var thisSpan = document.createElement("span");
	   thisSpan.className = "form_row_left";
	   var thisTXT = document.createTextNode(PersonalBookmarks.title_text);	    		
	   thisSpan.appendChild(thisTXT);
	   thisPsub.appendChild(thisSpan);	


	   var thisSpan = document.createElement("span");
	   thisSpan.className = "form_row_right";
	   if(BrowserDetect.browser == 'Explorer'){
	      var thisTextField1  = document.createElement("<input type='text' name='book_mark_title' id='book_mark_title'>");
	      thisTextField1.style.width = "220px";
	      thisSpan.appendChild(thisTextField1);
	   }else{
	      var thisTextField1  = document.createElement("input");
	      thisTextField1.setAttribute("type", "text");
	      thisTextField1.setAttribute("name", "book_mark_title");
	      thisTextField1.setAttribute("id", "book_mark_title");
	      thisTextField1.setAttribute("style", "width: 220px;");
	      thisSpan.appendChild(thisTextField1);
	   }

	   thisPsub.appendChild(thisSpan);	
	   thisForm.appendChild(thisPsub);

	   var thisPsub = document.createElement("p");
	   thisPsub.className = "form_row";

	   var thisSpan = document.createElement("span");
	   thisSpan.className = "form_row_left";
	   var thisTXT = document.createTextNode(PersonalBookmarks.url_text);	    		
	   thisSpan.appendChild(thisTXT);
	   thisPsub.appendChild(thisSpan);	

	   var thisSpan = document.createElement("span");
	   thisSpan.className = "form_row_right";

	   if(BrowserDetect.browser == 'Explorer'){
	      var thisTextField2  = document.createElement("<input type='text' name='book_mark_url' id='book_mark_url' value='http://'>");
	      thisTextField2.style.width =  "220px";
	      thisSpan.appendChild(thisTextField2);
	   }else{
	      var thisTextField2  = document.createElement("input");
	      thisTextField2.setAttribute("type", "text");
	      thisTextField2.setAttribute("name", "book_mark_url");
	      thisTextField2.setAttribute("id", "book_mark_url");
	      thisTextField2.setAttribute("value", "http://");
	      thisTextField2.setAttribute("style", "width: 220px;");
	      thisSpan.appendChild(thisTextField2);
	   }
	   thisPsub.appendChild(thisSpan);	
	   thisForm.appendChild(thisPsub);


	   var thisPsub = document.createElement("p");
	   thisPsub.className = "form_row";
	   if(BrowserDetect.browser == 'Explorer'){
	      var thisHidden1 = document.createElement("<input type='hidden' name='book_mark_id' id='book_mark_id' value='" +  targ.id + "'>");
	      thisPsub.appendChild(thisHidden1);
	      var thisSubmit = document.createElement("<input type='submit' name='foo' value='" + PersonalBookmarks.button_text + "'>");
	      thisPsub.appendChild(thisSubmit);
	   }else{
	      var thisHidden1 = document.createElement("input");
	      thisHidden1.setAttribute("type", "hidden");
	      thisHidden1.setAttribute("name", "book_mark_id");
	      thisHidden1.setAttribute("value", targ.id);
	      thisPsub.appendChild(thisHidden1);
	      var thisSubmit = document.createElement("input");
	      thisSubmit.setAttribute("type", "submit");
	      thisSubmit.setAttribute("name", "foo");
	      thisSubmit.setAttribute("value", PersonalBookmarks.button_text);
	      thisPsub.appendChild(thisSubmit);
	   }
	   thisForm.appendChild(thisPsub);
	   BasicFunctions.addEvent(thisForm, "submit", PersonalBookmarks.saveFormData, false);
	   thisDiv.appendChild(thisForm);
	   document.getElementsByTagName("body")[0].appendChild(thisDiv);	   	   
	   return false;
	},
	saveFormData: function() {
	   var pNode  = document.getElementsByTagName("body")[0];

	   var inputs = document.getElementsByTagName("input");
	   for (var i = 0; i < inputs.length; i++){
	      if(inputs[i].name == "book_mark_title"){
	         var bookmarkTitle  = inputs[i].value;
	      }
	      if(inputs[i].name == "book_mark_url"){
	         var bookmarkUrl  = inputs[i].value;
	      }
	      if(inputs[i].name == "book_mark_id"){
	         var bookmarkId  = inputs[i].value;
	      }
	   }
	   	   
	   if(window.XMLHttpRequest){
	      http_request = new XMLHttpRequest();
	         if (http_request.overrideMimeType) {
	            http_request.overrideMimeType('text/xml');
	         }
	      } else if (window.ActiveXObject) {
	         try {
		    http_request = new ActiveXObject("Msxml2.XMLHTTP");
	         } catch (e) {
		    try {
		        http_request = new ActiveXObject("Microsoft.XMLHTTP");
		    } catch (e) {}
	         }
	    }

	    if(!http_request){
	       //  error handling
	       return false;
	    }
	    http_request.onreadystatechange = function(){
	       var saved = 0;
	       if (http_request.readyState == 4) {
                  if (http_request.status == 200) {
		     var xmldoc      = http_request.responseXML;
		     var root_node   = xmldoc.documentElement;
		     var iChildren   = root_node.childNodes.length;
		     var iAttributes = root_node.attributes.length;
		     saved  = root_node.getElementsByTagName('found')[0].firstChild.nodeValue;
		  }
               } else {
	          // error handling
               }
	       if(saved > 0){
	          PersonalBookmarks.unload();
	          PersonalBookmarks.closeFormPopup();
	          PersonalBookmarks.load();
	       }
	   }; 
	   var thisDate = new Date();
	   var epoch = thisDate.getTime();  
 
	   http_request.open('GET', PersonalBookmarks.url + "?cmd=" + PersonalBookmarks.cmd + "&act=bookmarks&bct=save_data&bookmarks_id=" + PersonalBookmarks.personal_id + "&bookmarkId=" + bookmarkId + "&bookmarkTitle=" + BasicFunctions.uriEncodeString(bookmarkTitle) + "&bookmarkUrl=" + BasicFunctions.uriEncodeString(bookmarkUrl) + "&epoch=" + epoch, true);
	   http_request.send(null);	   
	   return false;
	},
	closeFormPopup: function() {
	   var pNode  = document.getElementsByTagName("body")[0];
	   var divs   = document.getElementsByTagName("div");
	   var this_div = false;

	   for(var i=0;i<divs.length;i++){
	      this_div = divs[i];
	      if(this_div.className == "bookmarkform"){
	         pNode.removeChild(this_div);
	      }
	   }
	   
	   return false;
	}
};

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};

BrowserDetect.init();
BasicFunctions.init();

