﻿// JavaScript Document
/*
\\ Transaction Framework
\\ Coded & Maintained by: Scott Crowley
\\ All code & concepts 2010 SC Designs
\\ v1.5 02/13/2011
*/
//whether or not to use a debug div in the page. if true, info can be placed in div with TS_JQ('#ts_debugDiv').append('msg');
var ts_debug = false;
//Assign jQuery to variable for use in other scripts
if (jQuery !== null && jQuery !== undefined) var TS_JQ = jQuery.noConflict();
//various message & functional containers that can be used and place in a page using jquery
var ts_loadingContainer = '<div id="ts_loadingContainer"><div class="ts_loadingMed"></div></div></div>';
var ts_debugContainer = '<div id="ts_debugDiv" style="background-color:#eeeeee; border:2px solid #333333; width:350px; margin:20px auto; padding:10px;"></div>';
var ts_msgContainer = '<div id="ts_msgDialog"></div>';
var ts_alertContainer = '<div id="ts_alertDialog" title="Alert"></div>';
var ts_confirmContainer = '<div id="ts_confirmDialog"></div>';
if (TS_JQ) {
	TS_JQ(function() {
		if (ts_debug === true) TS_JQ(document.body).prepend(ts_debugContainer);
	});
	//centers an element on screen. topDivdr is how much to divide top margin by. ie. if you want it a 1/4 from top, use 4
	function centerElementOnScreen(selector,topDivdr) {
		TS_JQ(document).scrollTop(0);
		if (topDivdr === undefined || topDivdr === null) topDivdr = 2;
		var window_width = TS_JQ(window).width();
		var window_height = TS_JQ(window).height();
		var element_height = TS_JQ(selector).outerHeight();
		var element_width = TS_JQ(selector).outerWidth();
		var top = (window_height-element_height)/topDivdr;
		var left = (window_width-element_width)/2;
		TS_JQ(selector).css({'top' : top , 'left' : left});
	}
	//allows you to write debug info to the ts_debugDiv
	function ts_debugMsg(msg) {
		if (ts_debug === false || msg == '') return null;
		TS_JQ('#ts_debugDiv').append(msg);
	}
	//---Override Javascript's Alert Dialog
	function alert(msg) {
		var isDiv = TS_JQ('#ts_alertDialog').is('div');
		if (isDiv === false) TS_JQ(document.body).append(ts_alertContainer);
		TS_JQ('#ts_alertDialog').html('<p>'+msg+'</p>').dialog({ close: function() { TS_JQ('#ts_alertDialog').html(''); } });
		//centerElementOnScreen('.ui-dialog',4);
	}
	//---Confirmation dialog function
	function ts_confirm(msg,title,yesFnc,noFnc) {
		if (title === undefined || title === null || title == '') title = 'Confirm';
		var isDiv = TS_JQ('#ts_confirmDialog').is('div');
		if (isDiv === false) TS_JQ(document.body).append(ts_confirmContainer);
		TS_JQ('#ts_confirmDialog').html('<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>'+msg+'</p>').dialog({
			resizable: false,
			height:175,
			modal: true,
			title: title,
			buttons: {
				"Yes": function() { TS_JQ('#ts_confirmDialog').html(''); TS_JQ(this).dialog('close'); if (yesFnc !== null) eval(yesFnc); },
				Cancel: function() { TS_JQ('#ts_confirmDialog').html(''); TS_JQ(this).dialog('close'); if (noFnc !== null) eval(noFnc);  }
			}
		});
		//centerElementOnScreen('.ui-dialog',4);
	}
	//creates new message to display
	//args: title=title of dialog box, msg=actual msg content(can be html), type=either 'none' or '' or 'error' or 'highlight',delay=ms to auto close dialog(0=bypass feature)
	//msgOptions: Must be an object containing at least one of the following:
	//msgOptions: {disabled(false),autoOpen(true),buttons({}),closeOnEscape(true),closeTxt(close),dialogClass(''),draggable(true),height(auto),hide(null),maxHeight(false),maxWidth(false),minHeight(150),minWidth(150),modal(false),postition(center),resizable(true),show(null),
	//msgOptions: stack(true),title(''),width(300),zIndex(1000)}
	function createDialog(title,msg,type,delay,msgOptions) {
		msgOptionsDflts = {disabled:false,autoOpen:true,buttons:{},closeOnEscape:true,closeTxt:'close',dialogClass:'',draggable:true,height:'auto',hide:null,maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:'center',resizable:true,show:null,stack:true,title:title,width:300,zIndex:1000}; //reset options to default
		if (typeof(msgOptions) == 'object') TS_JQ.extend(msgOptionsDflts,msgOptions);
		msgOptions = msgOptionsDflts;
		var modalClick = false;
		var isDiv = TS_JQ('#ts_msgDialog').is('div');
		if (delay == null || delay == undefined) delay = 0;
		if (isDiv === false) TS_JQ(document.body).append(ts_msgContainer);
		var $ts_msgDialog = TS_JQ('#ts_msgDialog');
		$ts_msgDialog.removeClass('ui-state-error').removeClass('ui-state-highlight');
		if (typeof(msgOptions) == 'object' && title != '') msgOptions.title = title;
		if (typeof(msgOptions) == 'object' && msgOptions.modal == 'click') {
			modalClick = true;
			msgOptions.modal = true;
		}
		var cls = '';
		if (type == 'error' || type == 'highlight') cls = (type == 'error') ? 'ui-state-error' : 'ui-state-highlight';
		if (cls != '' && msgOptions.dialogClass != null && msgOptions.dialogClass != '') msgOptions.dialogClass = msgOptions.dialogClass+' '+cls;
		else if (cls != '') msgOptions.dialogClass = cls;
		$ts_msgDialog.html(msg).dialog(msgOptions).addClass(cls);
		if (modalClick) TS_JQ('.ui-widget-overlay').click(function() { $ts_msgDialog.dialog('close'); });
		/*centerElementOnScreen('.ui-dialog',4);*/
		if (delay > 0) $ts_msgDialog.delay(delay).queue(function() { TS_JQ(this).dialog('close').dequeue(); });
	}
	//extend a form reset function
	TS_JQ.fn.clearForm = function() {
		return this.each(function() {
			var type = this.type, tag = this.tagName.toLowerCase();
			if (tag == 'form') return TS_JQ(':input',this).clearForm();
			if (type == 'text' || type == 'password' || tag == 'textarea') this.value = '';
			else if (type == 'checkbox' || type == 'radio') this.checked = false;
			else if (tag == 'select') this.selectedIndex = -1;
		});
	};
}
//simple redirect function. params: url to redirect to, type of redirect (parent, blank, self, etc). If no type is provided then 'parent' is used
//syntax to call function: TS_goToURL('index.html','blank');
function TS_goToURL() {
	var args = TS_goToURL.arguments;
	if (args.length == 1 || args[1] == '') {
		var url = args[0];
		var type = 'parent';
	} else {
		var url = args[0];
		var type = args[1];
	}
	if (type !='' && url != '') {
		if (type == 'blank') eval("window.open('"+url+"','_blank')");
		else eval(type+".location='"+url+"'");
	} else return false;
}
//standard jump menu function
function TS_jumpMenu(url,urlID,val) {
	if (val != '' && url != '' && urlID != '') {
		if (strpos(url,'?') !== false) var sp = '&';
		else var sp = '?';
		var gotoURL = url + sp + urlID + '=' + val;
		TS_goToURL(gotoURL);
	}
}
//display confirmation message before performing a redirect
function confirmBeforeRedirect() {
	var args = confirmBeforeRedirect.arguments;
	if (args.length < 2) return false;
	var msg = args[0];
	var url = args[1];
	var type = (args.length > 2 && args[2] != '') ? args[2] : '';
	if (msg != '' && url != '') {
		var ans = confirm(msg);
		if (ans === true) TS_goToURL(url,type);
	}
	return false;
}
//converts array of arguments received by another function and converts to a list of paramaters
function argToParam(argArr,offst) {
	var params = '';
	for (i=offst;i<argArr.length;i++) {
		if (typeof(argArr[i]) == 'object') params += argArr[i];
		else params += "'"+argArr[i]+"'";
		if (i+1 != argArr.length) params += ',';
	}
	return params;
}
//adds an event to an element
//Params: id=id of element to attach to or the actual element itself that you want to attach to, fnc=function to run when event is initiated, evnt=type of event to add to element(i.e. click,keyup,keydown,mouseover,mouseout,etc), xxx=any other params are sent as arguments to the fnc function
function addEvntHndlr() {
	var args = addEvntHndlr.arguments;
	if (args.length > 0) {
		var id = args[0];
		var fnc = args[1];
		var evnt = args[2];
		var params = argToParam(args,3);
		params = params.replace(/'this.value'/gi,'this.value');
		params = params.replace(/'this'/gi,'this');
	}
	if (typeof(id) == 'object') var el = id;
	else var el = document.getElementById(id);
	var fncName = fnc+"("+params+")";
	evntFnc = new Function(fncName);
	if (navigator.appName != 'Microsoft Internet Explorer') el.addEventListener(evnt,evntFnc,false);
	else el.attachEvent(evnt,evntFnc);
}
//adds or updates the value of a form element. won't change if element already has a value, unless override = true
//Params: id=id of element id to set value to, val=value to set
function setElementValue(id,val,type,override) {
	var el = document.getElementById(id);
	var ckBox = (type=='CHECKBOX_YN_TYPE' || type=='CHECKBOX_1_0_TYPE' || type=='CHECKBOX_-1_0_TYPE' || type=='CHECKBOX_TF_TYPE' || type=='CHECKBOX_VALUE_NULL_TYPE') ? true : false;
	var sel = (type=='SELECT_NUMERIC_TYPE' || type=='SELECT_STRING_TYPE') ? true : false;
	var elVal = (el !== null && el !== undefined) ? el.value : '';
	if (val != '' && ((sel) || (ckBox) || (elVal != '' && override === true) || (elVal == '' && !sel && !ckBox))) {
		if (ckBox) {
			var op = (type=='CHECKBOX_YN_TYPE') ? 'Y' : ((type=='CHECKBOX_1_0_TYPE') ? '1' : ((type=='CHECKBOX_-1_0_TYPE') ? '-1' : ((type=='CHECKBOX_TF_TYPE') ? 'T' : ((type=='CHECKBOX_VALUE_NULL_TYPE' && val != '') ? val : false))));
			if (val == op || (type=='CHECKBOX_1_0_TYPE' && val > 0) || (type=='1_0_TYPE' && val < 0)) el.checked = true;
		} else if (sel) {
			var selVal = (type=='SELECT_NUMERIC_TYPE') ? parseInt(val) : val;
			el.value = selVal;
		} else if (type == 'FILE_TYPE') {
			var spanName = id+'_display';
			var fileNameEl = document.getElementById(spanName);
			if (fileNameEl !== null && fileNameEl !== undefined) fileNameEl.innerHTML = val;
		} else if (el !== null && el !== undefined) el.value = val;
	}
}
//disables a form element
//Params: id=id of element id to disable
function disableFormElement(id) {
	var el = document.getElementById(id);
	el.disabled = true;
}
//used to cycle through various images using prev & next buttons. used with the TS_ListObjectGenerator class
//params: dir=direction(prev or next), prefx=container prefix, row=container row id, par=parent element images are located under
function imgcyle(dir,prefx,row,par,el) {
	var tmpID = '#'+prefx+row+' .'+par+' '+el;
	var disp = dispCnt = 0;
	var imgs = TS_JQ(tmpID);
	var total = imgs.length;
	var type = 'block';
	if (total < 2) return false;
	TS_JQ(imgs).each(function(idx) {
		var curDisp = (TS_JQ(this).css('display') == 'none') ? false : true;
		if (curDisp === true) {
			type = TS_JQ(this).css('display');
			disp = idx;
			TS_JQ(this).css('display','none');
			dispCnt ++;
		}
	});
	if (dispCnt == total && disp == total - 1) dispNxt = (dir == 'next') ? 1 : total - 1;
	else if (dir == 'prev' && disp == 0) dispNxt = total - 1;
	else if (dir == 'next' && disp == (total - 1)) dispNxt = 0;
	else dispNxt = (dir == 'next') ? disp + 1 : disp - 1;
	TS_JQ(imgs[dispNxt]).css('display',type);
}
//used to show a lightbox pertaining to a certain row of data.
//params: row=id for the current row (inc "#"), par=parent element class or id (inc "#" or "."), id=id of the clicked element
function dispImgLB(row,par,id) {
	var curSrc = TS_JQ('#'+id).attr('rel'); //current clicked image src
	var allImgs = TS_JQ(row+' '+par+' img'); //all images within parent
	var imgCnt = allImgs.length;
	var cur = 0; //current clicked image
	var imgArr = new Array();
	if (imgCnt > 0) {
		for(i=0;i<imgCnt;i++) {
			var tmpSrc = TS_JQ(allImgs[i]).parent().attr('rel');
			var tmpTitle = TS_JQ(allImgs[i]).parent().attr('title');
			if (tmpSrc == curSrc) cur = i;
			var tmpArr = new Array();
			tmpArr[0] = tmpSrc;
			tmpArr[1] = tmpTitle;
			imgArr[i] = tmpArr;
		}
	}
	TS_JQ.slimbox(imgArr,cur,{ overlayOpacity:overlayOpacity, fadeDur:fadeDur, resizeDuration:resizeDuration, initialWidth:initialWidth, initialHeight:initialHeight, imageFadeDuration:imageFadeDuration, captionAnimationDuration:captionAnimationDuration, counterText:counterText, loop:loop});
}
//Uses jQuery to dynamically add alternating table rows based on the passed arguments.
//params: tbl=table class to apply to, e=even row class name, o=odd row class name, h=hover class name, sf=boolean to skip 1st row, sl=boolean to skip last row, uh=boolean to use hover class
function altTableRows(tbl,e,o,h,sf,sl,uh) {
	var $tblObj = TS_JQ('.'+tbl);
	var odd = ($tblObj.find('tr').length%2 != 0) ? true : false;
	var el = (odd === false && sl === true) ? ':not(:last)' : '';
	var of = (sf === true) ? ':gt(0)' : '';
	var ol = (odd === true && sl === true) ? ':not(:last)' : '';
	if (uh === true) {
		var tf = (sf === true) ? ':gt(0)' : '';
		var tl = (sl === true) ? ':not(:last)' : '';
		$tblObj.find('tr'+tf+tl).mouseover(function(){ TS_JQ(this).addClass(h); }).mouseout(function(){ TS_JQ(this).removeClass(h); });
	}
	$tblObj.find('tr:nth-child(even)'+el).addClass(e);
	$tblObj.find('tr:nth-child(odd)'+of+ol).addClass(o);
}
//Updates a pager display div with the current page information. uses jQuery
//params: id=the element id that contains the pager display, cp=current page, lp=total pages, size=row disp size, trc=total number of rows
function updatePagerDisplay(parentid,contClass,cp,lp,size,trc) {
	if (trc > 0) {
		TS_JQ(parentid+' '+contClass).removeClass('ui-helper-hidden');
		cp = parseFloat(cp);
		lp = parseFloat(lp);
		size = parseFloat(size);
		trc = parseFloat(trc);
		var fpr = ((cp-1) * size)+1;
		var lpr = (fpr+size > trc) ? trc : (fpr + size)-1;
		TS_JQ(parentid+' '+contClass+' .pgr_cp').text(cp);
		TS_JQ(parentid+' '+contClass+' .pgr_lp').text(lp);
		TS_JQ(parentid+' '+contClass+' .pgr_fpr').text(fpr);
		TS_JQ(parentid+' '+contClass+' .pgr_lpr').text(lpr);
		TS_JQ(parentid+' '+contClass+' .pgr_trc').text(trc);
	} else TS_JQ(parentid+' '+contClass).addClass('ui-helper-hidden');
}
//Updates a pager button div with the current btn active status. switches class names depending which page the list is on. uses jQuery
//params: id=the element id that contains the pager btns,first btn class, prev btn class, next btn class, last btn class, cp=current page, lp=total pages
function updatePagerBtnStatus(parentid,contClass,fCls,pCls,nCls,lCls,cp,lp) {
	var useTheme = (TS_JQ(parentid).data('useTheme')) ? TS_JQ(parentid).data('useTheme') : false;
	if (cp == 1) {
		if (useTheme) TS_JQ(parentid+' '+contClass+' .pgNav:eq(0), '+parentid+' '+contClass+' .pgNav:eq(1)').addClass('ui-state-disabled');
		else {
			TS_JQ(parentid+' '+contClass+' '+fCls).removeClass(fCls.substr(1)).addClass(fCls.substr(1)+'_dis').css('cursor','default');
			TS_JQ(parentid+' '+contClass+' '+pCls).removeClass(pCls.substr(1)).addClass(pCls.substr(1)+'_dis').css('cursor','default');
		}
	} else {
		if (useTheme) TS_JQ(parentid+' '+contClass+' .pgNav:eq(0), '+parentid+' '+contClass+' .pgNav:eq(1)').removeClass('ui-state-disabled');
		else {
			TS_JQ(parentid+' '+contClass+' '+fCls+'_dis').removeClass(fCls.substr(1)+'_dis').addClass(fCls.substr(1)).css('cursor','pointer');
			TS_JQ(parentid+' '+contClass+' '+pCls+'_dis').removeClass(pCls.substr(1)+'_dis').addClass(pCls.substr(1)).css('cursor','pointer');
		}
	}
	if (cp == lp) {
		if (useTheme) TS_JQ(parentid+' '+contClass+' .pgNav:eq(2), '+parentid+' '+contClass+' .pgNav:eq(3)').addClass('ui-state-disabled');
		else {
			TS_JQ(parentid+' '+contClass+' '+nCls).removeClass(nCls.substr(1)).addClass(nCls.substr(1)+'_dis').css('cursor','default');
			TS_JQ(parentid+' '+contClass+' '+lCls).removeClass(lCls.substr(1)).addClass(lCls.substr(1)+'_dis').css('cursor','default');
		}
	} else {
		if (useTheme) TS_JQ(parentid+' '+contClass+' .pgNav:eq(2), '+parentid+' '+contClass+' .pgNav:eq(3)').removeClass('ui-state-disabled');
		else {
			TS_JQ(parentid+' '+contClass+' '+nCls+'_dis').removeClass(nCls.substr(1)+'_dis').addClass(nCls.substr(1)).css('cursor','pointer');
			TS_JQ(parentid+' '+contClass+' '+lCls+'_dis').removeClass(lCls.substr(1)+'_dis').addClass(lCls.substr(1)).css('cursor','pointer');
		}
	}
	if (useTheme) {
		TS_JQ('div.pgNav.ui-state-disabled').removeClass('ui-state-hover');
		TS_JQ('div.pgNav').removeClass('ui-state-active').unbind('mouseenter mouseleave');
		TS_JQ('div.pgNav').not('.ui-state-disabled').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'); });
	}
}
//php equivalent for is_array()
function is_array(val) {
	return (val instanceof Array)
}
//check all or no checkboxes.
//params: sel=complete jquery selector, action=either 'all' or 'none'
function ts_checkAllNone(sel,action) {
	if (sel == '') return false;
	var act = (action == 'none') ? false : true;
	TS_JQ(sel).each(function() { TS_JQ(this).attr('checked',act); });
	return true;
}
