//====================================
// ==============================================================
//  Realtor Engine: CMS - Client Side Tasks
// ==============================================================
//====================================

// Please refer to ajaxphpscripts.js for version information.

// (c)Snc Design - Quality Graphics and Code - [www.sncdesign.net]

// Notes: This document contains most rudementary calls by client side.

// ========================================
//  PHP $_GET Admin Handler
// ========================================
function checkadmin(i, account, page)
{
	window.commandinitiated = 0;
	window.oldrequest = 0;
	window.account = account;
	
	if (document.location.href.split("#")[0].indexOf("page=") != -1){}	//non javascript page request ignores the next 2 conditions
	else if (window.location.hash == "") //if no hash exists load the default page
	{
		window.location.hash = page;
		document.getElementById('anchor_iframe').src= "blank.php?functionstring=" + page;
	}
	else
	{
		var params = window.location.hash.split(":");
		window.location.hash = params[0].replace("#", "");
		launchInside(params[0].replace("#", ""),params[1]);
	}
	if (document.getElementById('copyright'))
	{
		var d = new Date();
		document.getElementById('copyright').innerHTML = document.getElementById('copyright').innerHTML.replace("{date}",d.getFullYear());
	}
	if(document.cookie.indexOf(";") == 1)
	{
		var brokencookies = document.cookie.split(";");
		var brokenpiece   = brokencookies[1].split("=");
		if (brokencookies[0] == "remember_me=true")
		{
			adminBar(1, brokenpiece[1]);
			window.loggedin = 1;
		}
	}
	else if (((getGetVar(location) == "?admin=true") || (i == 0)) && (document.getElementById('adminlogin')))
		adminBar(0); 
}
function getGetVar(searchStr)
{
	start = location.search.indexOf(searchStr)+searchStr.length+1;
	end = (location.search.indexOf('&', start) == -1)? location.search.length : location.search.indexOf('&', start);
	return unescape(location.search.substring(start, end));
}
function adminBar(i, accessmask)
{
		if ((i == 1) && (accessmask == "ROOT"))
		document.getElementById('adminlogin').innerHTML = "<input type=hidden id='accessmask' value='" + accessmask + "'>| <a class=\"footerlink\" href=\"javascript:launchForm('login');\">Logout</a> | <a class=\"footerlink\" href=\"javascript:launchInside('settings');\">Control Panel</a>";
		else if ((i == 1) && (accessmask != "ROOT"))
		document.getElementById('adminlogin').innerHTML = "<input type=hidden id='accessmask' value='" + accessmask + "'>| <a class=\"footerlink\" href=\"javascript:launchForm('login');\">Logout</a> | <a class=\"footerlink\" href=\"javascript:launchInside('settings');\">My Settings</a>";	
		else
		document.getElementById('adminlogin').innerHTML = " | <a class=\"footerlink\" href=\"javascript:launchForm('login');\">Login</a>";
			
}
// =================================
//  Display a loading icon
// =================================

function displayload()
{
	document.getElementById('ajaxDiv').innerHTML = '<img src="images/animated/loading.gif">Please Wait...';
}
// =================================
//  Display response text
// =================================

function displayresponse(i, id)
{
	if ((id == undefined) || (id == 'undefined') || (id == ''))
	id = 'ajaxDiv';
	document.getElementById(id).innerHTML = i;
}
// =================================
//  Clear or replace form content
// =================================
function clickclear(thisfield, defaulttext) 
{
     if (thisfield.value == defaulttext) 
     {
          thisfield.value = "";
     }
}

function clickrecall(thisfield, defaulttext) 
{
     if (thisfield.value == "") 
     {
          thisfield.value = defaulttext;
     }
}
// =================================
//  Key Press Check
// =================================

function numbersonly(myfield, e, dec)
{
	var key;
	var keychar;
	
	if (window.event)
	   key = window.event.keyCode;
	else if (e)
	   key = e.which;
	else
	   return true;
	keychar = String.fromCharCode(key);
	
	// control keys
	if ((key==null) || (key==0) || (key==8) || 
	    (key==9) || (key==13) || (key==27) )
	   return true;
	
	// numbers
	else if ((("0123456789").indexOf(keychar) > -1))
	   return true;
	
	// decimal point jump
	else if (dec && (keychar == "."))
	   {
	   myfield.form.elements[dec].focus();
	   return false;
	   }
	else
	   return false;
}

function checkSubmit(event, returnFunction)
{    
	NS4 = (document.layers) ? true : false; 
	var code = 0;
    
	if (NS4)
        	code = event.which;
    	else
        	code = event.keyCode;
   	if (code==13)
        	eval(returnFunction);
}
function checkEnter(event, myform)
{    
	NS4 = (document.layers) ? true : false; 
	var code = 0;
    
	if (NS4)
        	code = event.which;
    	else
        	code = event.keyCode;
   	if (code==13)
        	 document.getElementById(myform).submit();
}
// ========================================
//  Log a person in
// ========================================
function login(accessmask, remember_me)
{
	if(remember_me == 1)
	{
		delete_cookie("remember_me");
		delete_cookie("access_mask");
		document.cookie = "remember_me=true; expires=15/02/2020 00:00:00";
		document.cookie = "access_mask="+accessmask+"; expires=15/02/2020 00:00:00";		
	}
	adminBar(1, accessmask);
	window.loggedin = 1;
	launchInside('settings');
}

// ================================
//  Log Out and Destroy Cookies
// ================================

function logOut()
{
	delete_cookie("remember_me");
	delete_cookie("access_mask");
	window.loggedin = 0;
	location.reload(true);
}
function delete_cookie ( cookie_name )
{
  var cookie_date = new Date ( );  // current date & time
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}
// ========================================
//  Resize an Iframe
// ========================================

function reSize(ifrm)
{	
	var oBody		 =	window.frames[ifrm].document.body;
	var oFrame	 =	document.getElementById(ifrm);
	var stringadd   = 	ifrm.replace("ifrm", "");
	//if ((typeof window.recordedwidth == "undefined") || (window.recordedwidth >= document.getElementById('iframesize'+stringadd).offsetParent.offsetWidth))
	//{
	//	window.recordedwidth = document.getElementById('iframesize'+stringadd).offsetParent.offsetWidth;
	//	oFrame.style.width  = document.getElementById('iframesize'+stringadd).offsetParent.offsetWidth;
	//}
	if ((typeof window.recordedheight == "undefined") || (window.recordedheight >= oBody.scrollHeight))
	{	
		window.recordedheight = oBody.scrollHeight;
		oFrame.style.height = oBody.scrollHeight;
	}
}

function iFrameHeight(ifrm) 
{
	var h;
	
	if(navigator.userAgent.indexOf("MSIE")!=-1)
	{
		reSize(ifrm);
	}
	else
	{
		if(document.getElementById && !(document.all)) 
		{
			h = document.getElementById(ifrm).contentDocument.body.scrollHeight;
			document.getElementById(ifrm).style.height = h+"px";
		}
		else if(document.all) 
		{
			h = document.frames(ifrm).document.body.scrollHeight;
			document.all.eval(ifrm).style.height = h+"px";
		}
	}
}

function sizeToparent(id, parentid)
{
	document.getElementById(id).style.width = document.getElementById(parentid).offsetWidth;
	document.getElementById(id).style.height = document.getElementById(parentid).offsetHeight;
}
// ========================================
//  Force PDF Download
// ========================================
function download(i)
{
	var downloadWindow = window.open('download.php?filename=' + i,'Download', "height=0, width=0, menubar=0, scrollbars=0, status=0, toolbar=0, location=0");
}
// ========================================
//  Update Contact Form
// ========================================
function mailResult(response)
{
  	document.getElementById('f1_upload_process').innerHTML = '';
	document.getElementById('mail_result').innerHTML = response;
}
// ========================================
//  Quick Launch Functions
// ========================================
//standard
function displayresponse(message, id)
{
	if ((id == "undefined") || (id == undefined) || (id == ''))
	id = 'ajaxDiv';
	
     document.getElementById(id).innerHTML = message;
}
function launchAform(i)
{
	launchForm("form" + i);
}
function mapSearch()
{
	launchInside('blog,iframe', '13,http://base.google.com/base/s2?a_n0=housingxyz250a_y0=9xyz250hl=enxyz250gl=usxyz255/base/s2/ajax?a_n0=housingxyz250a_y0=9xyz250start=0xyz250q=xyz250scoring=xyz250xyz250a_n1=listing+typexyz250a_y1=1xyz250a_o1=5xyz250a_n3=pricexyz250a_y3=8xyz250a_o3=5xyz250a_n4=property+typexyz250a_y4=1xyz250a_o4=5xyz250a_n5=bedroomsxyz250a_y5=2xyz250a_o5=5xyz250a_n6=bathroomsxyz250a_y6=3xyz250a_o6=5xyz250a_n7=yearxyz250a_y7=2xyz250a_o7=5xyz250a_n8=square+feetxyz250a_y8=2xyz250a_o8=5xyz250a_n9=school+districtxyz250a_y9=1xyz250a_o9=5xyz250sl=onxyz250a_n2=locationxyz250a_y2=6xyz250a_o2=0xyz250a_v2=red%2520deerxyz250xyz250hl=enxyz250gl=usxyz250view=Map', '1', '100%');
}
function launchMailinglist()
{
	launchForm('mailinglist');
}
function launchVideo()
{
	launchForm('video');
}
function launchContactform()
{
	launchForm('contact');
}
function closeForm()
{
	winLaunch('dynamicForm');
	document.getElementById('AjaxDynamic').innerHTML = '';
}
function openExternalsite(link, width, height)
{
	if ((width == "") || (width == "undefined") || (height == undefined))
		width = 800;
	if ((height == "") || (height == "undefined") || (height == undefined))
		height = 600;
	window.open(link,"ExternalSite","scrollbars=1,width="+width+", height="+height);
}
// ========================================
//  Reveal From ID for ID
// ========================================
function reveal(insertid, fromid, type)
{
	if (type == "value")
	document.getElementById(insertid).innerHTML = document.getElementById(fromid).value;	
	else if (type == "innerhtml")
	document.getElementById(insertid).innerHTML = document.getElementById(fromid).innerHTML;
}
function revealPost(i)
{
	document.getElementById('post' + i).innerHTML = document.getElementById('richtextContent'+i).value + "...<a href=\"javascript:closePost("+i+");\">Show Less</a>";
}
// ========================================
//  Expand/Collapse Blog
// ========================================
function revealPost(i)
{
	document.getElementById('post' + i).innerHTML = document.getElementById('richtextContent'+i).value + "...<a href=\"javascript:closePost("+i+");\">Show Less</a>";
}
function closePost(i)
{
	document.getElementById('post' + i).innerHTML = document.getElementById('richtextShort'+i).value + "<a href=\"javascript:revealPost("+i+");\">Show More</a>";
}

// ========================================
//  Mailing List Vailidation
// ========================================
function vmailinglist(mainform) 
{
	var mNve    = mainform.email.value;
	var email   = new RegExp(/^[-._&0-9a-zA-Z]+[@][-._&0-9a-zA-Z]+[.][._0-9a-zA-Z]+[a-zA-Z]$/);
	if (!email.test(mNve))
	{
		alert('Please enter your email.');
		return false;
	}
	return true;
}
// ========================================
//  Contact Form Validation
// ========================================
function validate(mainform) 
{
	if ((mainform.name == "form2") || (mainform.name == "form3"))
		if (mainform.firstname.value == "")
		{
			alert('Please enter your name.');
			return false;
		}
	if ((mainform.name == "form2") || (mainform.name == "form3"))
		if (mainform.lastname.value == "")
		{
			alert('Please enter your last name.');
			return false;
		}
	mNve = "asdf@asdf.com";
	mNvp = "968-345-2345";
	if (mainform.phone)
		var mNve    = mainform.email.value;
	if (mainform.phone)
		var mNvp    = mainform.phone.value;
	var f       = '2';
	var phone   = new RegExp(/^\d{3}-\d{3}-\d{4}$/);
	var email   = new RegExp(/^[-._&0-9a-zA-Z]+[@][-._&0-9a-zA-Z]+[.][._0-9a-zA-Z]+[a-zA-Z]$/);

	if (((mNve == '') || (!email.test(mNve)) || (mNve == "email@domain.com")) && ((mNvp == '') || (!phone.test(mNvp)) || (mNvp == "000-000-0000")))
	{
		alert('Please enter either your phone number, your email or both. Please ensure that it is in a correct format.');
		f = '1';
	}
	if (mainform.name == "mainform")
	{
		var mNvm    = mainform.Message.value;
		if ((mNvm == '') || (mNvm == 'You must enter a message before submitting.') || (mNvm == 'Enter Message Here.'))
		{
			alert('You must enter a message.');
			document.mainform.Message.value = 'Enter Message Here.'
			f = '1';
		}
	}
	if (document.getElementById('tos')) //dont bother checking if it doesnt exist.
	{
		if (!document.getElementById('tos').checked)
		{
			f = 1;
			alert('You must agree to the terms of Service by checking the box.');
		}
	}
	if (f == '1')
	{
		return false;
	}
	else
	{
      		document.getElementById('f1_upload_process').innerHTML =
		'<table><tr><td><img src="images/animated/loading.gif"></td><td>Working...</td></tr></table>';
		return true;
	}
}

//Mouse over submit button when nothing is filled in displays error.
function mouseovervalidate() 
{
	var mNvm = document.mainform.Message.value;

	if ((mNvm == '') || (mNvm == 'Enter Message Here.'))
	{
		document.mainform.Message.value = 'You must enter a message before submitting.'
	}
}

//Mouse leaves submit button when nothing is filled in displays error.
function clearform() 
{
	var mNvm = document.mainform.Message.value;

	if (mNvm == 'You must enter a message before submitting.')
	{
		document.mainform.Message.value = ''
	}
}

// ========================================
//  Send necessary data to the Flash Banner
// ========================================
function launchFlash(movie, insert, x, y, wmode, variables) //creates variable list from "variables" (variable1=value1:variable2=value2...)
{
	if ((variables != undefined) && (variables != ""))
	{
		while(variables.indexOf("http://") != -1)
			variables = variables.replace("http://", "http//"); //this converts http:// since the ":" is used for a value split.
	}
	if (movie.indexOf("/") == -1) //revert to account directory if none specified
	{
		movie = 'images/applets/'+movie+'.swf';
	}
	if (variables != undefined) //if no list is defined
	{	
		var values = variables.split(":");
	}
	var soOne = new SWFObject(movie,insert,x,y, '8', '');
	var variable;
  	soOne.addParam('allowfullscreen','true');
  	soOne.addParam('scale','scale');
	soOne.addParam('wmode', wmode);
 	soOne.addVariable('autostart','true');
 	if ((variables != undefined) && (variables != "")) //if no list is defined
	{	
 		for(singlevalue in values) //create variable list
		{
			variable 	  = values[singlevalue].split("=");
			if (variable[1] != undefined)
			{
				variable[1] = variable[1].replace("http//", "http://");
			}
			soOne.addVariable(variable[0],variable[1]); //http:// is replaced
		}
	}
 	soOne.write(insert);
}

// =================================
//  Commence upload/Show loading bar
// =================================

function startUpload()
{
     document.getElementById('f1_upload_process').innerHTML =
	'<table><tr><td><img src="images/animated/loading.gif"></td><td class="whitetext">Working...</td></tr></table>';
	return true;
}

// =================================
//  Update File upload Progress
// =================================

function stopUpload(success, alternatesuccess)
{
	if ((success == 3) || (success == 2))
	{
		document.getElementById('f1_upload_process').innerHTML =
		'The item has been added successfully.';
		eval(alternatesuccess);

	}
	else if (success == 5)
	{
		document.getElementById('f1_upload_process').innerHTML =
		'The image you have attempted to upload is not the correct dimensions.';
	}
	else if (success == 6)
	{
		document.getElementById('f1_upload_process').innerHTML =
		'Please upload a file that is in JPEG format.';
	}
      else 
	{
		document.getElementById('f1_upload_process').innerHTML = success;
		//       	document.getElementById('f1_upload_process').innerHTML =
		// 'There was an error during your file upload! Please Be sure to verify a few things:<br /> 1. You are not having connection problems.<br />2. Make sure you attach a file before pressing OK.<br /> 3. Make sure your attached file is under 150KB.<br/>';
	}
}
// =================================
//  Remove an effect after a while
// =================================

function expire() 
{ 
	document.getElementById('f1_upload_process').innerHTML = "";
}
function sadvancedwin() 
{ 
	winLaunch('advancedwin');
}
function clearinfo()
{
	document.getElementById('f1_upload_process').innerHTML = "";
	winLaunch('dynamicForm');
	setTimeout("reloadcontent()", 100);
}
function clearinfo_i()
{
	document.getElementById('f1_upload_process').innerHTML = "";
	loadContent();
	winLaunch('dynamicForm');
}
function clearinfo_ii()
{
	document.getElementById('f1_upload_process').innerHTML = "";
	launchInside('blog','1');
	winLaunch('dynamicForm');
}
function reloadcontent()
{
	var suid = document.getElementById('suid').value;
	loadContent("item", suid);
}
function closeform()
{
	winLaunch('dynamicForm');
	enlargeImage(0);
	addPreviewer();
}
// =================================
//  Validate Field
// =================================
function validateField(field,regexpression,defaultclass)
{
	$(field).unbind('focus');
	if(field.value.match(regexpression)) //if we pass
	{
		$(field).animateToClass("passValidation", 1000).addClass("passValidation").removeClass('failValidation');
	}
	else if(field.value == '')
	{
		$(field).animateToClass(defaultclass, 1000).removeClass('passValidation').removeClass('failValidation');			
	}
	else
	{
		if(!$(field).is('.failValidation'))
			$(field).animateToClass("failValidation",1000).addClass("failValidation").removeClass('passValidation');

		$(field).focus(function() {
			$(this).nextAll("em").eq(0).css("top",$(this).offset().top-50).animate({opacity: "show", left: $(this).offset().left, top: $(this).offset().top - 75}, "slow");
		});
		$(field).blur(function() {
			$(this).nextAll("em").eq(0).animate({opacity: "hide", top: $(this).offset().top - 50}, "fast");
		});
	}
}
function checkForm(form)
{
	fail = 0;
	issues = 'Form Issues:';
	
	$('input').each(function() {
		if(this.alt == 'required' && this.className.search('passValidation') == -1)
		{
			fail = 1;		
			if(!$(this).is('.failValidation'))
				$(this).animateToClass("failValidation",1000).addClass("failValidation").removeClass('passValidation');
			issues +=  '\n' + this.name + ": " + $(this).nextAll("em").eq(0).html();
		}
	});
	
	// Hacked in by Daniel to validate attachment extensions
	filename = $('#file').val();
	// If a file has been specified to upload...
	if (filename) {
		file_extension = filename.substring(filename.lastIndexOf('.') + 1).toLowerCase();
		filetypes = $('#filetype').val().toLowerCase();
		type_array = filetypes.split(',');
		// ... its extension should be in the list of allowed ones.
		if (type_array.indexOf(file_extension) == -1) {
			issues += " Please attach a supported document type.";
			fail = 1;
		}
	}

	if(fail == 0)
		return true;

	alert(issues);
	return false;	
}