
var originalExperienceItem = null;
var originalEducationItem = null;
var originalImageItem = null;
var currentYear = 0;
var firstDay = true;
var firstYear = true;

function saveOriginalItems() {
	var cvObject = document.getElementById('cvObject');
	var babyObject = document.getElementById('babyObject');
	originalExperienceItem = document.getElementById('lastExp').cloneNode(true);
	originalEducationItem = document.getElementById('lastEdu').cloneNode(true);
	originalAchievementItem = document.getElementById('lastAch').cloneNode(true);
	originalImageItem = document.getElementById('lastImg').cloneNode(true);
}

function saveOriginalItems2() {
	var babyObject = document.getElementById('babyObject');
	originalImageItem = document.getElementById('lastImg').cloneNode(true);
}


function putCurrentYear(year) {
	currentYear = year;
}

function printAttributes(object) {
	var a = '';
	for (var i = 0; i < object.attributes.length; i++)
		a += object.attributes[i].name + ', ';
		
	alert(a);
}

function addAnotherExperience() {
	var cvObject = document.getElementById('cvObject');
	
	var beforeNode = document.getElementById('insertExpHere');
	var newNode = originalExperienceItem.cloneNode(true);
	
	cvObject.tBodies[0].insertBefore(newNode, beforeNode);
}

function addAnotherImage() {
	alert('go');
	var babyObject = document.getElementById('babyObject');
	
	var beforeNode = document.getElementById('insertImgHere');
	var newNode = originalImageItem.cloneNode(true);
	
	babyObject.tBodies[0].insertBefore(newNode, beforeNode);
}

function addAnotherEducation() {
	var cvObject = document.getElementById('cvObject');
	
	var beforeNode = document.getElementById('insertEduHere');
	var newNode = originalEducationItem.cloneNode(true);
	
	cvObject.tBodies[0].insertBefore(newNode, beforeNode);
}


function addAnotherAchievement() {
	var cvObject = document.getElementById('cvObject');
	
	var beforeNode = document.getElementById('insertAchHere');
	var newNode = originalAchievementItem.cloneNode(true);
	
	cvObject.tBodies[0].insertBefore(newNode, beforeNode);
}


function removePosition(obj, id, type) {
	// the object to be removed
	var removable = obj.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
	// main table tbody object
	var rootTable = removable.parentNode;
	
	if (confirm('Are you sure you want to remove this entry?\nThis will erase its content!')) {
		// insert a hidden input to mark this id with deleted (for controller action)
		if (id) {
			var idElement = document.createElement('input');
			idElement.type = 'hidden';
			if (type == 'exp')
				idElement.name = 'deletedExpItems[]';
			else 
				idElement.name = 'deletedEduItems[]';
			idElement.value = ''+id;
			cvObject.appendChild(idElement);
		}		
		// remove the row from table tbody
		rootTable.removeChild(removable);
	}
}

// check if a string represents a number (float)
function IsNumeric(sText, floatNo){
   var ValidChars = "0123456789";
   if (floatNo)
   		ValidChars += ".";
   var IsNumber=true;
   var Char;

   for (i = 0; i < sText.length && IsNumber == true; i++) { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) {
	         IsNumber = false;
      }
   }

   return IsNumber;
}


function checkRequiredFieldsCV() {
	var name = document.getElementById('cv_name');
	var city = document.getElementById('cv_city');
	var title = document.getElementById('cv_title');
/*	var month = document.getElementById('cv_month');
	var day = document.getElementById('cv_day');
	var year = document.getElementById('cv_year'); */ // serj comment. field no longer required
	
	var ok = true;
	
	if (!name.value.length) {
		alert('You have to complete the required fields first! No name given!');
		return false;
	}

	if (!city.value.length) {
		alert('You have to complete the required fields first! No city of residence given!');
		return false;
	}

	if (!title.value.length) {
		alert('You have to complete the required fields first! No title given!');
		return false;
	}
	
/*	if (month.options[month.selectedIndex].value == '0') {
		alert('You have to complete the required fields first! Choose your birth month!');
		return false;
	}

	if (!day.value.length || !IsNumeric(day.value, false) ||
		day.value > 31) {
		alert('You have to complete the required fields first! Invalid day!');
		return false;
	}
	
	if (!year.value.length || !IsNumeric(year.value, false) ||
		currentYear - year.value > 100 || year.value >= currentYear) {
		alert('Invalid birth year! Please choose a valid year.');
		return false;
	}  */ // serj comment. field no longer required
	
	return ok;
}


function checkRequiredFieldsClassified() {

	var countryId   = document.getElementById('classified_country_id');
	var country 	= parseInt(countryId.options[countryId.selectedIndex].value);
	var categoryId  = document.getElementById('classified_classifiedcategory_id');
	var category    = parseInt(categoryId.options[categoryId.selectedIndex].value);
	var title     = document.getElementById('classified_title');
	var price     = document.getElementById('classified_price');
	var currencyId  = document.getElementById('classified_currency_id');	
	var currency    = parseInt(currencyId.options[currencyId.selectedIndex].value);
		
	
	var ok = true;
	
	if (country == 0) {
		alert('You have to complete the required fields first! Choose a country!');
		return false;
	}
	
	if (category == 0) {
		alert('You have to complete the required fields first! Choose a category!');
		return false;
	}
			
	if (!title.value.length) {
		alert('You have to complete the required fields first! No title given!');
		return false;
	}

	if ((price.value <= 0) || !IsNumeric(price.value, false)){
		alert('You have to complete the required fields first! Give price a positive numeric value!');
		return false;
	}

	if (currency == 0) {
		alert('You have to complete the required fields first! No currency given!');
		return false;
	}
		
	return ok;
}

function checkRequiredFieldsBaby() {
	
	var babyName 	    = document.getElementById('name');
	var babyLocation    = document.getElementById('location');
	var monthId    = document.getElementById('cvmonth');
	var dayId      = document.getElementById('cvday');
	var yearId     = document.getElementById('cvyear');	
	var birthdate_month = parseInt(monthId.options[monthId.selectedIndex].value);
	var birthdate_day   = parseInt(dayId.options[dayId.selectedIndex].value);
	var birthdate_year  = parseInt(yearId.options[yearId.selectedIndex].value);
	var parents         = document.getElementById('parents');
	
	var ok = true;
	
	if (!babyName.value.length) {
		alert('You have to complete the required fields first! No name given!');
		return false;
	}
	
	if (!babyLocation.value.length) {
		alert('You have to complete the required fields first! No location given!');
		return false;
	}
			
	if (birthdate_month == 0) {
		alert('You have to complete the required fields first! Choose a month!');
		return false;
	}
		
	if (birthdate_day == 0) {
		alert('You have to complete the required fields first! Choose a day!');
		return false;
	}
	
	if (birthdate_year == 0) {
		alert('You have to complete the required fields first! Choose a year!');
		return false;
	}
				
	if (!parents.value.length) {
		alert('You have to complete the required fields first! No parents given!');
		return false;
	}
	
			
/*	if (month.options[month.selectedIndex].value == '0') {
		alert('You have to complete the required fields first! Choose your birth month!');
		return false;
	}

	if (!day.value.length || !IsNumeric(day.value, false) ||
		day.value > 31) {
		alert('You have to complete the required fields first! Invalid day!');
		return false;
	}
	
	if (!year.value.length || !IsNumeric(year.value, false) ||
		currentYear - year.value > 100 || year.value >= currentYear) {
		alert('Invalid birth year! Please choose a valid year.');
		return false;
	}  
*/

	
	return ok;
}

function checkSelectedTypesAdmin() {
	var check_page = document.getElementById('page_check');
	var check_cv = document.getElementById('cv_check');
	var check_classified = document.getElementById('classified_check');
	var check_baby = document.getElementById('baby_check');
	
	if (!check_page.checked && !check_cv.checked && !check_classified.checked && !check_baby.checked) {
		alert('You should select at least one user type!');
		return false;
	}
	
	return true;
}

function changeLayout(module,layoutId){
	editPageForm = document.getElementById('edit_page');
	editPageForm.action ='./common/'+module+'-controller.php?action=page.changeLayoutExe&layout='+layoutId;
	editPageForm.submit();
}

/** adds an event handler to an event listener **/
function addEvent(obj, evType, fn){ 
 if (obj.addEventListener){ 
   obj.addEventListener(evType, fn, false); 
   return true; 
 } else if (obj.attachEvent){ 
   var r = obj.attachEvent("on"+evType, fn); 
   return r; 
 } else { 
   return false; 
 } 
}


function openNewWindow(URL,title){
	window.open(URL,title,'location=no,menubar=no,toolbar=no,resizable=no,scrollbars=yes,width=800,height=600');
}

function confirmDelete(){
	var deleteCheckbox = document.getElementById('deleteCheckbox') ;
	
	if(deleteCheckbox.checked){
		return confirm("Are you really sure you want to delete your page?");
	}else {
		return true;
	}
}

function resizeWindow()
{
	if (self.innerWidth)
	{
		frameWidth = self.innerWidth;
		frameHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
		frameWidth = document.documentElement.clientWidth;
		frameHeight = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
		frameWidth = document.body.clientWidth;
		frameHeight = document.body.clientHeight;
	}
	else return;

	if (frameWidth < 1024 || frameHeight < 580)
	{
//		alert(window.screen.availWidth)
//		alert(window.screen.availHeight)
		window.resizeTo(window.screen.availWidth,window.screen.availHeight);
	}
	else
	{
		return;
	}
}


//check the validity of an email address
function emailCheck(emailStr) {

/* The following variable tells the rest of the function whether or not
to verify that the address ends in a two-letter country or well-known
TLD.  1 means check it, 0 means don't. */

var checkTLD=1;

/* The following is the list of known TLDs that an e-mail address must end with. */

var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

/* The following pattern is used to check if the entered e-mail address
fits the user@domain format.  It also is used to separate the username
from the domain. */

var emailPat=/^(.+)@(.+)$/;

/* The following string represents the pattern for matching all special
characters.  We don't want to allow special characters in the address. 
These characters include ( ) < > @ , ; : \ " . [ ] */

var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

/* The following string represents the range of characters allowed in a 
username or domainname.  It really states which chars aren't allowed.*/

var validChars="\[^\\s" + specialChars + "\]";

/* The following pattern applies if the "user" is a quoted string (in
which case, there are no rules about which characters are allowed
and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
is a legal e-mail address. */

var quotedUser="(\"[^\"]*\")";

/* The following pattern applies for domains that are IP addresses,
rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
e-mail address. NOTE: The square brackets are required. */

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

/* The following string represents an atom (basically a series of non-special characters.) */

var atom=validChars + '+';

/* The following string represents one word in the typical username.
For example, in john.doe@somewhere.com, john and doe are words.
Basically, a word is either an atom or quoted string. */

var word="(" + atom + "|" + quotedUser + ")";

// The following pattern describes the structure of the user

var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

/* The following pattern describes the structure of a normal symbolic
domain, as opposed to ipDomainPat, shown above. */

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

/* Finally, let's start trying to figure out if the supplied address is valid. */

/* Begin with the coarse pattern to simply break up user@domain into
different pieces that are easy to analyze. */

var matchArray=emailStr.match(emailPat);

	if (matchArray==null) {
	/* Too many/few @'s or something; basically, this address doesn't
	even fit the general mould of a valid e-mail address. */
	alert("Email address seems incorrect (check @ and .'s)");
	return false;
	}

var user=matchArray[1];
var domain=matchArray[2];
	
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {
		
		if (user.charCodeAt(i)>127) {
			
		alert("Ths username contains invalid characters.");
		
		return false;
	   }
	}
	
	for (i=0; i<domain.length; i++) {
		
		if (domain.charCodeAt(i)>127) {
			
		alert("Ths domain name contains invalid characters.");
		
		return false;
	   }
	}
	
	// See if "user" is valid 
	
	if (user.match(userPat)==null) {
	// user is not valid
	
	alert("The username doesn't seem to be valid.");
	
	return false;
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	
var IPArray=domain.match(ipDomainPat);

	if (IPArray!=null) {
		
	// this is an IP address
		for (var i=1;i<=4;i++) {

			if (IPArray[i]>255) {
				
				alert("Destination IP address is invalid!");
				
				return false;
		   }
		}
	return true;
	}
	
	// Domain is symbolic name.  Check if it's valid.
	 
var atomPat=new RegExp("^" + atom + "$");
var domArr=domain.split(".");
var len=domArr.length;

	for (i=0;i<len;i++) {
		
		if (domArr[i].search(atomPat)==-1) {
			
		alert("The domain name does not seem to be valid.");
		
		return false;
	   }
	}
	
/* domain name seems valid, but now make sure that it ends in a
known top-level domain (like com, edu, gov) or a two-letter word,
representing country (uk, nl), and that there's a hostname preceding 
the domain or country. */
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
			domArr[domArr.length-1].search(knownDomsPat)==-1) {
			
		alert("The address must end in a well-known domain or two letter " + "country.");
		
		return false;
	}
	
	// Make sure there's a host name preceding the domain.
	
	if (len<2) {
		
		alert("This address is missing a hostname!");
		
		return false;
	}

// If we've gotten this far, everything's valid!
return true;
}


	//check all checkboxes on a page
  function checkAll(){
  	var inputs = document.getElementsByTagName('input');
  	
  	for(var i = 0 ;i < inputs.length ; i++ ){
  		if(inputs[i].type == 'checkbox'){
  			inputs[i].checked=true;
  		}	
  	}
  }

	//uncheck all checkboxes on a page
  function unCheckAll(){
  	var inputs = document.getElementsByTagName('input');
  	
  	for(var i = 0 ;i < inputs.length ; i++ ){
  		if(inputs[i].type == 'checkbox'){
  			inputs[i].checked=false;
  		}	
  	}
  }
  

  
  //show email page form
  function showEmailPage(){
  	mainDiv 		= document.getElementById('emailPage');
  	secondaryDiv	= document.getElementById('reportAbuse');
  	
  	secondaryDiv.style.display = 'none';
  	mainDiv.style.display = 'block';
  }
  
  //show report abuse form
  function showReportAbuse(){
  	mainDiv 		= document.getElementById('reportAbuse');
  	secondaryDiv	= document.getElementById('emailPage');
  	
  	secondaryDiv.style.display = 'none';
  	mainDiv.style.display = 'block';
  }  
  
  //hide an object
  function hideObject(obj, email){
		obj.style.display = 'none';
  }
  
  
  function checkFieldValueEmailToFriend(email){
	if (email.value == ""){
		alert("Please complete email field!");
		return false;	
	}else if(!emailCheck(email.value)){
		//verify the validity of email
		// alert("The email address is not valid!");	//there is already a message returned by fct emailCheck()
		return false;		
	}else{
		alert("Sending email to the email address you specified!");	
		return true;
	}
  }  

  function checkFieldValueReportAbuse(reason, email){
	if ( (reason.value == "") && (email.value == "") ){
		alert("Please give a reason why this page is abusive AND complete your email address!");
		return false;	
	}else if (reason.value == ""){
		alert("Please give a reason why this page is abusive!");
		return false;	
	}else if (email.value == ""){
		alert("Please complete email field!");
		return false;	
	}else if(!emailCheck(email.value)){
		//verify the validity of email
		//alert("The email address is not valid!");	//there is already a message returned by fct emailCheck()
		return false;		
	}else{
		alert("Sending email to iTagz!");	
		return true;	
	}
  }  
  
  
  function checkEmailAdmin(email){
  	  if (email != ""){
			return  emailCheck(email);
	  }		
  }//fct checkEmailAdmin
  
  
  //validate days when month changes
  function changeMonthOrYear() {
  	  
  	  var monthId      = document.getElementById('cv_month');
  	  var yearId       = document.getElementById('cv_year');
  	  var dayId        = document.getElementById('cv_day');
  	  var currentMonth = parseInt(monthId.options[monthId.selectedIndex].value);
  	  var currentYear  = parseInt(yearId.options[yearId.selectedIndex].value); 
  	  var currentDay   = parseInt(dayId.selectedIndex);
  	  var days = 0;
  	  var optionElement;
  	  var i;
  	  var currentLength;
  	  
  	  //get the numers of days per month according to month and year
  	  switch(currentMonth) {
  	  	  	case 1:
  	  	  		days = 31;
  	  	  		break;
  	  	  	case 2:
  	  	  		if (isNaN(currentYear)) {
  	  	  			days = 28;
  	  	  		} else if (currentYear%4 == 0 ) {
  	  	  			days = 29;	
  	  	  		  } else {
  	  	  			days = 28;
  	  	  		  }
  	  	  		break;
  	  	  	case 3:
  	  	  		days = 31;
  	  	  		break;
  	  	  	case 4:
  	  	  		days = 30;
  	  	  		break;
  	  	  	case 5:
  	  	  		days = 31;
  	  	  		break;
  	  	  	case 6:
  	  	  		days = 30;
  	  	  		break;
  	  	  	case 7:
  	  	  		days = 31;
  	  	  		break;
  	  	  	case 8:
  	  	  		days = 31;
  	  	  		break;
  	  	  	case 9:
  	  	  		days = 30;
  	  	  		break;
  	  	  	case 10:
  	  	  		days = 31;
  	  	  		break;
  	  	  	case 11:
  	  	  		days = 30;
  	  	  		break;
  	  	  	case 12:
  	  	  		days = 31;
  	  	  		break;
  	  	  	default:
  	  	  		days = 30;
  	  	  		break;
  	  }
  	  
  	  //First clear all the options from the select
  	  currentLength = dayId.length;
  	  for(i=0;i<currentLength;i++) {
  	  	dayId.remove(0);
  	  }
  	
  	  //populate with the appropiat numbers of days according to month and year
  	  optionElement = document.createElement('option');
  	  optionElement.text  = "Day";
  	  optionElement.value = 0;
  	  try {
    	dayId.add(optionElement,null); // standards compliant
      }
  	  catch(ex) {
    	dayId.add(optionElement); // IE only
      }
 
  	  for (i=1;i<=days;i++) {
  	  	optionElement = document.createElement('option');
  	  	optionElement.text  = i;
  	  	optionElement.value = i;
  	  	
  	  	try {
    		dayId.add(optionElement,null); // standards compliant
    	}
  		catch(ex) {
    		dayId.add(optionElement); // IE only
    	}
  	  }
  	  
  	  if (currentDay<=days) {
  	  	dayId.selectedIndex = currentDay;
  	  } else {
  	  	dayId.selectedIndex = days;
  	  }
  }