<!-- o -->		
function noenter() {
  return !(window.event && window.event.keyCode == 13); }
function bar(evt){
var k=evt.keyCode||evt.which;
return k!=13;
}
 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>Нямате права за изтриване на "+objects+"!</b>";
		html+="<br> <div style='padding:10px'> Ако смятате, че записът не е коректен се свържете с администратора на адрес: (<b>"+adminwebaddress+"</b>)</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("Изтриването не е разрешено!"); 
		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=" + encodeURIComponent(phId)+ "&dogId=" + encodeURIComponent(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=" + encodeURIComponent(phId)+ "&text=" + encodeURIComponent(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=" + encodeURIComponent(phId)+ "&text=" + encodeURIComponent(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=" + encodeURIComponent(phId)+ "&text=" + encodeURIComponent(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> Сигурни ли сте, че искате да изтриете снимката? </p>'

		html = html + '<input type="button" class="button" name="action" value=" OK " onclick="startDeletePhoto('+photo_id+')" />'

		panel.setHeader("Изтрий снимката");
		
		panel.setBody(html);
		
		// if IE, scroll to top, because panel is opened there!
		if (document.all) 
			  window.scrollTo(100, 100);
	
	}


	function addPhoto() {

			panel.setHeader("Добави снимка");

			body = '<div class="content"><div align="left"><p>Изберете файл от вашият компютър:  <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="file" checked="checked" onclick="switchUrlOrFileDisplay()">Файл</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> Задай като заглавна снимка </label></td></tr>';
			body += '<tr><td width="80px"><label>Възраст:  </label></td><td><input type="text" name="notes" size="50"></td></tr>';
			body += '<tr><td width="80px"><label>Публикувал:  </label></td><td><input type="text" name="postedBy" size="50"></td></tr>';
			body += '<tr><td width="80px"><label><b>©  </b></label></td><td><input type="text" name="copyright" size="50"></td></tr>';
						
			// copyright
			body += '<tr><td colspan="2"><hr></td><tr>';
			body += "<tr><td colspan='2'><label style='color:red'>Обърнете внимание, че всички снимки ще са видими на публичен домейн. Моля не качвайте авторски защитени снимки.</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>Потвърждавам, че снимката не е обект на авторско право от трети лица.</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="Потвърди" disabled="disabled"></td>';
			body += '</tr></table>';
			body += '</form></div>';
			panel.setBody(body);

	}

	function startCheckRegNr(regNr) {
		if (regNr != null) {			
			url = "ajax/checkRegNr.php?regNr=" + encodeURIComponent(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='+ encodeURIComponent(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("THEDOGWN3"); 
						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=" + encodeURIComponent(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=" + encodeURIComponent(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();">Изтрий</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>Име:  </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=" + encodeURIComponent(parentName) + "&parentSex=" + encodeURIComponent(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("Добави Развъдник/Стопанин");
	if (role=="owner") {
			body = '<div class="content"><div align="left"><p>Моля въведете името на стопанина: <br></p></div><form name="nameForm"> <table border="0"><tr><td ><strong>Име:  </strong></td> <td><input style="width:180px" name="firstname" value="" onkeypress="return bar(event)"><input type="hidden" name="lastname" value="" onkeypress="return bar(event)"></td> </tr><tr> <td>&nbsp;</td><td align="right"><input type="button" class="button" name="action" value="Потвърди" onclick="startPersonSearch(nameForm.firstname.value, nameForm.lastname.value)"  /></td> </tr> </table> </form> </div>';
			}
	else {
			body = '<div class="content"><div align="left"><p>Моля въведете името на развъдника: <br></p></div><form name="nameForm"> <table border="0"><tr><td ><strong>Собственик:  </strong></td> <td><input style="width:180px" name="firstname" value=""></td> </tr> <tr> <td ><strong>Развъдник: </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="Потвърди" onclick="startPersonSearch(nameForm.firstname.value, nameForm.lastname.value)" /></td> </tr> </table> </form> </div>';
			}
			panel.setBody(body);

		}

	}

 

  function startPersonSearch(fname, lname) {

    firstname = fname;

		lastname = lname;



      url = "ajax/searchPerson.php?firstname=" + encodeURIComponent(firstname) + "&lastname=" + encodeURIComponent(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>Не беше намерен запис в базата данни.</p><a href="#" onclick="setAddPersonTextOnPersonPanel();">Към добавяне на нов запис</a>';

				} else {

					html = html + '<div style="padding:10px"><p>Моля изберете един от намерените записи.</p></div>';
					html = html + '<div style="width:390px;height:150px;overflow:auto">';
					html = html + '<table border="0" cellpadding="10px"><tr><td valign="top"><strong>Намерени записи:  </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>Моля проверете всички записи по-горе. \'' + firstname + ' ' + lastname + '\' не е сред изброените.</b></p>';

					html = html + '<p><input type="radio" class="radio" name="selectedPerson" value="new" onclick="getElementById(\'ok_btn\').removeAttribute(\'disabled\');" \><label>Проверих записите \'' + firstname + ' ' + lastname + '\' не е сред изброените.</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";
			startEditPersonzz(selPerson);
		}
	}

	

	function setAddPersonTextOnPersonPanel() {

		var html = '<form id="addForm" method="POST" action="managePerson.php" >';

		html = html + '<table>';

		html = html + '<tr><td><label>Име:  </label></td><td><input name="firstname" value="'+firstname+'" ></td></tr>';

		html = html + '<tr><td><label>Развъдник: </label></td><td><input name="lastname" value="'+lastname+'"></td></tr>';

		html = html + '<tr><td><label>Улица: </label></td><td><input name="street" value="" ></td></tr>';

		html = html + '<tr><td><label>Пощенски код: </label></td><td><input name="postalcode" value="" ></td></tr>';

		html = html + '<tr><td><label>Град: </label></td><td><input name="city" value="" ></td></tr>';

		html = html + '<tr><td><label>Държава: </label></td><td>'+getCountrySelectBox("")+'</td></tr>';

		html = html + '<tr><td><label>E-mail:  </label></td><td><input name="email" value="" ></td></tr>';

		html = html + '<tr><td><label>Телефон: </label></td><td><input name="phone" value="" ></td></tr>';

		html = html + '<tr><td><label>Уеб Сайт:  </label></td><td><input name="homepage" value="" ></td></tr>';

		if (mode=="normalMode") {

			radiobtncode = '<input type="radio" class="radio" name="breeder" value="1" ><label>Да</label>' + '<input type="radio" class="radio" name="breeder" value="0" checked="checked"><label>Не</label>';

			html = html + '<tr><td><label>Развъдчик ли е?  </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("Добави Развъдник/Стопанин");

		firstname = form.firstname.value;

		lastname = form.lastname.value;

		url = "ajax/addPerson.php?dogId="+dog_id+"&firstname="+encodeURIComponent(form.firstname.value)+"&lastname="+encodeURIComponent(form.lastname.value)+"&street="+encodeURIComponent(form.street.value)+"&postalcode="+encodeURIComponent(form.postalcode.value)+"&city="+encodeURIComponent(form.city.value)+"&country="+encodeURIComponent(form.country.value)+"&email="+encodeURIComponent(form.email.value)+"&phone="+encodeURIComponent(form.phone.value)+"&homepage="+encodeURIComponent(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> Сигурни ли сте, че искате да изтриете  '+ role +' за това куче?</p>'

		html = html + '<input type="button" class="button" name="action" value=" OK " onclick="startDeletePerson('+personId+',\''+role+'\')" />'

		panel.setHeader("Изтрийте записът на "+role);

		panel.setBody(html);

	}



  function startDeletePerson(personId,From) {

		url = "ajax/removePersonFrom.php?dogId="+dog_id+"&personId=" + encodeURIComponent(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=" + encodeURIComponent(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 startEditPersonzz(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=" + encodeURIComponent(personId) + "&rand="+new Date().getTime();

		if (window.XMLHttpRequest) { // Non-IE browsers

			req = new XMLHttpRequest();

			req.onreadystatechange = processEditPersonzz;

			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 = processEditPersonzz;

				req.open("GET", url, true);

				req.send(null);

				//document.body.style.cursor="wait";

			}

		}

  }

    function processEditPersonzz() {
	

    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>Име:  </label></td><td><input name="firstname" value="' + attrArray[1] + '" READONLY></td></tr>';

		    html = html + '<tr><td><label>Развъдник: </label></td><td><input name="lastname" value="' + attrArray[2] + '" READONLY></td></tr>';

		    html = html + '<tr><td><label>Улица: </label></td><td><input name="street" value="' + attrArray[3] + '" READONLY></td></tr>';

		    html = html + '<tr><td><label>Пощенски код: </label></td><td><input name="postalcode" value="' + attrArray[4] + '" READONLY></td></tr>';

		    html = html + '<tr><td><label>Град: </label></td><td><input name="city" value="' + attrArray[5] + '" READONLY></td></tr>';

		    html = html + '<tr><td><label>Държава: </label></td><td><option>'+getCountrySelectBox(attrArray[6])+'</option disabled="disabled"></td></tr>';

		    html = html + '<tr><td><label>E-mail:  </label></td><td><input name="email" value="' + attrArray[7] + '" READONLY></td></tr>';

		    html = html + '<tr><td><label>Телефон: </label></td><td><input name="phone" value="' + attrArray[8] + '" READONLY></td></tr>';

		    html = html + '<tr><td><label>Уеб Сайт:  </label></td><td><input name="homepage" value="' + attrArray[9] + '" READONLY></td></tr>';

			if (mode=="normalMode") {

				if (attrArray[10] == "1")

					radiobtncode = '<input type="radio" class="radio" name="breeder" value="1" checked="checked"><label>Да</label>' + '<input type="radio" class="radio" name="breeder" value="0" ><label>Не</label>';

				else

					radiobtncode = '<input type="radio" class="radio" name="breeder" value="1" ><label>Да</label>' + '<input type="radio" class="radio" name="breeder" value="0" checked="checked"><label>Не</label>';

				html = html + '<tr><td><label>Развъдчик ли е?  </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 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>Име:  </label></td><td><input name="firstname" value="' + attrArray[1] + '" ></td></tr>';

		    html = html + '<tr><td><label>Развъдник: </label></td><td><input name="lastname" value="' + attrArray[2] + '" ></td></tr>';

		    html = html + '<tr><td><label>Улица: </label></td><td><input name="street" value="' + attrArray[3] + '" ></td></tr>';

		    html = html + '<tr><td><label>Пощенски код: </label></td><td><input name="postalcode" value="' + attrArray[4] + '" ></td></tr>';

		    html = html + '<tr><td><label>Град: </label></td><td><input name="city" value="' + attrArray[5] + '" ></td></tr>';

		    html = html + '<tr><td><label>Държава: </label></td><td>'+getCountrySelectBox(attrArray[6])+'</td></tr>';

		    html = html + '<tr><td><label>E-mail:  </label></td><td><input name="email" value="' + attrArray[7] + '" ></td></tr>';

		    html = html + '<tr><td><label>Телефон: </label></td><td><input name="phone" value="' + attrArray[8] + '" ></td></tr>';

		    html = html + '<tr><td><label>Уеб Сайт:  </label></td><td><input name="homepage" value="' + attrArray[9] + '" ></td></tr>';

			if (mode=="normalMode") {

				if (attrArray[10] == "1")

					radiobtncode = '<input type="radio" class="radio" name="breeder" value="1" checked="checked"><label>Да</label>' + '<input type="radio" class="radio" name="breeder" value="0" ><label>Не</label>';

				else

					radiobtncode = '<input type="radio" class="radio" name="breeder" value="1" ><label>Да</label>' + '<input type="radio" class="radio" name="breeder" value="0" checked="checked"><label>Не</label>';

				html = html + '<tr><td><label>Развъдчик ли е?  </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("Добави Развъдник/Стопанин");

    	firstname = form.firstname.value;

		lastname = form.lastname.value;

		url = "ajax/updatePerson.php?dogId="+dog_id + "&personId="+encodeURIComponent(form.personId.value)+"&firstname="+encodeURIComponent(form.firstname.value)+"&lastname="+encodeURIComponent(form.lastname.value)+"&street="+encodeURIComponent(form.street.value)+"&postalcode="+encodeURIComponent(form.postalcode.value)+"&city="+encodeURIComponent(form.city.value)+"&country="+encodeURIComponent(form.country.value)+"&email="+encodeURIComponent(form.email.value)+"&phone="+encodeURIComponent(form.phone.value)+"&homepage="+encodeURIComponent(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 updateForbiddenDialog(adminwebaddress, objects) {
		html = "<b>Нямате права за редактиране на "+objects+"!</b>";
		html+="<br> <div style='padding:10px'>Ако смятате, че записът не е коректен се свържете с администратора на адрес:  (<b>"+adminwebaddress+"</b>) </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("Редактирането не е разрешено!"); 
		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 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;
}	
	
										
