//REALCOVE CORE FUNCTIONS
//DEFAULT JQUERY AJAX HANDLER
$j.ajaxSetup({
	url: '/services.php',
	global: false,
	type: 'POST',
	dataType: 'json'
});

//On page read 	
$j( function() {
	if( $j('.jq_watermark').length > 0 )
	{
		$j('input.jq_watermark, textarea.jq_watermark').watermark();//Auto Trigger All Defined Watermarks	
	}
	$j("body").on("click", ".app-debug-header", function(){
		$j(this).closest('.app-debug').find('.app-debug-cont').toggle();
	});
});

function formatPhone(phone)
{
	var new_phone = phone.replace(/[^0-9]/g, '');
	
	if(  phone.length == 7 )
	{
		new_phone = new_phone.replace(/([0-9]{3})([0-9]{4})/g, '$1-$2');
	}
	else if(  phone.length == 10 )
	{
		new_phone = new_phone.replace(/([0-9]{3})([0-9]{3})([0-9]{4})/g, '($1) $2-$3');
	}
	else
	{
		new_phone = phone;
	}
	
	return new_phone;
	
}

/***************************************************************************
 * Provides isset functionality like that in PHP
 **************************************************************************/
function isset() {
		// http://kevin.vanzonneveld.net
		// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: FremyCompany
		// +   improved by: Onno Marsman
		// *     example 1: isset( undefined, true);
		// *     returns 1: false
		// *     example 2: isset( 'Kevin van Zonneveld' );
		// *     returns 2: true
		
		var a=arguments, l=a.length, i=0;
		
		if (l===0) {
				throw new Error('Empty isset'); 
		}
		
		while (i!==l) {
				if (typeof(a[i])=='undefined' || a[i]===null) { 
						return false; 
				} else { 
						i++; 
				}
		}
		return true;
}
/***************************************************************************
 * Provides empty functionality like that in PHP
 **************************************************************************/
function empty (mixed_var) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philippe Baumann
    // +      input by: Onno Marsman
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: LH
    // +   improved by: Onno Marsman
    // +   improved by: Francesco
    // +   improved by: Marc Jansen
    // +   input by: Stoyan Kyosev (http://www.svest.org/)
    // *     example 1: empty(null);
    // *     returns 1: true
    // *     example 2: empty(undefined);
    // *     returns 2: true
    // *     example 3: empty([]);
    // *     returns 3: true
    // *     example 4: empty({});
    // *     returns 4: true
    // *     example 5: empty({'aFunc' : function () { alert('humpty'); } });
    // *     returns 5: false
    var key;

    if (mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || typeof mixed_var === 'undefined') {
        return true;
    }

    if (typeof mixed_var == 'object') {
        for (key in mixed_var) {
            return false;
        }
        return true;
    }

    return false;
}
/***************************************************************************
 * Provides explode functionality like that in PHP
 **************************************************************************/
function explode (delimiter, string, limit) {
    // http://kevin.vanzonneveld.net
    // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: kenneth
    // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     improved by: d3x
    // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: explode(' ', 'Kevin van Zonneveld');
    // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
    // *     example 2: explode('=', 'a=bc=d', 2);
    // *     returns 2: ['a', 'bc=d']
    var emptyArray = {
        0: ''
    };

    // third argument is not required
    if (arguments.length < 2 || typeof arguments[0] == 'undefined' || typeof arguments[1] == 'undefined') {
        return null;
    }

    if (delimiter === '' || delimiter === false || delimiter === null) {
        return false;
    }

    if (typeof delimiter == 'function' || typeof delimiter == 'object' || typeof string == 'function' || typeof string == 'object') {
        return emptyArray;
    }

    if (delimiter === true) {
        delimiter = '1';
    }

    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

/***************************************************************************
 * Provides implode functionality like that in PHP
 **************************************************************************/
function implode (glue, pieces) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Waldo Malqui Silva
    // +   improved by: Itsacon (http://www.itsacon.net/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
    // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
    // *     returns 2: 'Kevin van Zonneveld'
    var i = '',
        retVal = '',
        tGlue = '';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (Object.prototype.toString.call(pieces) === '[object Array]') {
            return pieces.join(glue);
        } else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    } else {
        return pieces;
    }
}
/***************************************************************************
 * Works like basename function in PHP
 **************************************************************************/
function basename (path, suffix) {
		// http://kevin.vanzonneveld.net
		// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: Ash Searle (http://hexmen.com/blog/)
		// +   improved by: Lincoln Ramsay
		// +   improved by: djmix
		// *     example 1: basename('/www/site/home.htm', '.htm');
		// *     returns 1: 'home'
		// *     example 2: basename('ecra.php?p=1');
		// *     returns 2: 'ecra.php?p=1'

		var b = path.replace(/^.*[\/\\]/g, '');
		
		if (typeof(suffix) == 'string' && b.substr(b.length-suffix.length) == suffix) {
				b = b.substr(0, b.length-suffix.length);
		}
		
		return b;
}

/***************************************************************************
 * Allows setting of default values for textboxes, strips them out before 
 * sending to server
 **************************************************************************/
$j(function(){

		/***************************************************************************
		 * Default Input Values - Handle default values for form elements
		 **************************************************************************/
		$j('input[type="textbox"].usehint').each(function(){
				//We need to save the element for the sake of the data() method
				var definput = $j(this);
				//Save the default value for this element
				definput.data('DefVal',definput.val())
						//Assign a starting color of silver
						.css('color','silver')
								//When the this element gets focus...
								.focus(function(){
										//If the default text is the current value...
										if(definput.val()==definput.data('DefVal')){
												//Clear the text and change color to black
												definput.val('').css('color','black');
										}
								})
								//When this element loses focus...
								.blur(function(){
										//If the field is essentially empty...
										if(definput.val().replace(' ','')==''){
												//Use our saved default value
												definput.val(definput.data('DefVal'))
														//And change color back to silver
														.css('color','silver');
										}
								});
								//Additional functionality goes here
								/***************************************************************************
								 * Before submit, set all fields with default values to empty
								 **************************************************************************/
								//Select only the current form
								$j(this).parents('form:first')
											 //When this form's submit button is clicked...
											 .find('input[type="submit"],button[type="submit"]').click(function(){
											 //Select all default-capable fields in the current form
												$j(this).parents('form:first').find('input.usehint').each(function(){
														//If the data matches the value...
														if($j(this).val()==$j(this).data('DefVal')){
																//Set the value of the field to empty
																$j(this).val('');
														}
												});
												//Allow the button to submit
												return true;
								});																
				}); //End default value functionality
}); //End DOM Ready
/***************************************************************************
 * Works like in_array function in PHP
 **************************************************************************/
function in_array (needle, haystack, argStrict) {
    // Checks if the given value exists in the array  
    // 
    // version: 1009.2513
    // discuss at: http://phpjs.org/functions/in_array    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '', strict = !!argStrict; 
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {                
							return true;
            }
        }
    }
     return false;
}
/***************************************************************************
 * Works like stripos function in PHP
 **************************************************************************/
function stripos (f_haystack, f_needle, f_offset) {
    // http://kevin.vanzonneveld.net
    // +     original by: Martijn Wieringa
    // +      revised by: Onno Marsman
    // *         example 1: stripos('ABC', 'a');
    // *         returns 1: 0
    var haystack = (f_haystack + '').toLowerCase();
    var needle = (f_needle + '').toLowerCase();
    var index = 0;

    if ((index = haystack.indexOf(needle, f_offset)) !== -1) {
        return index;
    }
    return false;
}
/***************************************************************************
 * Not sure if this is still used out there
 **************************************************************************/
function clearSearchForm() {
	document.srchform.qry.value = '';
	//alert(document.srchform.property[1].value);
	
	//document.getElementById("property").checked = false;
	
//	for (i = 0; i < document.srchform.property[].length; i++)
	//	document.srchform.property[i].checked = false ;
//	}

	//document.srchform.property[1].checked = true;
	$("pricelow").selectedIndex = "0";
	$("pricehigh").selectedIndex = "0";
	document.srchform.minsqft.value = '';
	$("minbeds").selectedIndex = "0";
	$("minbaths").selectedIndex = "0";
}

function validRequired(formField,fieldLabel) {
	var result = true;
	if (formField.value == "") {
		alert('Please enter a value for the "' + fieldLabel +'" field.');
		formField.focus();
		result = false;
	}
	return result;
}

function validateForm(theForm)
{//DEPRECATE THIS BAD FUNCTION
	if (theForm.mls.value == " Type MLS # Here") { // it is not an MLS request

		var problem = 'No';
		if (theForm.area.value == "ERROR_QUICK_AREA") {
			alert ("Please enter a search area.");
			theForm.area.value = "*** Area";
			theForm.area.focus();
			problem = 'Yes';
		}
		if (problem == 'No') { return true; } 
			else { return false; }
	}
}

function clearType() {document.quick.mls.value = '';}

/***************************************************************************
 * 	Format money like that in PHP
 *	var price = '$' + (123456789.4321).formatMoney(2, '.', ',');
 **************************************************************************/

Number.prototype.formatMoney = function(c, d, t){
	var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
	 return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
 };


/***************************************************************************
 * 	getCookie Returns value of cookie even if stored in array "array[value]"
 **************************************************************************/
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
		 
/***************************************************************************
 * 	Inspect elements inside an object
 **************************************************************************/
function inspect(obj, maxLevels, level)
{
  var str = '', type, msg;

    // Start Input Validations
    // Don't touch, we start iterating at level zero
    if(level == null)  level = 0;

    // At least you want to show the first level
    if(maxLevels == null) maxLevels = 1;
    if(maxLevels < 1)     
        return '<font color="red">Error: Levels number must be > 0</font>';

    // We start with a non null object
    if(obj == null)
    return '<font color="red">Error: Object <b>NULL</b></font>';
    // End Input Validations

    // Each Iteration must be indented
    str += '<ul>';

    // Start iterations for all objects in obj
    for(property in obj)
    {
      try
      {
          // Show "property" and "type property"
          type =  typeof(obj[property]);
          str += '<li>(' + type + ') ' + property + 
                 ( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>';

          // We keep iterating if this property is an Object, non null
          // and we are inside the required number of levels
          if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1);
      }
      catch(err)
      {
        // Is there some properties in obj we can't access? Print it red.
        if(typeof(err) == 'string') msg = err;
        else if(err.message)        msg = err.message;
        else if(err.description)    msg = err.description;
        else                        msg = 'Unknown';

        str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
      }
    }

      // Close indent
      str += '</ul>';

    return str;
}

function loadSystemMessage( message ) 
{
	if( !empty(message) )
	{
		var width = $j('#wrapper').width() - 10;
		$j("#system_message_cont").width(width);
		$j('#system_message').append('<div>' + message + '</div>');
		$j("#system_message_cont").fadeIn('fast');
		
		setTimeout("clearSystemMessage()",3000);
	}
}
															
function clearSystemMessage() 
{
	$j("#system_message_cont").fadeOut('slow');
	$j('#system_message').html("");
}
			
function sendEmailHelpRequest( ref_url ) {

	var userName = $('userName').value;
	
	new Ajax.Request( "/services.php", {
									method: "post",
									parameters: {	api:'sendEmailHelpRequest', userName:userName, ref_url:ref_url },		
									onLoading: function() { 									
									},
									onSuccess: function(transport){
										$("system_message").innerHTML = transport.responseText;
										//response = eval(transport.responseText);
									}});	
	

}

function loadDynFile(file, type){
	//Dynamically load a js or css file	
	var exists = false;			
	var qry = type == 'css' ? 'link' : 'script';
	var attr = type == 'css' ? 'href' : 'src';
	
	$j(qry).each( function()
	{//Look for loaded file anywhere in DOM
		if( $j(this).attr(attr) == file ) exists = true;							
	});
				
	if( !exists ) 
	{				
		if(type == "js")
		{//Create Javascript domfile
			var domfile=document.createElement('script');
			domfile.setAttribute("type","text/javascript");
			domfile.setAttribute("src", file);
		}
		else if(type == "css")
		{//Create CSS domfile
			var domfile=document.createElement("link");
			domfile.setAttribute("rel", "stylesheet");
			domfile.setAttribute("type", "text/css");
			domfile.setAttribute("href", file);
		}
						
		if (typeof domfile != "undefined")
		{			
			var head = document.getElementsByTagName ("head")[0] || document.documentElement;
			
			if( type == 'css' ) 			
			{//CSS files inserted between main.css and custom css file
				var custom_css = document.getElementById('custom_css');
				head.insertBefore(domfile, custom_css);//head.firstChild
			}
			else
			{//JS files appended to bottome of HEAD				
				head.insertBefore(domfile, head.lastChild);
			}
		}			
	}
}

function authUser( userName, password, callbackFunctionName ) {
	//Check if user has authorization to access this page/site
	$j.ajax({
		data:	{ api:'authUser', userName:userName, password:password, return_type:'json' },	
		success: function( response ) {	
			if( response == null ) {
				loadSystemMessage("No response has been returned from the server, please try again later.");
			} else {
					if( response.status == 1 ) 
					{
						
						if(isset(callbackFunctionName) && typeof window[callbackFunctionName] === "function") 
						{
							window[callbackFunctionName]( response );
						} 
						else
						{
							window.location.reload();
						}
	
					} 
					else if( response.status == 0 ) 
					{	
						if(isset(callbackFunctionName) && typeof window[callbackFunctionName] === "function") 
						{
							window[callbackFunctionName]( response );
						}			
						else 
						{		
							loadSystemMessage(response.msg);
						}
					}
			}
		},
		complete: function() {											
		}
	});			
}
function createUser( userName, password, onSuccessFunctionName ) {
	//Min requirements for user to create account
	$j.ajax({
		data:	{ api:'createUser', userName:userName, password:password, return_type:'json' },	
		success: function( response ) {	
			if( response == null ) {
				loadSystemMessage("No response has been returned from the server, please try again later.");
			} else {
					if( response.status == 1 ) 
					{
						
						if(isset(onSuccessFunctionName) && typeof window[onSuccessFunctionName] === "function") 
						{
							window[onSuccessFunctionName]();
						} 
						else
						{
							window.location.reload();
						}
	
					} 
					else if( response.status == 0 ) 
					{	
						loadSystemMessage(response.msg);
					}
			}
		},
		complete: function() {											
		}
	});			
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
 * 
 * jQuery Delay Plugin
 * version: 0.0.1 (14-Jan-2010)
 * @requires jQuery v1.3.0 or later
 * Author: drew (drew.wells@claytonhomes.com)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */
$j.fn.eachDelay = function(callback, speed){
	return $j.eachDelay( this, callback, speed)
}

$j.extend({
	eachDelay: function(object,callback, speed){ 
		var name, i = -1, length = object.length, $div = $('<div>'), id;
		if (length === undefined) { //not an array process as object
			var arr = [], x = -1;
			for (name in object) arr[++x] = name; 
			id = window.setInterval(function(){
			 if( ++i === arr.length || callback.call(object[ arr[i] ], arr[i], object[ arr[i] ]) === false) 
				 clearInterval(id);
			}, speed);	
		}
		else { //array-compatible element ie. [], jQuery Object
			id = window.setInterval(function(){ 
				if (++i === object.length || callback.call(object[i], i, object[i]) === false) 
					clearInterval(id);
			}, speed);
		}
		return object;
	}
});
