// +----------------------------------------------------------------------+
// | Copyright (c) 2006-2009 Karin Schellner                              |
// +----------------------------------------------------------------------+
// | This program is free software: you can redistribute it and/or modify |
// | it under the terms of the GNU General Public License as published by |
// | the Free Software Foundation, either version 3 of the License, or    |
// | (at your option) any later version.                                  |
// |                                                                      |
// | This program is distributed in the hope that it will be useful,      |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        |
// | GNU General Public License for more details.                         |
// |                                                                      | 
// | You should have received a copy of the GNU General Public License    |
// | along with this program. If not, see <http://www.gnu.org/licenses/>. |
// +----------------------------------------------------------------------+	

 var req;
 var panel;
 var firstname, lastname, personId, photoId, photoref;
 var mode;
 var role, dog_id, parentSex;
 var countrySelectHtml;

	function deletionForbiddenDialog(adminwebaddress, objects) {
		html = "<b>You do not have permission to delete "+objects+"!</b>";
		html+="<br> <div style='padding:10px'> Please contact the Administrator (<b>"+adminwebaddress+"</b>) with your request for deletion.</div>";
		var handleOK = function() { 
	    	this.hide(); 
		}; 
		mySimpleDialog = new YAHOO.widget.SimpleDialog("simpledlg", { 
	    width:"400px",  
	    fixedcenter: true,  
	    constraintoviewport: true,  
	    underlay:"shadow", 
	    close:true,  
	    visible:false,  
	    draggable:true,
			modal:true,
			effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.30}
			} ); 
		mySimpleDialog.setHeader("Deletion not allowed!"); 
		mySimpleDialog.setBody(html); 
		mySimpleDialog.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_WARN); 
		var myButtons = [ { text:" OK ", handler:handleOK, isDefault:true } ]; 
		mySimpleDialog.cfg.queueProperty("buttons", myButtons); 
		mySimpleDialog.render(document.body);
		mySimpleDialog.show();	
	}

	function startSetPrimaryPhoto(phId, dId) {
		url = "ajax/setPrimaryPhoto.php?photoId=" + escape(phId)+ "&dogId=" + escape(dId)+"&rand="+new Date().getTime();
		if (window.XMLHttpRequest) { // Non-IE browsers
			req = new XMLHttpRequest();
			req.onreadystatechange = processSetPrimaryPhoto;
			try {
				req.open("GET", url, true);
				document.body.style.cursor="wait";
			} catch (e) {
				alert(e);
			}
			req.send(null);
		} else if (window.ActiveXObject) { // IE
			req = new ActiveXObject("Microsoft.XMLHTTP");
			if (req) {
				req.onreadystatechange = processSetPrimaryPhoto;
				req.open("GET", url, true);
				req.send();
				document.body.style.cursor="wait";
			}
		}
  	}

  	function processSetPrimaryPhoto() {
    	if (req.readyState == 4) { // Complete
    		document.body.style.cursor="auto";
      		if (req.status == 200) { // OK response
				//alert(req.responseText);
			} else {
        		alert("Problem: " + req.statusText);      
			}
		}
	}

	function editSaveCopyright(phId) {
		var el = document.getElementsByName('copyright_'+phId)[0];
		var btn = document.getElementsByName('editSave_'+phId)[0];
		if (btn.value == 'edit') {
			el.removeAttribute('readOnly');
			btn.value='save';
		} else {
			el.setAttribute('readOnly','readOnly');
			var cr = el.value;
			startSaveCopyright(cr, phId);
			btn.value='edit';
		}
	}
	
	function startSaveCopyright(cr_text,phId) {
		url = "ajax/saveCopyright.php?photoId=" + escape(phId)+ "&text=" + escape(cr_text)+"&rand="+new Date().getTime();
		if (window.XMLHttpRequest) { // Non-IE browsers
			req = new XMLHttpRequest();
			req.onreadystatechange = processSaveCopyright;
			try {
				req.open("GET", url, true);
				document.body.style.cursor="wait";
			} catch (e) {
				alert(e);
			}
			req.send(null);
		} else if (window.ActiveXObject) { // IE
			req = new ActiveXObject("Microsoft.XMLHTTP");
			if (req) {
				req.onreadystatechange = processSaveCopyright;
				req.open("GET", url, true);
				req.send();
				document.body.style.cursor="wait";
			}
		}
  	}

  	function processSaveCopyright() {
    	if (req.readyState == 4) { // Complete
    		document.body.style.cursor="auto";
      		if (req.status == 200) { // OK response
				//alert(req.responseText);
			} else {
        		alert("Problem: " + req.statusText);      
			}
		}
	}


	//	
	// AJAX calls for saving Photo PostedBy changes
	//
	function editSavePhotoPostedBy(phId) {
		var el = document.getElementsByName('postedBy_'+phId)[0];
		var btn = document.getElementsByName('editSavePhotoPostedBy_'+phId)[0];
		if (btn.value == 'edit') {
			el.removeAttribute('readOnly');
			btn.value='save';
		} else {
			el.setAttribute('readOnly','readOnly');
			var cr = el.value;
			startSavePhotoPostedBy(cr, phId);
			btn.value='edit';
		}
	}
	function startSavePhotoPostedBy(cr_text,phId) {
		url = "ajax/savePhotoPostedBy.php?photoId=" + escape(phId)+ "&text=" + escape(cr_text)+"&rand="+new Date().getTime();
		if (window.XMLHttpRequest) { // Non-IE browsers
			req = new XMLHttpRequest();
			req.onreadystatechange = processSavePhotoPostedBy;
			try {
				req.open("GET", url, true);
				document.body.style.cursor="wait";
			} catch (e) {
				alert(e);
			}
			req.send(null);
		} else if (window.ActiveXObject) { // IE
			req = new ActiveXObject("Microsoft.XMLHTTP");
			if (req) {
				req.onreadystatechange = processSavePhotoPostedBy;
				req.open("GET", url, true);
				req.send();
				document.body.style.cursor="wait";
			}
		}
  	}
  	function processSavePhotoPostedBy() {
    	if (req.readyState == 4) { // Complete
    		document.body.style.cursor="auto";
      		if (req.status == 200) { // OK response
				//alert(req.responseText);
			} else {
        		alert("Problem: " + req.statusText);      
			}
		}
	}


	//	
	// AJAX calls for saving Photonotes changes
	//
	function editSavePhotonotes(phId) {
		var el = document.getElementsByName('photonotes_'+phId)[0];
		var btn = document.getElementsByName('editSavePhotonotes_'+phId)[0];
		if (btn.value == 'edit') {
			el.removeAttribute('readOnly');
			btn.value='save';
		} else {
			el.setAttribute('readOnly','readOnly');
			var cr = el.value;
			startSavePhotonotes(cr, phId);
			btn.value='edit';
		}
	}
	function startSavePhotonotes(cr_text,phId) {
		url = "ajax/savePhotonotes.php?photoId=" + escape(phId)+ "&text=" + escape(cr_text)+"&rand="+new Date().getTime();
		if (window.XMLHttpRequest) { // Non-IE browsers
			req = new XMLHttpRequest();
			req.onreadystatechange = processSavePhotonotes;
			try {
				req.open("GET", url, true);
				document.body.style.cursor="wait";
			} catch (e) {
				alert(e);
			}
			req.send(null);
		} else if (window.ActiveXObject) { // IE
			req = new ActiveXObject("Microsoft.XMLHTTP");
			if (req) {
				req.onreadystatechange = processSavePhotonotes;
				req.open("GET", url, true);
				req.send();
				document.body.style.cursor="wait";
			}
		}
  	}
  	function processSavePhotonotes() {
    	if (req.readyState == 4) { // Complete
    		document.body.style.cursor="auto";
      		if (req.status == 200) { // OK response
				//alert(req.responseText);
			} else {
        		alert("Problem: " + req.statusText);      
			}
		}
	}


	function switchUrlOrFileDisplay()
	{
	  if (document.getElementById("url").disabled) {
		//alert("make url available");
		document.getElementById("url").disabled='';
		document.getElementById("file").disabled='disabled';
	  } else {
		//alert("make file available");
		document.getElementById("file").disabled='';
		document.getElementById("url").disabled='disabled';  
	  }
	}


	function checkEmptyDamSireField() {
		if (document.getElementById("damInput").value=="")
			document.getElementById("damId").value="";
		if (document.getElementById("sireInput").value=="")
			document.getElementById("sireId").value="";
	} 

 	function changeBreederQuestion() {

		var breederQuestion = document.getElementById('breederQuestion');

  		if (document.getElementsByName('copytopersondb')[0].checked == true) {

    		var deactivated = false;

			breederQuestion.removeAttribute("style");

  		} else {

    		var deactivated = true;

			breederQuestion.style.color="#aaaaaa";

  		}

		var radio = document.getElementsByName('breeder');

		for(i=0; i<radio.length;i++) 

			radio[i].disabled=deactivated;

	}


 	function deletePhoto(photo_id) {

		photoId = photo_id;

		html = '<p> Are you sure you want to remove this photo? </p>'

		html = html + '<input type="button" class="button" name="action" value=" OK " onclick="startDeletePhoto('+photo_id+')" />'

		panel.setHeader("Remove this photo");
		
		panel.setBody(html);
		
		// if IE, scroll to top, because panel is opened there!
		if (document.all) 
			  window.scrollTo(100, 100);
	
	}


	function addPhoto() {

			panel.setHeader("Add Photo Reference");

			body = '<div class="content"><div align="left"><p>Please specify a URL or a file from your filesystem: <br> </p></div>';
			body += '<form method="POST" action="manage.php" enctype="multipart/form-data">';
			body += '<table border="0" cellspacing="0" cellpadding="4"><tr>';
			body += '<td width="80px"><label><input type="radio" class="radio" name="urlOrFile" value="url" onclick="switchUrlOrFileDisplay()">URL</label></td>';
			body += '<td><input type="text" name="url" size="50" value="" disabled="disabled" id="url"></td>';
			body += '</tr><tr>';
			body += '<td width="80px"><label><input type="radio" class="radio" name="urlOrFile" value="file" checked="checked" onclick="switchUrlOrFileDisplay()">Local File</label></td>';
			body += '<td><input type="file" name="image" size="30" value="" id="file" accept="image/jpg, image/gif, image/jpeg, image/bmp, image/tiff, image/png"></td>';
			body += '</tr><tr>';
			body += '<td colspan="2" align="center"><input type="checkbox" name="primary" ><label> Set as primary image </label></td></tr>';
			body += '<tr><td width="80px"><label><b>Copyright Owner: </b></label></td><td><input type="text" name="copyright" size="50"></td></tr>';
			body += '<tr><td width="80px"><label>Posted by: </label></td><td><input type="text" name="postedBy" size="50"></td></tr>';
			body += '<tr><td width="80px"><label>Notes: </label></td><td><input type="text" name="notes" size="50"></td></tr>';
			// copyright
			body += '<tr><td colspan="2"><hr></td><tr>';
			body += "<tr><td colspan='2'><label style='color:red'>Please note that all uploaded pictures are put in the public domain. Please don't upload copyrighted pictures.</label></td></tr>";
			body += '<tr><td colspan="2"><input type="checkbox" name="confirm_right" onclick="if (this.checked) getElementById(\'submit_btn\').disabled=false; else getElementById(\'submit_btn\').disabled=true;" ><label><b> In uploading this image, I confirm that it is not protected by any third party copyright.</b></label></td></tr>';	
			body += '<input type="hidden" name="dogId" value="'+dog_id+'"/>';
			body += '<tr><td colspan="2" align="center"><input id="submit_btn" type="Submit" name="Submit" value="Submit" disabled="disabled"></td>';
			body += '</tr></table>';
			body += '</form></div>';
			panel.setBody(body);

	}

	function startCheckRegNr(regNr) {
		if (regNr != null) {			
			url = "ajax/checkRegNr.php?regNr=" + escape(regNr)+"&rand="+new Date().getTime();
			if (window.XMLHttpRequest) { // Non-IE browsers
				req = new XMLHttpRequest();
				req.onreadystatechange = processCheckRegNr;
				try {
					req.open("GET", url, true);
					document.body.style.cursor="wait";
				} catch (e) {
					alert(e);
				}
				req.send(null);
			} else if (window.ActiveXObject) { // IE
				req = new ActiveXObject("Microsoft.XMLHTTP");
				if (req) {
					req.onreadystatechange = processCheckRegNr;
					req.open("GET", url, true);
					req.send();
					document.body.style.cursor="wait";
				}
			}
		}
	}
	
	function processCheckRegNr() {
	    if (req.readyState == 4) { // Complete
	    	document.body.style.cursor="auto";
	      if (req.status == 200) { // OK response
					resp = req.responseText.split(';');
					if (resp[0] == "ok" || resp[0] == dog_id) {
						var actionBtn = document.createElement("input");						
						actionBtn.setAttribute('name','action');
						actionBtn.setAttribute('value','Save');				
						updateForm.appendChild(actionBtn);
						updateForm.submit();
					} else {					
						html='<div class="content"><div align="left"><p>The dog with name </p><p><a href="details.php?id='+ escape(resp[0]) + '">'+resp[1]+'</a></p><p> already has this number. Please verify!</p></div>';		
						var handleOK = function() { 
							this.hide(); 
						}; 
						mySimpleDialog = new YAHOO.widget.SimpleDialog("simpledlg", { 
						width:"400px",  
						fixedcenter: true,  
						constraintoviewport: true,  
						underlay:"shadow", 
						close:true,  
						visible:false,  
						draggable:true,
							modal:true,
							effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.30}
							} ); 
						mySimpleDialog.setHeader("Duplicate Registration Number!"); 
						mySimpleDialog.setBody(html); 
						mySimpleDialog.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_WARN); 
						var myButtons = [ { text:" OK ", handler:handleOK, isDefault:true } ]; 
						mySimpleDialog.cfg.queueProperty("buttons", myButtons); 
						mySimpleDialog.render(document.body);
						mySimpleDialog.show();
					}
			} else {
		        alert("Problem: " + req.statusText);      
			}
    	}						
	}

	function startDeletePhoto(photoId) {

		url = "ajax/deletePhoto.php?photoId=" + escape(photoId)+"&rand="+new Date().getTime();

		if (window.XMLHttpRequest) { // Non-IE browsers

			req = new XMLHttpRequest();

			req.onreadystatechange = processDeletePhoto;

			try {

				req.open("GET", url, true);

				document.body.style.cursor="wait";

			} catch (e) {

				alert(e);

			}

			req.send(null);

		} else if (window.ActiveXObject) { // IE

			req = new ActiveXObject("Microsoft.XMLHTTP");

			if (req) {

				req.onreadystatechange = processDeletePhoto;

				req.open("GET", url, true);

				req.send();

				document.body.style.cursor="wait";

			}

		}

  }



  function processDeletePhoto() {

    if (req.readyState == 4) { // Complete

    	document.body.style.cursor="auto";

      if (req.status == 200) { // OK response

				panel.setBody("");

				panel.hide();

				//  according entry from Form

				el = document.getElementById("photo_"+photoId);

				p_el = el.parentNode;

				p_el.removeChild(el);

			} else {

        alert("Problem: " + req.statusText);      

			}

    }

  }


 	function setTestParentSex(s) {

		parentSex = s;

	}


 	function setRole(r) {

		role = r;

	}

	

	function setDogId(d) {

		dog_id = d;

	}

 

 	function createPanel(parentNode) {

	 panel = new YAHOO.widget.Panel("panel", { 

	    width:"400px",  

	    fixedcenter: true,  

	    constraintoviewport: true,  

	    underlay:"shadow", 

	    close:true,  

	    visible:false,  

	    draggable:true,

			modal:true,

			effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.30}

			} ); 
	 	panel.setBody("");

		panel.render(parentNode);

		return panel;

	}



	function startAddPhotoRef(url) {

		photoref = url;

		if (url == null) {

			alert("You have to specify the url!");	

		} else {

      url = "ajax/addPhoto.php?dogId="+dog_id+"&photoref=" + escape(url)+"&rand="+new Date().getTime();

      if (window.XMLHttpRequest) { // Non-IE browsers

        req = new XMLHttpRequest();

        req.onreadystatechange = processAddPhotoRef;

        try {

          req.open("GET", url, true);

          document.body.style.cursor="wait";

        } catch (e) {

          alert(e);

        }

        req.send(null);

      } else if (window.ActiveXObject) { // IE

        req = new ActiveXObject("Microsoft.XMLHTTP");

        if (req) {

          req.onreadystatechange = processAddPhotoRef;

          req.open("GET", url, true);

          req.send();

          document.body.style.cursor="wait";

        }

      }

    }	

	}

	

	function processAddPhotoRef() {

    if (req.readyState == 4) { // Complete

    	document.body.style.cursor="auto";

      if (req.status == 200) { // OK response

				photoId = req.responseText;

				panel.setBody("");

				panel.hide();

				// create according entry in Form, if it does not yet exist

				if  ((photoId != null) && (document.getElementById("photo_"+photoId)==null)) {

					p_el = document.getElementById("photos");

					div_el = document.createElement("div");

					div_el.setAttribute("id", "photo_"+photoId);			

					html = '<p><img src="'+photoref+'" width="250px" alt="'+photoref+'">';

					html = html + '<a href="javascript:deletePhoto('+photoId+');panel.show();">Delete</a></p>';

					div_el.innerHTML = html;

					p_el.appendChild(div_el);

					//alert (html);

				}

  	  } else {

        alert("Problem: " + req.statusText);      

			}

    }	

	}

	function setChooseTestParent() {
		if (panel != null) {
			panel.setHeader("Choose "+parentSex);
			body = '<div class="content"><div align="left"><p>Please enter the name (or part of the name) of the '+parentSex+': </p></div> <form name="parentForm"><input type="text" name="test" style="display:none"/> <table border="0"> <tr> <td ><strong>Name: </strong></td> <td><input style="width:180px" name="parentName" value="" ></td> </tr> <tr> <td>&nbsp;</td><td align="right"> <input type="button" class="button" name="action" value="Submit" onclick="startTestParentSearch(parentForm.parentName.value)" /></td> </tr> </table> </form> </div>';
			panel.setBody(body);
		}
	}
	
	function startTestParentSearch(parentName) {
		if (parentSex == 'sire')
			sex = "male";
		else
			sex = "female";

      url = "ajax/getTestParents.php?parentName=" + escape(parentName) + "&parentSex=" + escape(sex) + "&rand="+new Date().getTime();

      if (window.XMLHttpRequest) { // Non-IE browsers
        req = new XMLHttpRequest();
        req.onreadystatechange = processTestParentSearch;
        try {
          req.open("GET", url, true);
          document.body.style.cursor="wait";
        } catch (e) {
          alert(e);
        }
        req.send(null);
      } else if (window.ActiveXObject) { // IE
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
          req.onreadystatechange = processTestParentSearch;
          req.open("GET", url, true);
          req.send();
          document.body.style.cursor="wait";
        }
      }
	}
	
	
function processTestParentSearch() {
    if (req.readyState == 4) { // Complete
    	document.body.style.cursor="auto";
      if (req.status == 200) { // OK response
		var html = "";
	    var parentArray = req.responseText.split(';');
		if (parentArray.length <= 1) {
			html = html + '<p>Your dog has not been found in our database.<br>Testmatings can only be done with dogs available in our database.</p><a href="#" onclick="setChooseTestParent();">Try with another name</a>';
		} else {
			html = html + '<div style="padding:10px;"><p>Please choose your '+parentSex+' from one of the following dogs found in our database:</p></div>';
			html = html + '<div style="height:200px; overflow:auto; ">';					
			for (var i=0;i<parentArray.length-1;i++) {
				var attrArray = parentArray[i].split('$');
			    html = html + '<input type="radio" class="radio" name="selectedTestParent" value="' + attrArray[0] + '" onClick="startTestMating(this.value);" ><span style="font-weight:bold;font-size:11px">'+attrArray[1]+'</span><label> ( '+attrArray[2]+', '+attrArray[3]+', '+attrArray[4]+', '+attrArray[5]+', '+attrArray[6]+')</label><br>'; 
			}
			html = html + '</div>';	
		}
		panel.cfg.setProperty("width","600px");
		panel.setBody(html);				
      } else {
        alert("Problem: " + req.statusText);      
 	  }
    }
}

function startTestMating(parentId) {
	var query = new PageQuery(document.location.search);
	if (parentSex == "sire") {
		queryStr = parentSex+"="+parentId;
		var existingMother = query.getValue('dam');
		if (existingMother) 
			queryStr=queryStr+"&dam="+existingMother;
	} else { 
		queryStr = parentSex+"="+parentId;
		var existingFather = query.getValue('sire');
		if (existingFather) 
			queryStr=queryStr+"&sire="+existingFather;
	}
	document.location.href = "testmating.php?"+queryStr;
}


function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { 
		return this.keyValuePairs; 
	}
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s)
				return this.keyValuePairs[j].split("=")[1];
		}
		return false;
	}
	this.getParameters = function() {
		var a = new Array(this.getLength());
		for(var j=0; j < this.keyValuePairs.length; j++) {
			a[j] = this.keyValuePairs[j].split("=")[0];
		}
		return a;
	}
	this.getLength = function() { 
		return this.keyValuePairs.length; 
	}
}


	function setSearchTextOnPersonPanel(m) {

		mode = m;

		if (panel != null) {

			panel.setHeader("Add Person");

			body = '<div class="content"><div align="left"><p>Please enter the name of the person: <br> (We will first of all check if he/she is already available in our database.)</p></div> <form name="nameForm"> <table border="0"> <tr> <td ><strong>Firstname: </strong></td> <td><input style="width:180px" name="firstname" value=""></td> </tr> <tr> <td ><strong>Lastname: </strong></td> <td><input style="width:180px" name="lastname" value=""></td> </tr> <tr> <td>&nbsp;</td><td align="right"><input type="button" class="button" name="action" value="Submit" onclick="startPersonSearch(nameForm.firstname.value, nameForm.lastname.value)" /></td> </tr> </table> </form> </div>';

			panel.setBody(body);

		}

	}

 

  function startPersonSearch(fname, lname) {

    firstname = fname;

		lastname = lname;

		if ((lastname == null) || (lastname == "")) {

			alert("You have to specify the lastname!");	

		} else {

      url = "ajax/searchPerson.php?firstname=" + escape(firstname) + "&lastname=" + escape(lastname)+"&rand="+new Date().getTime();

      if (window.XMLHttpRequest) { // Non-IE browsers

        req = new XMLHttpRequest();

        req.onreadystatechange = processPersonSearch;

        try {

          req.open("GET", url, true);

          document.body.style.cursor="wait";

        } catch (e) {

          alert(e);

        }

        req.send(null);

      } else if (window.ActiveXObject) { // IE

        req = new ActiveXObject("Microsoft.XMLHTTP");

        if (req) {

          req.onreadystatechange = processPersonSearch;

          req.open("GET", url, true);

          req.send();

          document.body.style.cursor="wait";

        }

      }

    }

  }



  function processPersonSearch() {

    if (req.readyState == 4) { // Complete

    	document.body.style.cursor="auto";

      if (req.status == 200) { // OK response

				var html = "";

		    var personArray = req.responseText.split(';');

				if (personArray.length <= 1) {

					html = html + '<p>Your person has not been found in our database.</p><a href="#" onclick="setAddPersonTextOnPersonPanel();">Go on adding</a>';

				} else {

					html = html + '<div style="padding:10px"><p>Please check whether your person is one of the following persons found in our database and select your person.</p></div>';
					html = html + '<div style="width:390px;height:150px;overflow:auto">';
					html = html + '<table border="0" cellpadding="10px"><tr><td valign="top"><strong>Found persons: </strong></td><td align="left">';					

					for (var i=0;i<personArray.length-1;i++) {

						var attrArray = personArray[i].split('$');

				    html = html + '<input type="radio" class="radio" name="selectedPerson" value="' + attrArray[0] + '" onClick="getElementById(\'ok_btn\').removeAttribute(\'disabled\');" ><label>'+attrArray[1]+' '+attrArray[2]+', '+attrArray[3]+', '+attrArray[4]+'</label><br>'; 

					}
					html = html + '</td></tr></table></div>';
					html = html + '<table border="0" cellpadding="10px">';
					html = html +	'<tr><td colspan="2"><p>&nbsp;</p><p><b>Please look carefully at all persons listed above.<br>It is very important that you only select this if your \'' + firstname + ' ' + lastname + '\' is not one of the above persons.</b></p>';

					html = html + '<p><input type="radio" class="radio" name="selectedPerson" value="new" onclick="getElementById(\'ok_btn\').removeAttribute(\'disabled\');" \><label>I have checked that \'' + firstname + ' ' + lastname + '\' is not one of the above persons.</label></p>';

					html = html + '</td></tr><tr><td colspan="2" align="center"><input id="ok_btn" type="button" class="button" value="OK" disabled="disabled" onclick="decideNewOrEdit(document.getElementsByName(\'selectedPerson\'));" /></td></tr></table>';

				}

				panel.setBody(html);				

      } else {

        alert("Problem: " + req.statusText);      

			}

    }

  }

	

	function decideNewOrEdit(radioBtns) {

		for (var i=0; i < radioBtns.length; i++) {
			if (radioBtns[i].checked)
			  var selPerson = radioBtns[i].value;
	   	}

		if (selPerson == "new") {
			setAddPersonTextOnPersonPanel();
		} else {
			//mode="contextMode";
			startEditPerson(selPerson);
		}
	}

	

	function setAddPersonTextOnPersonPanel() {

		var html = '<form id="addForm" method="POST" action="managePerson.php" >';

		html = html + '<table>';

		html = html + '<tr><td><label>Firstname: </label></td><td><input name="firstname" value="'+firstname+'" ></td></tr>';

		html = html + '<tr><td><label>Lastname: </label></td><td><label>'+lastname+'</label><input type="hidden" name="lastname" value="'+lastname+'"></td></tr>';

    html = html + '<tr><td><label>Kennel: </label></td><td><input name="kennel" value="" ></td></tr>';
		
    html = html + '<tr><td><label>Street: </label></td><td><input name="street" value="" ></td></tr>';

		html = html + '<tr><td><label>Postal Code: </label></td><td><input name="postalcode" value="" ></td></tr>';

		html = html + '<tr><td><label>City: </label></td><td><input name="city" value="" ></td></tr>';

		html = html + '<tr><td><label>Country: </label></td><td>'+getCountrySelectBox("")+'</td></tr>';

		html = html + '<tr><td><label>Email: </label></td><td><input name="email" value="" ></td></tr>';

		html = html + '<tr><td><label>Phone: </label></td><td><input name="phone" value="" ></td></tr>';

		html = html + '<tr><td><label>Homepage: </label></td><td><input name="homepage" value="" ></td></tr>';

		if (mode=="normalMode") {

			radiobtncode = '<input type="radio" class="radio" name="breeder" value="1" ><label>yes</label>' + '<input type="radio" class="radio" name="breeder" value="0" checked="checked"><label>no</label>';

			html = html + '<tr><td><label>Is Breeder? </label></td><td>'+radiobtncode+'</td></tr>';

		}

		html = html + '<tr><td colspan="2" align="center"><input name="action" type="submit" class="button" value="Add" onclick="javascript: return checkModeforSave(\''+mode+'\',document.getElementById(\'addForm\'));"/></td></tr>';

		html = html + '</table></form>';

		panel.setBody(html);		

	}

	

	function checkModeforSave(mode, form) {

		if (mode == "normalMode")

			return true;

		else {

			startAddPerson(form, role);

			return false;

		}

	}

														

	function startAddPerson(form, addTo) {

		panel.setHeader("Add Person");

    firstname = form.firstname.value;

		lastname = form.lastname.value;

		url = "ajax/addPerson.php?dogId="+dog_id+"&firstname="+escape(form.firstname.value)+"&lastname="+escape(form.lastname.value)+"&kennel="+escape(form.kennel.value)+"&street="+escape(form.street.value)+"&postalcode="+escape(form.postalcode.value)+"&city="+escape(form.city.value)+"&country="+escape(form.country.value)+"&email="+escape(form.email.value)+"&phone="+escape(form.phone.value)+"&homepage="+escape(form.homepage.value)+"&addTo="+addTo+"&rand="+new Date().getTime();

		if (window.XMLHttpRequest) { // Non-IE browsers

			req = new XMLHttpRequest();

			req.onreadystatechange = processAddPerson;

			try {

				req.open("GET", url, true);

				document.body.style.cursor="wait";

			} catch (e) {

				alert(e);

			}

			req.send(null);

		} else if (window.ActiveXObject) { // IE

			req = new ActiveXObject("Microsoft.XMLHTTP");

			if (req) {

				req.onreadystatechange = processAddPerson;

				req.open("GET", url, true);

				req.send();

				document.body.style.cursor="wait";

			}

		}	

	}



  function processAddPerson() {

	if (req.readyState == 4) { // Complete

    	document.body.style.cursor="auto";

      if (req.status == 200) { // OK response
			
				persId = req.responseText;

				panel.setBody("");

				panel.hide();

				// create according entry in Form, if it does not yet exist

				p_el = document.getElementById(role);

				//if not on "update-dog"-page,i.e. no "role" found, reload current webpage

				if (p_el == null) {

					location.reload();

				} else {

					if  ((persId != null) && (document.getElementById(role+persId)==null)) {

						span_el = document.createElement("span");

						span_el.setAttribute("id", role+persId);

						span_el.style.whitespace="nowrap";

						html = firstname + " " + lastname + "<a href='#' onclick='setDeleteTextOnPersonPanel("+persId+",\""+role+"\");panel.show();'><img src='images/drop.gif' alt=''></a><br>";

						span_el.innerHTML = html;

						p_el.appendChild(span_el);		

					}

				}

  	  } else {

        alert("Problem: " + req.statusText);      

			}

    }

  } 





	function setDeleteTextOnPersonPanel(person_id, rolename) {

		personId = person_id;

		role=rolename;

		html = '<p> Are you sure you want to remove this person as '+ role +' for this dog?</p>'

		html = html + '<input type="button" class="button" name="action" value=" OK " onclick="startDeletePerson('+personId+',\''+role+'\')" />'

		panel.setHeader("Remove this person as "+role);

		panel.setBody(html);

	}



  function startDeletePerson(personId,From) {

		url = "ajax/removePersonFrom.php?dogId="+dog_id+"&personId=" + escape(personId) + "&From="+From+"&rand="+new Date().getTime();

		if (window.XMLHttpRequest) { // Non-IE browsers

			req = new XMLHttpRequest();

			req.onreadystatechange = processDeletePerson;

			try {

				req.open("GET", url, true);

				document.body.style.cursor="wait";

			} catch (e) {

				alert(e);

			}

			req.send(null);

		} else if (window.ActiveXObject) { // IE

			req = new ActiveXObject("Microsoft.XMLHTTP");

			if (req) {

				req.onreadystatechange = processDeletePerson;

				req.open("GET", url, true);

				req.send();

				document.body.style.cursor="wait";

			}

		}

  }



  function processDeletePerson() {

    if (req.readyState == 4) { // Complete

    	document.body.style.cursor="auto";

      if (req.status == 200) { // OK response

				panel.setBody("");

				panel.hide();

				//  according entry from Form

				el = document.getElementById(role+personId);

				p_el = el.parentNode;

				p_el.removeChild(el);

			} else {

        alert("Problem: " + req.statusText);      

			}

    }

  }


  function startEditPerson(personId) {

		panel.setHeader("Edit Person");

		// add changing parameter-value (I added the current time!), as IE caches page, if same url !!!!
		url = "ajax/editPerson.php?personId=" + escape(personId) + "&rand="+new Date().getTime();

		if (window.XMLHttpRequest) { // Non-IE browsers

			req = new XMLHttpRequest();

			req.onreadystatechange = processEditPerson;

			try {

				req.open("GET", url, true);

				document.body.style.cursor="wait";

			} catch (e) {

				alert(e);

			}

			req.send(null);

		} else if (window.ActiveXObject) { // IE

			req = new ActiveXObject("Microsoft.XMLHTTP");

			if (req) {

				req.onreadystatechange = processEditPerson;

				req.open("GET", url, true);

				req.send(null);

				//document.body.style.cursor="wait";

			}

		}

  }



  function processEditPerson() {

    if (req.readyState == 4) { // Complete

    	document.body.style.cursor="auto";

      if (req.status == 200) { // OK response

		    var attrArray = req.responseText.split('%');

				var html = '<form id="editForm" method="POST" action="managePerson.php" ><input type="hidden" name="personId" value="' + attrArray[0] + '"/>';

				html = html + '<table>';

		    html = html + '<tr><td><label>Firstname: </label></td><td><input name="firstname" value="' + attrArray[1] + '" ></td></tr>';

		    html = html + '<tr><td><label>Lastname: </label></td><td><input name="lastname" value="' + attrArray[2] + '" ></td></tr>';
        
        html = html + '<tr><td><label>Kennel: </label></td><td><input name="kennel" value="' + attrArray[3] + '" ></td></tr>';
		    
        html = html + '<tr><td><label>Street: </label></td><td><input name="street" value="' + attrArray[4] + '" ></td></tr>';

		    html = html + '<tr><td><label>Postal Code: </label></td><td><input name="postalcode" value="' + attrArray[5] + '" ></td></tr>';

		    html = html + '<tr><td><label>City: </label></td><td><input name="city" value="' + attrArray[6] + '" ></td></tr>';

		    html = html + '<tr><td><label>Country: </label></td><td>'+getCountrySelectBox(attrArray[7])+'</td></tr>';

		    html = html + '<tr><td><label>Email: </label></td><td><input name="email" value="' + attrArray[8] + '" ></td></tr>';

		    html = html + '<tr><td><label>Phone: </label></td><td><input name="phone" value="' + attrArray[9] + '" ></td></tr>';

		    html = html + '<tr><td><label>Homepage: </label></td><td><input name="homepage" value="' + attrArray[10] + '" ></td></tr>';

			if (mode=="normalMode") {

				if (attrArray[11] == "1")

					radiobtncode = '<input type="radio" class="radio" name="breeder" value="1" checked="checked"><label>yes</label>' + '<input type="radio" class="radio" name="breeder" value="0" ><label>no</label>';

				else

					radiobtncode = '<input type="radio" class="radio" name="breeder" value="1" ><label>yes</label>' + '<input type="radio" class="radio" name="breeder" value="0" checked="checked"><label>no</label>';

				html = html + '<tr><td><label>Is Breeder? </label></td><td>'+radiobtncode+'</td></tr>';

			}

			html = html + '<tr><td>&nbsp;</td></tr>';

				html = html + '<tr><td colspan="2" align="center"><input name="action" type="submit" class="button" value="Save" onclick="javascript: return checkModeforUpdate(\''+mode+'\',document.getElementById(\'editForm\'));"/></td></tr>';

				html = html + '</table></form>';

				panel.setBody(html);				

      } else {

        alert("Problem: " + req.statusText);      

			}

    }

  }

	

	function checkModeforUpdate(mode, form) {

		if (mode == "normalMode")

			return true;

		else {

			startUpdatePerson(form,role);

			return false;

		}

	}


	function startUpdatePerson(form, addTo) {

		panel.setHeader("Add Person");

    	firstname = form.firstname.value;

		lastname = form.lastname.value;

		url = "ajax/updatePerson.php?dogId="+dog_id + "&personId="+escape(form.personId.value)+"&firstname="+escape(form.firstname.value)+"&lastname="+escape(form.lastname.value)+"&kennel="+escape(form.kennel.value)+"&street="+escape(form.street.value)+"&postalcode="+escape(form.postalcode.value)+"&city="+escape(form.city.value)+"&country="+escape(form.country.value)+"&email="+escape(form.email.value)+"&phone="+escape(form.phone.value)+"&homepage="+escape(form.homepage.value)+"&addTo="+addTo+"&rand="+new Date().getTime();

		if (window.XMLHttpRequest) { // Non-IE browsers

			req = new XMLHttpRequest();

			req.onreadystatechange = processAddPerson;

			try {

				req.open("GET", url, true);

				document.body.style.cursor="wait";

			} catch (e) {

				alert(e);

			}

			req.send(null);

		} else if (window.ActiveXObject) { // IE

			req = new ActiveXObject("Microsoft.XMLHTTP");

			if (req) {

				req.onreadystatechange = processAddPerson;

				req.open("GET", url, true);

				req.send();

				document.body.style.cursor="wait";

			}

		}	

	}


	function clickedClone() {
		simpleDialog = new YAHOO.widget.SimpleDialog("dlg", { 
		width:"400px",  
		fixedcenter: true,  
		constraintoviewport: true,  
		underlay:"shadow", 
		close:true,  
		visible:false,  
		draggable:true,
		modal:true,
		effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.30}
		} ); 
		simpleDialog.setHeader("Clone Dog ?"); 
		simpleDialog.setBody("You pressed the 'Clone'-button. Are you sure you want to make a copy of this dog?"); 
		simpleDialog.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_WARN); 
		var handleYes = function() { 
			checkEmptyDamSireField();
			var actionBtn = document.createElement("input");						
			actionBtn.setAttribute('name','action');
			actionBtn.setAttribute('value','Clone');				
			updateForm.appendChild(actionBtn);
			updateForm.submit()
			this.hide();
		} 
		var handleNo = function() { 
			this.hide(); 
		}
		var myButtons = [ { text:"Yes",  handler:handleYes }, { text:"Cancel", handler:handleNo, isDefault:true } ]; 
		simpleDialog.cfg.queueProperty("buttons", myButtons); 
		simpleDialog.render(document.body);
		simpleDialog.show();	
	}
	

	function showDeleteDialog(deleteWhat, id) {

		mySimpleDialog = new YAHOO.widget.SimpleDialog("dlg", { 

	    width:"400px",  

	    fixedcenter: true,  

	    constraintoviewport: true,  

	    underlay:"shadow", 

	    close:true,  

	    visible:false,  

	    draggable:true,

			modal:true,

			effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.30}

			} ); 

		mySimpleDialog.setHeader("Delete Dialog"); 

		mySimpleDialog.setBody("Are you sure you want to remove this "+deleteWhat+" from the archive?"); 

		mySimpleDialog.cfg.setProperty("icon",YAHOO.widget.SimpleDialog.ICON_WARN); 

		var handleYes = function() { 

			if (deleteWhat == "person")

				window.location.href="managePerson.php?action=Delete&personId="+id;

			else

				window.location.href="manage.php?action=Delete&id="+id;

			this.hide();

		} 

		var handleNo = function() { 

			this.hide(); 

		}

		var myButtons = [ { text:"Yes",  handler:handleYes }, { text:"Cancel", handler:handleNo, isDefault:true } ]; 

		mySimpleDialog.cfg.queueProperty("buttons", myButtons); 

		mySimpleDialog.render(document.body);

		mySimpleDialog.show();

	}

function setCountrySelectBox(html) {
	countrySelectHtml = html;
}

function getCountrySelectBox(selCountry) {
	if (selCountry !=null) {
		oldVal = "value='"+selCountry+"'";
		newVal = "value='"+selCountry+"' selected='selected' ";
		countrySelectHtml = countrySelectHtml.replace(oldVal,newVal);
	}	
	return countrySelectHtml;
}	
	
										
