
//BROWSER DETECTION
var ns4 = document.layers;
var ns6 = document.getElementById && !document.all;
var ie4 = document.all;
var msgPeriodicExecutor = null;     
 
function DetectBrowser(){ //Detectarea browserului folosit
	this.ver=navigator.appVersion
	this.agent=navigator.userAgent
	this.dom=document.getElementById?1:0
	this.opera5=(navigator.userAgent.indexOf("Opera")>-1 && document.getElementById)?1:0
	this.ie5=(this.ver.indexOf("MSIE 5")>-1 && this.dom && !this.opera5)?1:0; 
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom && !this.opera5)?1:0;
	this.ie4=(document.all && !this.dom && !this.opera5)?1:0;
	this.ie=this.ie4||this.ie5||this.ie6
	this.mac=this.agent.indexOf("Mac")>-1
	this.ns6=(this.dom && parseInt(this.ver) >= 5) ?1:0; 
	this.ns4=(document.layers && !this.dom)?1:0;
	this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns6 || this.opera5)
	return this
}
var bw=new DetectBrowser();

//FIELDS
function imgField(field, img){
	if(img == "over") {
		border_color 	= "#3574A1";
		border_style 	= "dashed";
		bgcolor 		= "#FEFFD6";
	}else {
		border_color 	= "#cccccc";
		border_style 	= "solid";
		bgcolor 		= "#FCFEB4";
	}
	//field.style.borderColor 	= border_color;
	field.style.borderStyle 	= border_style;
	field.style.backgroundColor = bgcolor;
}

function imgMandatoryField(field, img){
	if(img == "over") {
		border_color 	= "#3574A1";
		border_style 	= "dashed";
		bgcolor 		= "#FEFFD6";
	}else {
		border_color 	= "#cccccc";
		border_style 	= "solid";
		bgcolor 		= "#FCFEB4";
	}
	//field.style.borderColor 	= border_color;
	field.style.borderStyle 	= border_style;
	field.style.backgroundColor = bgcolor;
}


function imgNameMandatoryField(field, img){
	if(img == "over") {
		border_color 	= "#3574A1";
		border_style 	= "dashed";
		bgcolor 		= "#FEFFD6";
	}else {
		border_color 	= "#cccccc";
		border_style 	= "solid";
		bgcolor 		= "#F9FB9A";
	}
	//field.style.borderColor 	= border_color;
	field.style.borderStyle 	= border_style;
	field.style.backgroundColor = bgcolor;
}


//BUTS
function imgBut(but, img){
	but.src = img;
}



//Reset Form
function resetForm(formName){
	if(ns6) form = eval("document.getElementById('"+formName+"')");
	else if(ns4) form = eval("document."+formName);
	else form = eval("document.all."+formName);
	form.reset();
}



function focus2(field){
	if(field.value == 0) field.value = '';
}	


function blur2(field){
	if(field.value == '') field.value = '0';
}	


function fieldValue(field_name){
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	return field.value;
}

function setFieldValue(field_name, val){
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	return field.value;
	field.value = val;
}

function writeIn(field_name, val){
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	field.innerHTML = val;
}



function formatNR(nr, dec)
{
str = "" + Math.round(eval(nr) * Math.pow(10,dec));
while(str.length < dec)
	str = "0" + str;
decidx = str.length - dec;
tmp = str.substring(0,decidx);
if(tmp == '')
	tmp = '0';
if(dec > 0)
	tmp = tmp + '.' + str.substring(decidx, str.length);
return(tmp);
}



function getkey(e)
{
if (window.event)
   return window.event.keyCode;
else if (e)
   return e.which;
else
   return null;
}


function goodchars(e, goods)
{
var key, keychar;
key = getkey(e);
if (key == null) return true;

// get character
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
goods = goods.toLowerCase();

// check goodkeys
if (goods.indexOf(keychar) != -1)
	return true;

// control keys
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
   return true;

// else return false
return false;
}

function goodalphanumeric(e)
{
var key, keych;
key = getkey(e);

if (key == null) return true;
keych = String.fromCharCode(key);

if (('a' <= keych && 'z' >= keych) || ('A' <= keych && 'Z' >= keych) || ('0' <= keych && '9' >= keych)) return true;

// control keys
if ( key==null || key==0 || key==8 || key==9 || key==13 || key==27 )
   return true;

// else return false
return false;
}


function getSelectedRadio(buttonGroup) {
   // returns the array number of the selected radio button or -1 if no button is selected
   if (buttonGroup[0]) { // if the button group is an array (one button is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            return i
         }
      }
   } else {
      if (buttonGroup.checked) { return 0; } // if the one button is checked, return zero
   }
   // if we get to this point, no radio button is selected
   return -1;
} // Ends the "getSelectedRadio" function

function getSelectedRadioValue(buttonGroup) {
   // returns the value of the selected radio button or "" if no button is selected
   var i = getSelectedRadio(buttonGroup);
   if (i == -1) {
      return "";
   } else {
      if (buttonGroup[i]) { // Make sure the button group is an array (not just one button)
         return buttonGroup[i].value;
      } else { // The button group is just the one button, and it is checked
         return buttonGroup.value;
      }
   }
} // Ends the "getSelectedRadioValue" function

function getSelectedCheckbox(buttonGroup) {
   // Go through all the check boxes. return an array of all the ones
   // that are selected (their position numbers). if no boxes were checked,
   // returned array will be empty (length will be zero)
   var retArr = new Array();
   var lastElement = 0;
   if (buttonGroup[0]) { // if the button group is an array (one check box is not an array)
      for (var i=0; i<buttonGroup.length; i++) {
         if (buttonGroup[i].checked) {
            retArr.length = lastElement;
            retArr[lastElement] = i;
            lastElement++;
         }
      }
   } else { // There is only one check box (it's not an array)
      if (buttonGroup.checked) { // if the one check box is checked
         retArr.length = lastElement;
         retArr[lastElement] = 0; // return zero as the only array value
      }
   }
   return retArr;
} // Ends the "getSelectedCheckbox" function

function getSelectedCheckboxValue(buttonGroup) {
   // return an array of values selected in the check box group. if no boxes
   // were checked, returned array will be empty (length will be zero)
   var retArr = new Array(); // set up empty array for the return values
   var selectedItems = getSelectedCheckbox(buttonGroup);
   if (selectedItems.length != 0) { // if there was something selected
      retArr.length = selectedItems.length;
      for (var i=0; i<selectedItems.length; i++) {
         if (buttonGroup[selectedItems[i]]) { // Make sure it's an array
            retArr[i] = buttonGroup[selectedItems[i]].value;
         } else { // It's not an array (there's just one check box and it's selected)
            retArr[i] = buttonGroup.value;// return that value
         }
      }
   }
   return retArr;
} // Ends the "getSelectedCheckBoxValue" function
  

//Email Validation
function emailValid(email)
{
  var result = false
  var theStr = new String(email)
  var index = theStr.indexOf("@");
  if (index > 0)
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
	result = true;
  }
  return result;
}

function formSubmit(form, act){
	document.forms[form].action = act;
	document.forms[form].submit();
}





function fieldOb(field_name){
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	return field;
}

function changeRowColor(row, color){
	rOb = fieldOb(row);
	rOb.bgColor = color;  
}


//Validates a field
function ValidateField(elem, name){
	if((elem.value == ''))	{ // ||(elem.value == 0)
    		alert('Warning: Not all mandatory fields (*) have been filled!');
    		elem.focus();
   	 		return(false);
   	}
	else if(name.indexOf('email') != -1){
			 	if(!emailValid(elem.value)){
					alert('Invalid E-mail address !');
					elem.focus();
   	 				return(false);
				}
	}
	return(true);
}

//Just Validates a field without (alert & focus)
function JustValidateField(elem){
	if((elem.value == '')||(elem.value == 0))	return(false);
	else if(name.indexOf('email') != -1){
			 	if(!emailValid(elem.value)){
   	 				return(false);
				}
	}
	return(true);
}


//Validate form for Mandatory fields to be filled properly
function Validate(form, fields){
   	mandatory_fields = fields.split(',');
	for(i=0; i<mandatory_fields.length; i++){
		
		if(mandatory_fields[i].indexOf('|')){
			//groupped fields (at least one of them must be filled/selected)
			mandatory_group_fields = mandatory_fields[i].split('|');
			valid = 0;
			for(j=0; j<mandatory_group_fields.length; j++){
				elem = eval('form.' + mandatory_group_fields[j]);
				if(ValidateField(elem, mandatory_group_fields[j]) ) valid = 1;
				else return(false);
			}
			if(!valid){
				//no fields filled
				elem = eval('form.' + mandatory_group_fields[0]);
				if(!ValidateField(elem, mandatory_group_fields[0])) return(false);
			}
			
		}else{
			//single field
			elem = eval('form.' + mandatory_fields[i]);
			if(!ValidateField(elem, mandatory_fields[i])) return(false);
		}
		
	}//for
	
	return(true);
}



//Login Form Check
function checkLogin(form){
   	if(form.login_user.value == '')	{
    		alert('Insert Username');
    		form.login_user.focus();
   	 	return(false);
   	}
   	if(form.login_pass.value == '')	{
    		alert('Insert Password');
    		form.login_pass.focus();
   	 	return(false);
   	}
	return(true);
}


//Search Form Check
function checkSearch(form){
   /*
   if((form.price_search.value == '') && (form.bedrooms_search.value == '') && (form.bathrooms_search.value == '') )	{
    		alert('Please specify at least one search criterea!');
    		form.price_search.focus();
   	 	return(false);
   	}
	*/
	return(true);
}

function checkFormPass(form){
   	if(form.pass_veche.value == '')	{
    		alert('Enter current password!');
    		form.pass_veche.focus();
   	 	return(false);
   	}
	
   	if(form.pass_noua_1.value == '')	{
    		alert('Enter new password!');
    		form.pass_noua_1.focus();
   	 	return(false);
   	}
	
   	if(form.pass_noua_2.value == '')	{
    		alert('Reenter new password!');
    		form.pass_noua_2.focus();
   	 	return(false);
   	}
	
   	if(form.pass_noua_1.value != form.pass_noua_2.value)	{
    		alert('Error! You have reentered a different new password!');
    		form.pass_noua_1.focus();
   	 	return(false);
   	}

	return(true);
}

var allowed_file_types = '';
var err_msg = 'Warning: File type not allowed...';

function ValidateFile(form, file_var){
	fis = eval('form.' + file_var);
	fis = fis.value.toLowerCase();
	fis_parts = fis.split('.');
	if(fis_parts.length == 1) ext = '';
						 else ext = fis_parts[fis_parts.length - 1];

	if(fis == ''){
		alert('Warning: No file specified...');
		return false;
	}else if(ext == ''){
		alert(err_msg);
		return false;
	}else{
		valid = false;
		allowed_file_types2 = allowed_file_types.toLowerCase();
		allowed_file_types2 = allowed_file_types2.split(',');
		for(i=0; i<allowed_file_types2.length; i++){
			if(ext == allowed_file_types2[i]) valid = true;
		}
		if(!valid) alert(err_msg);
		return valid;
	}

	return true;
}


function ValidateSubmitListing(form){
	if(!Validate(form, 'date_start_day,date_start_month,date_start_year,time_start_hour,time_start_min,time_end_hour,time_end_min,address,city,province,zip,price,mls,mls_link,supr,type_of_home,bedrooms,bathrooms')) return false;

	if(form.picture.value != '') {
		allowed_file_types = 'jpg,gif';
		err_msg = 'Warning: Picture file type not allowed...';
		if(!ValidateFile(form, 'picture')) return false;
	}
	
	if(form.spec.value != '') {
		allowed_file_types = 'doc,rtf,pdf,txt,htm';
		err_msg = 'Warning: Spec sheet file type not allowed...';
		if(!ValidateFile(form, 'spec')) return false;
	}
	
	return true;
}



function ValidateProfile(form){
	if(!Validate(form, 'user,pass,fname,lname,address,city,province,zip,phone1,email')) return false;

	if(form.photo.value != '') {
		allowed_file_types = 'jpg,gif';
		err_msg = 'Warning: Photo file type not allowed...';
		if(!ValidateFile(form, 'photo')) return false;
	}
	
	return true;
}

function GotoPage(pag, GET){
	if(ns6) form = eval("document.getElementById('formSearch')");
	else if(ns4) form = eval("document.formSearch");
	else form = eval("document.all.formSearch");
	form.action = PHP_SELF + "?"+GET+"&pag="+pag;
	form.submit();
}


//Login Form Check
function ValidateFriendEmail(form){
   	if(form.your_name.value == '')	{
    		alert('Insert Your Name');
    		form.your_name.focus();
   	 	return(false);
   	}
   	if(form.friend_email.value == '')	{
    		alert('Insert Firend\'s Email Address');
    		form.friend_email.focus();
   	 	return(false);
   	}else if(!emailValid(form.friend_email.value)) {
    		alert('Invalid Email Address');
    		form.friend_email.focus();
   	 	return(false);
	}
	
	return(true);
}


//Ads emails to people list
function AddToPeopleList(nr){
	CONTROL = eval('document.forms["frm"].elements['+nr+']');	
	VAL = document.forms["frm"].email.value;
	
	if(VAL == '') {
		alert('Insert email address!');
		document.forms["frm"].email.focus();
	}else if(!emailValid(VAL)) {
		alert('Invalid email address!');
		document.forms["frm"].email.focus();
	}else{
		//verify if not already in list
		exists = 0;
		for(var i = 0;i < CONTROL.length;i++){
			if(CONTROL.options[i].value.toUpperCase() == VAL.toUpperCase()) exists = 1;
		}
		if(exists) alert('Email already in list!');
		else{
			var len = CONTROL.length;
			
			//for (a in CONTROL)
			newOption = new Option(VAL, VAL);
			CONTROL.options[len] = newOption;
			CONTROL.options[len].selected = true;
			document.forms["frm"].email.value = '';
			document.forms["frm"].email.focus();
		}
	}
}


function RemovePeopleFromList(nr){
	CONTROL = eval('document.forms["frm"].elements['+nr+']');	
	CONTROL.length = 0;
}


function SelectPeopleList(nr){
	CONTROL = eval('document.forms["frm"].elements['+nr+']');	
	for(var i = 0;i < CONTROL.length;i++){
		CONTROL.options[i].selected = true;
	}
}

function DeselectPeopleList(nr){
	CONTROL = eval('document.forms["frm"].elements['+nr+']');	
	for(var i = 0;i < CONTROL.length;i++){
		CONTROL.options[i].selected = false;
	}
}



function AddPeopleToList(people, nr){
	if(people != ''){
		CONTROL = eval('document.forms["frm"].elements['+nr+']'); 
		emails = people.split(',');
	
		for(i=0; i<emails.length; i++){
			VAL = emails[i];
			if(VAL != ''){

				/*
				//verify if not already in list
				exists = 0;
				for(var i = 0;i < CONTROL.length;i++){
					if(CONTROL.options[i].value.toUpperCase() == VAL.toUpperCase()) exists = 1;
				}

				if(!exists){
					*/
					var len = CONTROL.length++;
					CONTROL.options[len].value = VAL;
					CONTROL.options[len].text = VAL;
					CONTROL.options[len].selected = true;
				//}
			}
		}
	}
}

function showImage(nr){
	for(i=1;i<nr;i++){
		image = fieldOb('image'+i);
		image.className='ascuns';
	}
	for(i=nr+1;i<5;i++){
		image = fieldOb('image'+i);
		image.className='ascuns';
	}
	image = fieldOb('image'+nr);
	image.className='vizibil';	
}

function initImages(){
	/*
	for(i=1;i<5;i++){
		image = fieldOb('image'+i);
		alert(image);
		image.className='ascuns';
	}
	*/
	image = fieldOb('image1');
	image.className='vizibil';
}

function showDescription(nr){
	for(i=1;i<nr;i++){
		image = fieldOb('description'+i);
		image.className='ascuns';
	}
	for(i=nr+1;i<5;i++){
		image = fieldOb('description'+i);
		image.className='ascuns';
	}
	image = fieldOb('description'+nr);
	image.className='vizibil';	
}

function initDescriptions(){
	/*
	for(i=1;i<5;i++){
		image = fieldOb('image'+i);
		alert(image);
		image.className='ascuns';
	}
	*/
	image = fieldOb('description1');
	image.className='vizibil';
}

// change rate next line
function onPageLoaded(){
defaultRate = parseFloat('7.5');
initializePaymentCalculator('purchaseRequest');
populateTerms(300);
populate(calculate());
}

function AddDescribeField(id) {
	var x = fieldOb('hidden_row');
	if (id == 'Referred by a real estate agent' || id == 'Referred by a mortgage broker' || id == 'Referred by a friend' || id == 'Other ') x.className='';
	else x.className='ascuns';
}

function AlternateInformation(checked,value){
	if (checked && value == 2)
		tclass = '';
	else 
		tclass = 'ascuns';
		
	field_name = 'alternate_inf';
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	
	field.className=tclass;	

}


function ValidateSubmit(form, action){
	document.forms[form].action = action;
	
	if(action == '?users&register&signup_step=2')
		if(Validate(document.forms[form], 'company,lname,fname,email,pass,pass2,cell1,cell2,cell3,address,city')) 
			document.forms[form].submit();
	
	if(action == '?users&register&signup_step=4') 
		if(Validate(document.forms[form], 'fname,lname,address,city,zip')) 
			document.forms[form].submit();
}



function CalculateSealPrice(value1,value2,value3,value4,n){
	price = 0.00;
	    
	if( n != 0 )
		if( eval(fieldOb('totalul'+n).value) ) price = price + eval(fieldOb('totalul'+n).value);
	
	if(value2) price = price + 1900.00;

	if(value3) price = price + 200.00;
	
	if(value4) price = price + 150.00;

	amount2 = fieldOb('amount2');
	
	amount2.value = price;
	if( n != 0 )
		if( eval(fieldOb('totalul'+n).value) )  amount2.value = price - eval(fieldOb('totalul'+n).value);
		
	totalul = fieldOb('totalul');
	totalul.value='TOTAL = $' + price + '.00/yr';
	total = fieldOb('total');
	total.value = totalul.value;
}


function CalculatePrice(n){
	price = 0.00;
	
	if(price == 0.00) 
		if(eval(fieldOb('amount2').value) && eval(fieldOb('step').value)==2 ) price = price + eval(fieldOb('amount2').value);
	
	if( fieldOb('seal_type2').checked ) price = price + 1900.00;

	if( fieldOb('seal_type3').checked ) price = price + 200.00;
	
	if( fieldOb('seal_type4').checked ) price = price + 150.00;
	
	amount = fieldOb('amount');
	
	if( eval(fieldOb('amount2').value) ) amount.value = price - eval(fieldOb('amount2').value);
	else amount.value = price;
	
	totalul = fieldOb('totalul');
	totalul.value='TOTAL = $' + price + '.00/yr';
	total = fieldOb('total');
	total.value = totalul.value;
}


function CalculateItemPrice(k){
	price = 0.00;

	if( fieldOb('seal_type2').checked) price = price + 1900.00;

	if( fieldOb('seal_type3').checked) price = price + 200.00;
	
	if( fieldOb('seal_type4').checked) price = price + 150.00;
	
	t = fieldOb('totalul'+k);
	t.value = price;
	
	
}


function AddNewWebAddressField(nr){
	if(nr>=2 && nr<=10){
		field = fieldOb('website_add'+nr);
		field.className='vizibil';
		number = fieldOb('web_address_fields_number');
		nr ++;
		number.value = (nr);
	}
}

function LicenseAppear(checked){
	if (checked)
		tclass = 'vizibil';
	else 
		tclass = 'ascuns';
		
	field_name = 'new_license';
	if(ns6) field = eval("document.getElementById('"+field_name+"')");
	else if(ns4) field = eval("document."+field_name);
	else field = eval("document.all."+field_name);
	
	field.className=tclass;	

}

function hideMessage(pe)
{
    Effect.toggle('message','appear');
    pe.stop();
    msgPeriodicExecutor = null;
}

function displayMessage(msg)
{    
    if ($('message').visible() && (msgPeriodicExecutor != null))
    {         
        msgPeriodicExecutor.stop();
        $('message').hide();        
    }
    
    $('inner_message').replace('<div id="inner_message">' + msg + '</div>');
    Effect.toggle('message','appear');  
    
    msgPeriodicExecutor = new PeriodicalExecuter(hideMessage, 5);
}

function enableButtons(enable)
{
    buttons = $$('input[type="button"]');
    for (i=0;i < buttons.length;i++)
    {
        buttons[i].disabled = !enable;
    }
}

function onPrivacyUrlResponse(transport,jsonOb)
{    
    enableButtons(true);

    if (jsonOb.success)
    {
        displayMessage('The privacy url has been updated successfully');  
    }
    else
    {
        displayMessage('There was a problem updating the url: ' + jsonOb.msg);
    }
}

function onPrivacyUrlValidationResponse(transport,jsonOb)
{
    enableButtons(true);
    if (jsonOb.success)
    {
        displayMessage('The privacy url has been validated');  
        
        // Update UI
        $('pending_approval-'+jsonOb.domainId).setStyle({display:'none'});
        $('manage_domain_link-'+jsonOb.domainId).setStyle({display:'inline'});
        
        Effect.toggle('approval_steps-'+jsonOb.domainId,'slide');
    }
    else
    {
        displayMessage('There was a problem validating the url('+ jsonOb.domainId +'): ' + jsonOb.msg);
    }
}

function onFailedAjaxRequest()
{
    displayMessage('Unable to communicate with the TrustMe server.  Please try again in a few seconds.  If the problem persists, please contact the adminstrator');
    
    enableButtons(true);
}

function updatePrivacyUrl(updateFieldId)
{
    // Get the id out of the update field id (which is always formatted like this: [name of field]-[domain id]
    var fieldSplitArray = updateFieldId.split("-");
    if (fieldSplitArray[1] > 0)
    {        
        enableButtons(false);
    
        new Ajax.Request('ajax.php',
          {
                method:'get',
                parameters:{'action':'update_privacy_statement_url','domain_id':fieldSplitArray[1],'new_url': $(updateFieldId).value},
                onSuccess: onPrivacyUrlResponse,
                onFailure: onFailedAjaxRequest
          });                    
    }
}

function validatePrivacyUrl(validateFieldId)
{
    // Get the id out of the update field id (which is always formatted like this: [name of field]-[domain id]
    var fieldSplitArray = validateFieldId.split("-");
    if (fieldSplitArray[1] > 0)
    {        
        new Ajax.Request('ajax.php',
          {
                method:'get',
                parameters:{'action':'verify_privacy_statement','domain_id':fieldSplitArray[1]},
                onSuccess: onPrivacyUrlValidationResponse,
                onFailure: onFailedAjaxRequest
          });          
    }
}

