// JavaScript Document

//REGULAR FUNCTIONS
function compilePgrInfo(parentID,listname,dispCont,pgSize,btnDiv,fCls,pCls,nCls,lCls) {
	TS_JQ(parentID).find('table tr:not(.ui-widget-header)').hover(function() { TS_JQ(this).addClass('ui-state-hover'); },function() { TS_JQ(this).removeClass('ui-state-hover'); }).end().find('.pagerNavButtonDiv, .pagerInfoDiv').removeClass('ui-helper-hidden');
	var pd = TS_JQ('.pagedisplay',parentID).val();
	var info = pd.split('/');
	updatePagerDisplay(parentID,dispCont,parseFloat(info[0]),parseFloat(info[1]),pgSize,parseFloat(info[2]));
	if (btnDiv!='' && fCls!='' && pCls!='' && nCls!='' && lCls!='') updatePagerBtnStatus(parentID,btnDiv,fCls,pCls,nCls,lCls,parseFloat(info[0]),parseFloat(info[1]));
}
function applyOverlay(el) {
	var overlay = '<div class="ui-widget-overlay"></div>';
	TS_JQ(el).before(overlay);
	TS_JQ('.ui-widget-overlay').click(function() { TS_JQ('#dialogDiv').dialog('close'); });
}
function formatForList(value, maxChars) {
	var isBigger = false;
	value = value.replace(/<head[^>]*>[\w\W]*?<\/head>[\n\r]*/gi, '');
	value = value.replace(/<link[^>]*>[\n\r]*/gi, '');
	value = value.replace(/<script[^>]*>[\w\W]*?<\/script>[\n\r]*/gi, '');
	value = value.replace(/<style[^>]*>[\w\W]*?<\/style>[\n\r]*/gi, '');
	value = strip_tags(value);
	if (maxChars != -1) {
		if (strlen(trim(value)) > maxChars) {
			value = value.substr(0, maxChars);
			isBigger = true;
		}
	}
	value = value.replace('<','&lt;');
	value = value.replace('>','&gt;');
	if (value == "") value = "&nbsp;";
	if (isBigger) value += "...";
	return value;
}
function updateHistoryStatus(action,id) {
	var delfromall = false;
	if (action == 'deletefromall') {
		action = 'delete';
		delfromall = true;
	}
	var serData = 'action='+action;
	var doAjax = true;
	var as = false;
	var comp = function() {  };
	var $sidebarhist = TS_JQ('#sidebarHistory');
	var $histlist = TS_JQ('#historyList');
	if (action == "usage") {
		var useHist= $sidebarhist.data('useHist');
		serData += '&usehist='+((useHist) ? 1 : 0);
		if (!useHist) {
			comp = function() { $sidebarhist.find('.loading-med').parent().addClass('ui-helper-hidden') };
			$sidebarhist.find('.loading-med').parent().removeClass('ui-helper-hidden');
			$histlist.addClass('ui-helper-hidden');
			as = true;
		}
	} else if (action == 'delete') {
		serData += '&hID='+id;
	} else if (action == 'deleteall') {
	} else if (action == 'getsidebar') {
		as = true;
		comp = function() { $sidebarhist.find('.loading-med').parent().addClass('ui-helper-hidden') };
	} else doAjax = false;
	if (delfromall === true) serData += '&delfromall=1';
	if (doAjax) TS_JQ.ajax({ url: 'includes/ajax/update_history.php', type: 'POST', data: serData, dataType: 'script', async: as, complete: comp });
	else if (action == 'getall') {
		var allHist = TS_JQ.ajax({ url: 'includes/ajax/update_history.php', type: 'POST', data: serData, dataType: 'html', async: false}).responseText;
		if (allHist == 'timeout') createDialog('An Error Has Occurred!','You are currently not logged in. Please log in and try your request again.','error',5000,{modal:true});
		else {
			if (allHist != '') showHistoryDetails('',allHist,true);
			TS_JQ('#dialogDiv *[title!=\'\']').tipTip({ maxWidth: 'auto', defaultPosition: 'bottom', edgeOffset: 8, delay: 200, fadeOut: 400 });
		}
	}
}
function showHistoryDetails(par,html,showAll) {
	if (par != '') {
		var lnk = TS_JQ(par+' .ui-icon-circle-arrow-e').attr('title');
		var desc = TS_JQ(par+' .histEvent').attr('title');
		var time = TS_JQ(par+' .ui-icon-clock').attr('title');
		time = time.replace(' ','</strong> at <strong>');
		var dialogHTML = '<p><strong>'+desc+'</strong> on <strong>'+time+'</strong>.</p><p>&nbsp;</p><p><button class="btnCls" onClick="TS_goToURL(\''+lnk+'\');">Go to page</button></p>';
	} else if (par == '' && html != '') var dialogHTML = html;
	if (dialogHTML != '') {
		var sa = (showAll === true) ? 650 : 'auto';
		var minW = (showAll === true) ? 650 : 300;
		var $diadiv = TS_JQ('#dialogDiv');
		$diadiv.dialog({'title': 'History Event Details', 'width': sa, 'height': sa, 'minWidth': minW, 'modal': true}).html(dialogHTML).dialog('open').find('.btnCls').button().end().parent().css({'padding':'3px 3px 20px'});
		TS_JQ('.ui-widget-overlay').click(function() { $diadiv.dialog('close'); });
		if (showAll === true) {
			TS_JQ('#fullhistoryList').find('.ui-icon-circle-arrow-e').click(function() { var liURL = TS_JQ(this).attr('title'); if (liURL != '') TS_goToURL(liURL); }).end().find('a').hover(function() { TS_JQ(this).addClass('ui-state-hover').css('border','none'); }, function () { TS_JQ(this).removeClass('ui-state-hover'); }).end().find('.ui-icon-trash').click(function(evnt) { evnt.preventDefault(); var tmp=TS_JQ(this).attr('id'); var id=tmp.substr(10); updateHistoryStatus('deletefromall',id); });
		}
	}
}
function errorHandler(xhr,txt,err) {
	var errTxt = '';
	if (txt == 'timeout') errTxt = 'Your request has timed out. Please try again.';
	else if (txt == 'error') {
		var det = '';
		var code = xhr.status;
		if (code == 401) det = 'You have unauthorized access to the request page.';
		else if (code == 403) det = 'The requested page is forbidden.';
		else if (code == 404) det = 'The requested page was not found on the server.';
		else if (code == 500) det = 'An Internal Server Error has occurred on the requested page.';
		errTxt = 'An error has occurred while trying to retrieve your request.<br><br>Error code: '+xhr.status+'<br>Error message: '+xhr.statusText+'<br>Additional detail: '+det;
	} else if (txt == 'notmodified') errTxt = 'A <em>&ldquo;not modified&rdquo;</em> error has occurred while trying to retrieve your request. Please try again.';
	else if (txt == 'parsererror') errTxt = 'A <em>&ldquo;parse error&rdquo;</em> error has occurred while trying to retrieve your request. Please try again.';
	createDialog('An Error Has Occurred!',errTxt,'error',0,{modal: true, width: 400});
}
//returns todays date formatted mm/dd/yyyy
function getTodaysDate(type) {
	var dteObj = new Date();
	var dteMo = (dteObj.getMonth())+1;
	var dteDay = dteObj.getDate();
	var dteYr = dteObj.getFullYear();
	if (type == 'full') return dteMo+'/'+dteDay+'/'+dteYr;
	else if (type == 'd' || type == 'day') return dteDay;
	else if (type == 'm' || type == 'mo') return dteMo;
	else if (type == 'y' || type == 'yr') return dteYr;
}
//comapares 2 string dates (mm/dd/yy or mm/dd/yyyy) and returns 1 if dte1>dte2, 0 if dte1=dte2 or -1 if dte1<dte2 
function compareDates(dte1,dte2) {
	var dteArr1=explode('/',dte1);
	var dteArr2=explode('/',dte2);
	dteArr1[0]=parseFloat(dteArr1[0]);
	dteArr2[0]=parseFloat(dteArr2[0]);
	dteArr1[1]=parseFloat(dteArr1[1]);
	dteArr2[1]=parseFloat(dteArr2[1]);
	dteArr1[2]=parseFloat(dteArr1[2]);
	dteArr2[2]=parseFloat(dteArr2[2]);
	var ret = -1;
	if (dteArr1[2]>dteArr2[2] || (dteArr1[2]==dteArr2[2] && (dteArr1[0]>dteArr2[0] || (dteArr1[0]==dteArr2[0] && dteArr1[1]>dteArr2[1])))) ret = 1;
	else if (dteArr1[0]==dteArr2[0] && dteArr1[1]==dteArr2[1] && dteArr1[2]==dteArr2[2]) ret = 0;
	return ret;
}
//likes or dislikes something. type={1-review,2-member,3-property,4-manager},id={id of thing being liked}, mID={id of member submitting. can be 1 if not logged in}, like={1-like, 0-dislike}
function likeDislikeAction(type,id,mID,like) {
	if (id < 1) return false;
	if (type<1 || type>4) type = 1;
	if (like > 0) like = 1;
	var data = 'type='+type+'&id='+id+'&mID='+mID+'&like='+like;
	TS_JQ.ajax({ url: 'includes/ajax/like_dislike_action.php', type: 'POST', data: data, dataType: 'script', async: true, beforeSend: function(e) { TS_JQ('#sstoolbarDiv').find('.loadingDiv').removeClass('ui-helper-hidden-accessible'); }, complete: function(xhr,txt) { TS_JQ('#sstoolbarDiv').find('.loadingDiv').addClass('ui-helper-hidden-accessible'); }, timeout: 5000, error: function(xhr,txt,err) { errorHandler(xhr,txt,err); } });
}
function insertSocialNetworkDiv(aftrDiv,cnt,txt,id1,id2,ili,clkEvnt,title,noLike) {
	if (noLike === null || noLike === undefined) noLike = false;
	var html = '<div id="sstoolbarDiv" class="ui-widget ui-widget-content noborder fltLeft clearFltLeft"><div class="fltLeft"><a href="#" class="sstoolbar-btn" title="Share this page on your favorite social network">Share</a></div><div class="likepanel fltLeft">';
	if (!noLike && ((ili && id1 != id2) || !ili)) html += '<a href="#" class="dislikeBtn ui-widget ui-state-default ui-corner-all" title="Dislike this '+title+'"><span class="icon"></span></a><a href="#" class="likeBtn" title="Like this '+title+'">Like</a><div class="loadingDiv ui-helper-hidden-accessible"><div class="loading-sml"></div></div>';
	if (!noLike) html += '<span class="likeCnt">'+cnt+'</span>&nbsp;<span class="likeCntTxt">'+txt+'</span>';
	html += '</div></div>';
	TS_JQ(html).insertAfter(aftrDiv);
	TS_JQ('.sstoolbar-btn').button({ icons: { primary: 'ui-icon-circle-plus' } }).append('<span class="btn-img"></span>').socialShareToolbar();
	if (!noLike) {
		TS_JQ('.likeBtn').button().prepend('<span class="icon"></span>').click(function(evnt) { evnt.preventDefault(); likeDislikeAction(clkEvnt[0],clkEvnt[1],clkEvnt[2],1); });
		TS_JQ('.dislikeBtn').hover(function() { TS_JQ(this).addClass('ui-state-hover'); }, function() { TS_JQ(this).removeClass('ui-state-hover'); }).mousedown(function() { TS_JQ(this).addClass('ui-state-active'); }).mouseup(function() { TS_JQ(this).removeClass('ui-state-active'); }).click(function(evnt) { evnt.preventDefault(); likeDislikeAction(clkEvnt[0],clkEvnt[1],clkEvnt[2],0); });
	}
}
function applyToolTipListeners() {
	TS_JQ('*[title!=\'\']').not('.ttLeft,.ttRight,.ttTop,.ttCustom,.ttNone,.ttInfo,.ttFocusRight,.ttFocusBottom').tipTip({ maxWidth: 'auto', defaultPosition: 'bottom', edgeOffset: 8, delay: 300, fadeOut: 400 });
	TS_JQ('.ttTop[title!=\'\']').tipTip({ maxWidth: 'auto', defaultPosition: 'top', edgeOffset: 8, delay: 300, fadeOut: 400 });
	TS_JQ('.ttRight[title!=\'\']').tipTip({ maxWidth: 'auto', defaultPosition: 'right', edgeOffset: 8, delay: 300, fadeOut: 400 });
	TS_JQ('.ttLeft[title!=\'\']').tipTip({ maxWidth: 'auto', defaultPosition: 'left', edgeOffset: 8, delay: 300, fadeOut: 400 });
	TS_JQ('.ttInfo[rel!=\'\']').tipTip({ maxWidth: '200px', attribute: 'rel', defaultPosition: 'bottom', edgeOffset: 8, delay: 700, fadeOut: 400 });
	TS_JQ('.ttFocusRight[title!=\'\']').tipTip({ activation: 'focus', maxWidth: '300px', defaultPosition: 'right', edgeOffset: 8, delay: 150, fadeOut: 200 });
	TS_JQ('.ttFocusBottom[title!=\'\']').tipTip({ activation: 'focus', maxWidth: '300px', defaultPosition: 'bottom', edgeOffset: 8, delay: 150, fadeOut: 200 });
}
function showGeneralMsg(title,cont,w,h,mw) {
	var $diadiv = TS_JQ('#dialogDiv');
	$diadiv.dialog({'title': title, 'width': w, 'height': h, 'minWidth': mw, 'modal': true}).html(cont).dialog('open').parent().css({'padding':'3px 3px 20px'});
	TS_JQ('.ui-widget-overlay').click(function() { $diadiv.dialog('close'); });
}
function showAnnouncement(id,isPropAdmin) {
	var obj=TS_JQ('#'+id).data('anncmtDetail');
	var cont='<p class=\"h4Cls\"><strong>Title:</strong> '+obj.title+'</p><p class=\"h4Cls\"><strong>Date posted:</strong> '+obj.date+'</p><p class=\"h4Cls\"><strong>Regarding Manager:</strong> '+obj.mgr+'</p><p>&nbsp;</p><p class=\"h4Cls\"><strong>Announcement:</strong> '+obj.content+'</p><p>&nbsp;</p>';
	if (isPropAdmin === true) {
		TS_JQ('#dialogDiv').unbind('dialogopen');
		cont += '<div><button id="chgAnnActive">Make Announcement '+((obj.active==1)?'Inactive':'Active')+'<span></span></button>&nbsp;<button id="editAnnouncement">Edit Announcement</button></div>';
		TS_JQ('#dialogDiv').bind('dialogopen',function() { TS_JQ('#chgAnnActive').button().click(function(evnt) { evnt.preventDefault(); editFunction('pdContent',this,'pa&act='+obj.active+'&annID='+id.substr(9)); }); TS_JQ('#editAnnouncement').button().click(function(evnt) { evnt.preventDefault(); TS_JQ('#dialogDiv').dialog('close'); editFunction('pdContent',this,'pa&annID='+id.substr(9)); }); });
	}
	showGeneralMsg('Property Announcement Details',cont,650,650,300);
}
function getLatestNews() {
	TS_JQ.ajax({ url: 'includes/ajax/latest_news_content.php', type: 'POST', data: '', dataType: 'script', async: true, beforeSend: function(e) { TS_JQ('#latestNews').find('.loading-med').parent().removeClass('ui-helper-hidden').end().find('ul').addClass('ui-helper-hidden'); }, complete: function(xhr,txt) { TS_JQ('#latestNews').find('.loading-med').parent().addClass('ui-helper-hidden').end().find('ul').removeClass('ui-helper-hidden'); }, timeout: 5000, error: function(xhr,txt,err) { errorHandler(xhr,txt,err); } });
}
function displayLatestNews(id) {
	var $itm = TS_JQ('#'+id);
	var title = ($itm.find('div').attr('title') != '') ? $itm.find('div').attr('title') : $itm.find('div').html();
	var cont='<p class=\"h4Cls\">'+$itm.data('latestNews').desc+'</p><p>&nbsp;</p><p class=\"h4Cls\">posted on: '+$itm.data('latestNews').date+'</p><p>&nbsp;</p>';
	showGeneralMsg(title,cont,500,400,300);
}
function getFeaturedProps() {
	TS_JQ.ajax({ url: 'includes/ajax/featured_props_content.php', type: 'POST', data: '', dataType: 'script', async: false, beforeSend: function(e) { TS_JQ('#featureContent').parent().find('.loading-med').parent().removeClass('ui-helper-hidden'); }, complete: function(xhr,txt) { TS_JQ('#featureContent').parent().find('.loading-med').parent().addClass('ui-helper-hidden') }, timeout: 5000, error: function(xhr,txt,err) { errorHandler(xhr,txt,err); } });
}
function divFader(id,idSW,fi,fo,dly) {
	var $divs = TS_JQ('#'+id+' div[id^='+idSW+']');
	var cnt = $divs.length;
	$divs.each(function(idx) { var next = (idx+2>cnt) ? 0 : idx+1; setInterval(function() { crossFade(TS_JQ('#'+id+' div:eq('+idx+')'),TS_JQ('#'+id+' div:eq('+next+')'),fo,fi); }, dly)  });
}
function crossFade(foObj,fiObj,foMS,fiMS) { TS_JQ(foObj).animate({opacity:0},foMS,'linear',divFadeIn(fiObj,fiMS)); }
function divFadeIn(obj,ms) { TS_JQ(obj).effect('fade',ms); }
function divFadeOut(obj,ms) { TS_JQ(obj).fadeOut(ms); }
function changeClass() { TS_JQ(this).toggleClass('ui-helper-hidden'); }
function deleteServerFile(txt,path,successFnc,failFnc) { 
	createDialog('Please Confirm!',txt,'none',0,{ modal:true, width: 300, buttons: { Cancel: function() { TS_JQ(this).dialog('close'); }, 'Delete': function() { TS_JQ(this).dialog('close'); TS_JQ.ajax({ url: 'includes/ajax/misc_functions.php', type: 'POST', data: 'type=filedelete&params='+path+'|'+successFnc+'|'+failFnc, dataType: 'script', async: true, beforeSend: function(e) {}, complete: function(xhr,txt) {}, timeout: 5000, error: function(xhr,txt,err) { errorHandler(xhr,txt,err); } }); }}}); }
function renameServerFile(dir,oldname,newname,successFnc,failFnc,custOkMsg,custFailMsg) {
	TS_JQ.ajax({ url: 'includes/ajax/misc_functions.php', type: 'POST', data: 'type=filerename&params='+dir+'|'+oldname+'|'+newname+'|'+successFnc+'|'+failFnc+'|'+custOkMsg+'|'+custFailMsg, dataType: 'script', async: true, timeout: 5000, beforeSend: function(e) {  }, complete: function(xhr,txt) {  }, error: function(xhr,txt,err) { errorHandler(xhr,txt,err); } });
}
function updateDatabase(tbl,pk,id,fld,fldtype,newval,successFnc,failFnc) {
	TS_JQ.ajax({ url: 'includes/ajax/misc_functions.php', type: 'POST', data: 'type=dbupdate&params='+tbl+'|'+pk+'|'+id+'|'+fld+'|'+fldtype+'|'+newval+'|'+successFnc+'|'+failFnc, dataType: 'script', async: true, timeout: 5000, beforeSend: function(e) {  }, complete: function(xhr,txt) {  }, error: function(xhr,txt,err) { errorHandler(xhr,txt,err); } });
}
function getPropertyCount(obj) {
    var count = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) count++;
    }
    return count;
}

//DOCUMENT READY FUNCTIONS
TS_JQ(function() {
	//load ie specific javascript file if client is using an ie browser
	if (TS_JQ('body').hasClass('ie')) TS_JQ.getScript('includes/js/ie_fixes.js');
	//equalize element heights
	TS_JQ.fn.equalizeHeights = function() { return this.height( Math.max.apply(this, TS_JQ(this).map(function(i,e){ return TS_JQ(e).height() }).get() ) ) }
	//share social network plugin. inspired by shareIt plugin http://joohi.hu/shareit
	TS_JQ.fn.extend({
		socialShareToolbar: function(optsin) {
			var self = TS_JQ(this),
			options = TS_JQ.extend({
				title: "Share this page",
				icons: [
					['http://www.facebook.com/sharer.php?u='+document.location,'i/socialnetwork_icons/facebook.png','Facebook'],
					['http://www.linkedin.com/shareArticle?mini=true&url='+document.location,'i/socialnetwork_icons/linkedin.png','LinkedIn'],
					['http://twitter.com/home?status=Currently reading '+document.location,'i/socialnetwork_icons/twitter.png','Twitter'],
					['http://digg.com/submit?url='+document.location,'i/socialnetwork_icons/digg.png','Digg'],
					['http://del.icio.us/post?url='+document.location,'i/socialnetwork_icons/delicious.png','Delicious']
				]
			}, optsin);
			var sstBox;
			function showShareBox() {
				TS_JQ("body").append(
					sstBox = TS_JQ('<div id="ssharetbar-box" class="ssharetbar-box ui-widget ui-widget-content ui-corner-all"><h2 class="ui-widget-header ui-corner-all">'+options.title+'</h2></div>')
				);
				sstBox.css("left", TS_JQ(self).offset().left+"px");
				sstBox.css("top", TS_JQ(self).offset().top+TS_JQ(self).height()+6+"px");
				TS_JQ(options.icons).each(function() {
					sstBox.append('<a href="'+this[0]+'" class="gen" target="_blank"><img src="'+this[1]+'" /><span>'+this[2]+'</span></a>');
				});
				TS_JQ("*").bind("click.socialShareToolbar", function() {
					TS_JQ(".ssharetbar-box").remove();
					TS_JQ("*").unbind("click.socialShareToolbar");
				});
			}
			function doIt() {
				self.click(function(evnt) {
					evnt.preventDefault();
					showShareBox();
					return false;
				});
			}
			doIt();
		}
	});
});

