
//BROWSER DETECTION
var ns4 = document.layers;
var ns6 = document.getElementById && !document.all;
var ie4 = document.all;
 
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 		= "#F6F6F6";
	}else {
		border_color 	= "#cccccc";
		border_style 	= "solid";
		bgcolor 		= "#FFFFFF";
	}
	//field.style.borderColor 	= border_color;
	//field.style.borderStyle 	= border_style;
	field.style.backgroundColor = bgcolor;
}

function imgField2(field, img){
	if(img == "over") {
		border_color 	= "#bbd7e8";
		border_style 	= "solid";
		bgcolor 		= "#F6F6F6";
		font_color		= "#6aa2c3";
	}else {
		border_color 	= "#84b5d2";
		border_style 	= "solid";
		bgcolor 		= "#e2eff6";
		font_color 		= "#adb3ba";
	}
	field.style.borderColor 	= border_color;
	field.style.borderStyle 	= border_style;
	field.style.backgroundColor = bgcolor;
	field.style.color 	= font_color;
}

function imgSettings(field, img){
	field = $('#' + field);
	field.toggleClass("about_field_background2");
}

function imgSettingsTextarea (field, img){
 
field = $('#' + field);
field.toggleClass("about_textarea_background2");
} 


//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;
}

//get order and sort from url needed to sort
function existsURLParam(strParamName) {
    var strReturn = "";
    var strHref = window.location.href;
    if ( strHref.indexOf("?") > - 1 ) {
        var strQueryString = strHref.substr(strHref.indexOf("?")+1).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
            if (aQueryString[iParam] == strParamName.toLowerCase()) return true;
        }
    }
    return false;
} 
 
   
   
//get order and sort from url needed to sort
function getURLParam(strParamName) {
    var strReturn = "";
    var strHref = window.location.href;
    if ( strHref.indexOf("?") > - 1 ) {
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
            if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > - 1 ) {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
}

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 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.type == 'checkbox' && !elem.checked))	{ // ||(elem.value == 0)
		var label = elem.previousElementSibling.textContent;
    		alert(label.substring(0, label.length-1)+' is required!');
    		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){
	if (fields=='') return true;
   	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.old_pass.value == '')	{
    		alert('Enter current password!');
    		form.old_pass.focus();
   	 	return(false);
   	}
	
   	if(form.new_pass1.value == '')	{
    		alert('Enter new password!');
    		form.new_pass1.focus();
   	 	return(false);
   	}
	
   	if(form.new_pass2.value == '')	{
    		alert('Reenter new password!');
    		form.new_pass2.focus();
   	 	return(false);
   	}
	
   	if(form.new_pass1.value != form.new_pass2.value)	{
    		alert('Error! You have reentered a different new password!');
    		form.new_pass1.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,pass1,pass2,fname,lname,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();
}

function IsNumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         {
         blnResult = false;
         }
      }
   return blnResult;
   }



  /*
   * input type file customized
   */
  
  
  var W3CDOM = (document.createElement && document.getElementsByTagName);

function init() {
	
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	//var x = document.getElementsByTagName('form');
	//alert($('#import_contacts_form').length);

		
	if ($('#import_contacts_form').length > 0)
		fakeFileUpload.className = 'fakefile';
	else if ($('#add_documents_forms').length>0)
		fakeFileUpload.className = 'fakefile2';
	else return;
	
	
//	alert(fakeFileUpload.className);
	s1 = document.createElement('span');
	s2 = document.createElement('span');
	s3 = document.createElement('em');
	s4 = document.createElement('strong');
	s5 = document.createElement('div');
	s5.className="docup";
	s1.appendChild(document.createElement('input'));
	s2.appendChild(s1);
	s3.appendChild(s2);
	s4.appendChild(s3);
	s5.appendChild(s4);
	fakeFileUpload.appendChild(s5);
	
	var image_input = document.createElement('input');
	image_input.className = 'button3'; // HTTP+'_layouts/images/but_03.png';
	image_input.value = 'Upload...';
	image_input.type = 'button';
	//image_input.id = 'docupload';
	s6 = document.createElement('div');
	s6.className="docup1";
	s6.appendChild(image_input);
	fakeFileUpload.appendChild(s6);
	
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file' && x[i].type != 'button') continue;
		if (x[i].getAttribute('noscript')) continue;
		if ($('#import_contacts_form').length > 0) {
			if (x[i].parentNode.className != 'fileinputs') 
				continue;
			x[i].className = 'file hidden';
		}else if ($('#add_documents_forms').length>0){
			if (x[i].parentNode.className != 'fileinputs2') 
				continue;
			x[i].className = 'file2 hidden';
		}
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		if (x[i].value)
			x[i].onchange();
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
	
	
}

	

	
	

   
