/*!
 * Subscribe-HR javascript API library
 * Based on JQuery
 *
 * Copyright (c) 2009 Subscribe-HR
 *
 */

/**
 * Scrollable - enables scrollable divs
 *
 */
;(function($){
	
	$.fn.scrollable = function(pixles, duration, options){
	
		var cont = $(this);
		var chld = $(this).children();
		var btNext = $(options.nextButton);
		var btPrev = $(options.previousButton);
		
		//check if we are at the top or bottom and disable/enable scroll buttons accordingly
		reachedTop(cont, pixles, btNext, btPrev);
		
		var chldHeight = 0;
		$.each(chld, function() {
			chldHeight += $(this).height();
		});
		
		if (chldHeight <= pixles) {
			btNext.hide();
		}
		
		btNext.click(function() {			
			cont.scrollTo('+='+pixles, duration);
			reachedBottom(cont, pixles, btNext, btPrev);
			return false;
		});
				
		btPrev.click(function() {
			cont.scrollTo('-='+pixles, duration);
			reachedTop(cont, pixles, btNext, btPrev);
			return false;
		});		
	};
	
	reachedTop = function(elem, pixles, btNext, btPrev){
		if (elem.scrollTop() - pixles <= 0) {
			btPrev.hide();
		} else {
			btPrev.show();
		}
		
		btNext.show();
	};
	
	reachedBottom = function(elem, pixles, btNext, btPrev){
		if ((elem[0].scrollHeight - elem.scrollTop() - pixles) <= elem.outerHeight()) {
			btNext.hide();
		} else {
			btNext.show();
		}
		btPrev.show();
	};
	
})( jQuery );

var Subscribe = {
};

Subscribe.Base = {

	Init : function() {
		//Subscribe.Base.EnableTabs();
		Subscribe.Base.EnableHideButton();
		Subscribe.Base.EnableBoolean();
		Subscribe.Base.EnableDatepicker();
		Subscribe.Base.EnableChecklists();				
		Subscribe.Base.EnableSearch();
		Subscribe.Base.EnableAttachments();
		Subscribe.Base.EnableCharts();
		//Subscribe.Base.EnableSearchSorting();
		
		//enable customer drop down
		$('#module-customers-dropdown a').click(function() {
			$('#customer-selector').attr('value', $(this).attr('href'));
			$('#customer-selector-form').submit();
			return false;
		});
		
		//stretch main content if the menu is disabled
		if ($('#menu-list').css('display') == 'none') {
			$('#content').removeClass('content-with-menu');
			$('#content').addClass('content-without-menu');
		}
		
		//quick search enter key fix
		$('input.search-local-input').keydown(function(event){		
			if (event.keyCode == 13) {
				var parentFrm = $(this).closest('form');
				//parentFrm.append($('<input/>').attr('type', 'hidden').attr('name', parentFrm.attr('id') + '_search_enter'));
				parentFrm.append($('<input/>').attr('type', 'hidden').attr('name', 'search_enter'));
				parentFrm.submit();
				return false;
			}
		});
		
		//customer selector
		if ($('#customer-selector') != null) {
			$('#customer-selector').change(function() {
				$('#customer-selector-form').submit();
			});
		}
		
		$('input[name="delete"]').click(function() {
		
			if (confirm("Are you sure you want to delete this record?")) {
				return true;
			}
			
			return false;
		});
		
		$('#delete-form').click(function() {
		
			if (confirm("Are you sure you want to delete all the selected records?")) {
				return true;
			}
			
			return false;
		});
		
		//form select all checkboxes
		$('#frm-select-all').click(function() {
			if ($(this).attr('checked')) {
				$('input[name="searchSelect[]"]').attr('checked', true);
			} else {
				$('input[name="searchSelect[]"]').attr('checked', false);
			}
		});
		
		//enable help lightbox
		var helpLB = $('#help-light-box');
		if (helpLB != undefined) {
			var dlg = helpLB.dialog({
				modal: true,
				dialogClass: 'help-box-style',
				bgiframe: true,
				autoResize: false,
				width: 446,
				height: 328, //284
				draggable: false,
				resizable: false,
				title: 'Welcome to Subscribe-HR',
				buttons: { 
					"Ok": function() { 
						$(this).dialog("close");
					},
					
					"Do Not Show Again": function() {
						$.ajax({
							type: 'POST',
							url: $('#mod-url').attr('value') + '/misc/',
							dataType: 'json',
							data: 'ajaxRequest=1&request=disableHelp'
						});
						$(this).dialog("close");
					}
				}
			});
		}
	},

	//enables tabs on domain object forms
	EnableTabs : function() {
		var tabs = $('#form-tabs').tabs();
		tabs.bind('tabsselect', function(event, ui) {
		
			//get location url
			/*var url = window.location.toString();
			
			//remove anchor from url
			var anchor = url.indexOf('#');
	    	if (anchor != -1) {
	    		url = url.substring(0, anchor);
	    	}
        	
        	//make tab bookmarkable
        	document.location = url + '#' + ui.panel.id;*/
        });
	},
	
	//enables search form sorting fields
	EnableSearchSorting : function() {
		$('a.search-label-link, a.search-label-link-asc, a.search-label-link-desc').click(function(){
			var sLbl = $(this);
			var sLblSrt = $('#' + sLbl.attr('id') + '_sort');
			var sortClass = sLbl.attr('class');
			
			if (sortClass == 'search-label-link-asc') {
				sLblSrt.attr('value', 'desc');
			} else if (sortClass == 'search-label-link-desc') {
				sLblSrt.attr('value', 'none');
			} else {
				sLblSrt.attr('value', 'asc');
			}

			sLbl.closest('form').submit();
			return false;
		});
	},
	
	//enables tabs on domain object forms
	EnableHideButton : function() {
		if ($('#main-menu-hide-button') != null) {
			$('#main-menu-hide-button').click(function() {
				var menuList = $('#menu-list');
				var content = $('#content');
				if (content.attr('class') == 'content-without-menu') {
					$('#menu-list').show('drop');
					//.switchClass('content-without-menu', 'content-with-menu') - IE8's got issues with this one
					$('#content').removeClass('content-without-menu').addClass('content-with-menu');
					Subscribe.Base.UpdateButtonState(0);
				} else {
					//.switchClass('content-with-menu', 'content-without-menu') - IE8's got issues with this one
					$('#content').removeClass('content-with-menu').addClass('content-without-menu');
					$('#menu-list').hide('drop');
					Subscribe.Base.UpdateButtonState(1);
				}
			});
		}
	},
	
	EnableDocumentGenerator : function() {
		$('.create-document').click(function() {
			
			$('<div id="document-top-container"><div id="document-container" class="float-left" style="width: 100%"><div class="img-loading float-left"></div><div class="float-left" style="padding: 1px 0 0 2px; font-weight: bold;">Loading...</div></div></div>').dialog({		
				modal: true,
				bgiframe: true,
				draggable: false,
				resizable: false,
				closeOnEscape: false,
				title: 'Select Document Template',
				width: 500,
				height: 30,
				open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
				buttons: { 
					"Ok": function() {
						
						var tmpl = $('#select-document-template').val();
						if (tmpl) {
							document.location = $('#mod-url').attr('value') + '/misc/?ajaxRequest=1&request=getObjectDocumentFile&objectName=' + $('#cdon').val() + '&objectId=' + $('#cdo').val() + '&objectId=' + $('#cdo').val() + '&templateId=' + tmpl;
						}
						
						$(this).dialog("close");
						$('#document-top-container').remove();						
					}
				}
			});
			
			$.ajax({
				type: 'POST',
				url: $('#mod-url').attr('value') + '/misc/',
				dataType: 'json',
				data: 'ajaxRequest=1&request=getObjectDocuments&objectName=' + $('#cdon').val(),
				success: function(res){
					if (res.html) {
						$('#document-container').html(res.html);
					}
				}
			});
			
			
			return false;
		});
	},
	
	//enables tabs on domain object forms
	UpdateButtonState : function(state) {
		$.ajax({
			type: 'POST',
			url: $('#mod-url').attr('value') + '/misc/',
			dataType: 'json',
			data: 'ajaxRequest=1&request=updateMenuState&state='+state
		});
	},	

	//enables tools dropdown - use on any theme with tools dropdown box
	EnableTools : function() {
		var elm = $('#module-navigation-tools-dropdown-container');
		$('#module-navigaton-tools').click(function(){
			var pos = $(this).position();
			elm.css('left', pos.left);
			elm.css('top', pos.top + 54);
			elm.css('display', 'block');	
		});
		
		elm.mouseleave(function(){
			elm.css('display', 'none');
		});
		
		$(document).click(function(event){
			if (event.target.id != 'module-navigaton-tools') {
				elm.css('display', 'none');
			}
		});
	},	

	//enables customers dropdown - use on any theme with tools dropdown box
	EnableCustomers : function() {
		var elm = $('#module-customers-container');
		$('#module-customers').click(function(){
			var pos = $(this).position();
			elm.css('left', pos.left);
			elm.css('top', pos.top + 54);
			elm.css('display', 'block');	
		});
		
		elm.mouseleave(function(){
			elm.css('display', 'none');
		});
		
		$(document).click(function(event){
			if (event.target.id != 'module-customers') {
				elm.css('display', 'none');
			}
		});
	},
	
	//enables customers dropdown - use on any theme with tools dropdown box
	EnableIdentities : function() {
		var elm = $('#module-identity-container');
		$('#module-identity').click(function(){
			var pos = $(this).position();
			elm.css('left', pos.left);
			elm.css('top', pos.top + 19);
			elm.css('display', 'block');	
		});
		
		elm.mouseleave(function(){
			elm.css('display', 'none');
		});
		
		$(document).click(function(event){
			if (event.target.id != 'module-identity') {
				elm.css('display', 'none');
			}
		});
		
		//enable customer drop down
		$('#module-identity-dropdown a').click(function() {
			
			if ($(this).hasClass('current-group')) {
				return false;
			}
		
			if (confirm('You are about to switch groups. If you switch groups your permissions will be altered. It will affect what you see and do. Please click OK if you would like to proceed.')) {
				$('#identity-selector').attr('value', $(this).attr('href'));
				$('#identity-selector-form').submit();
			}
			return false;
		});
	},
	
	//enables all attachment elements on the form
	EnableAttachments : function() {
		$.each($('.attachment-default'), function() {
			var bttn = $(this);
			new AjaxUpload(bttn, {
				action: bttn.attr('href'), 
				name: 'attachment',
				responseType: 'json',
				onSubmit : function(file, ext){			
					$('#__ld_' + bttn.attr('id')).addClass('img-loading');
					this.disable();
				},
				onComplete: function(file, response){
					$('#__ld_' + bttn.attr('id')).removeClass('img-loading');
					this.enable();
					if (response.type != null) {
						
						//images
						if (response.type == 'image') {
							$('#_ai_' + bttn.attr('id')).attr('src', response.link.replace(/amp;/g, ''));
							$('#_ai_' + bttn.attr('id')).css('display', '');	
						//couments
						} else {
							if ($('#_al_' + bttn.attr('id')).hasClass('attachment-replace')) {
								$('#_al_' + bttn.attr('id')).empty();
							}						
							$('#_al_' + bttn.attr('id')).append($('<li></li>').append($('<a></a>').attr('href', response.link.replace(/amp;/g, '')).html(response.label)));
							$('#_al_' + bttn.attr('id')).css('display', '');
						}
					}
				}
			});
		});
		
		$('a.remove-attachment').click(function() {
			var bttn = $(this);
			$.ajax({
				type: 'POST',
				url: bttn.attr('href'),
				dataType: 'html'
			});
			bttn.parent().remove();
			return false;
		});
	},
	
	//enables all checklists
	EnableChecklists : function() {
		$.each($('select.input-checklist-default'), function() {
			if ($(this).is(":visible")) {		
				$(this).toChecklist({
					addSearchBox : true,
					searchBoxText : 'Quick list search...'
				});
			}
		});
	},
	
	//enables all checklists
	EnableDatepicker : function() {
		$.each($('input.input-datepicker-default'), function() {
			var format = $('#date-format').attr('value');
			$(this).datepicker({
				changeMonth: true,
				changeYear: true,
				dateFormat: format,
				//constrainInput: false,
				yearRange: '-19:+19'
			});
		});
	},
	
	//enables all boolean fields
	EnableBoolean : function() {
		$.each($('input.boolean-default'), function() {		
			var boolF = $(this);
			boolF.click(function(){
				if (boolF.attr('checked')) {
					$('#' + boolF.attr('id').replace('_checkbox', '')).attr('value', 1);
				} else {
					$('#' + boolF.attr('id').replace('_checkbox', '')).attr('value', 0);
				}
			});
		});
	},
	
	//enables global search
	EnableSearch : function(formName, tabId) {
		$('#header-search-go').click(function() {
			$('#global-search').submit();
		});
		
		var modUrl = $('#mod-url').attr('value');
		$('#header-search-input').autocomplete(modUrl + '/search/', {
			width: 180,
			max: 20,
			highlight: false,
			scroll: true,
			scrollHeight: 300,
			matchContains: true,
			dataType: 'json',
			parse: function(data) {
			    var rows = new Array();
			    for(var i=0; i<data.length; i++){
			        rows[i] = { data:data[i], value:data[i].id + '|' + data[i].doo, result:data[i].res };
			    }
			    return rows;
			},
			formatItem: function(row, i, n) {
				return row.res + ' <b>[' + row.grp + ']</b>';
			}
		}).result(function(event, data, formatted) { 
			$('#global-search-options').attr('value', formatted);
			$('#global-search').submit(); 
		});
	},
	
	//enable flash charts
	EnableCharts : function() {
	
		var modUrl = $('#mod-url').attr('value');
		$.each($('div.flash-graph'), function() {
		
			var flashCont = $(this);
			var modUrl = $('#mod-url').attr('value');		
			var graphTypeEl = $('#' + flashCont.attr('id') + '_graph_type');
			var graphCountEl = $('#' + flashCont.attr('id') + '_count_graph');
			var graphCount = 0;
			var dbGraph = 0;
			if (graphCountEl.attr('type') == 'hidden') {
				dbGraph = 1;
			}
			if (graphCountEl.attr('checked') || (dbGraph && graphCountEl.attr('value') == 1)) {
				graphCount = 1;
			}
			var chartType = graphTypeEl.attr('value');
			var chart = Subscribe.Base.CreateChart(chartType, flashCont.attr('name'), flashCont.attr('id'), graphCount, dbGraph);
			
			//inject flash content
			flashCont.html(chart);				
			
			//graph type change triggered
			graphTypeEl.change(function(){
				
				//create new chart
				var chart = Subscribe.Base.CreateChart($(this).attr('value'), flashCont.attr('name'), flashCont.attr('id'), graphCountEl.attr('checked'), dbGraph);
				
				//inject flash content
				flashCont.html(chart);
			});
			
			//graph count click triggered
			graphCountEl.click(function(){
				
				if ($(this).attr('checked')) {
					//create new chart
					var chart = Subscribe.Base.CreateChart(graphTypeEl.attr('value'), 'single', flashCont.attr('id'), 1, dbGraph);
				} else {
					//create new chart
					var chart = Subscribe.Base.CreateChart(graphTypeEl.attr('value'), flashCont.attr('name'), flashCont.attr('id'), 0, dbGraph);
				}				
				
				//inject flash content
				flashCont.html(chart);
			});
			
			//export triggered
			if ($('#reportExportLink') != null) {	
				$('#reportExportLink').click(function() {
					var exportOpt = $('#exportOption').attr('value');
					var sw = 'export-pdf';
					if (exportOpt == 'excel') {
						var sw = 'export-excel';	
					}
				
					$('#reportExportLink').attr('href', modUrl + '/report/edit/' + sw + '/' + flashCont.attr('id').replace('report', '') + '/?exportOptions=' + exportOpt + '&graphType=' + graphTypeEl.attr('value') + '&recordCount=' + graphCountEl.attr('checked') + '&noGr=' + $('#_do_not_export').attr('checked'));
				});
			}
			
			$('#exportOption').change(function() {
				var tv = $(this).attr('value');
				if (tv == 'pdfportrait' || tv == 'pdflandscape') {
					$('#_do_not_export_tr').show();
				} else {
					$('#_do_not_export_tr').hide();
				}
			});
			
		});
		
		//export triggered
		if ($('#reportExportLink') != null && $('#report-id').attr('value') != null) {	
			$('#reportExportLink').click(function() {
				var exportOpt = $('#exportOption').attr('value');
				var sw = 'export-pdf';
				if (exportOpt == 'excel') {
					var sw = 'export-excel';
				}
			
				$('#reportExportLink').attr('href', modUrl + '/report/edit/' + sw + '/' + $('#report-id').attr('value') + '/?exportOptions=' + exportOpt + '&graphType=0&recordCount=' + $('#report' + $('#report-id').value + '_count_graph').attr('checked'));
			});
		}
		
		
	},
	
	//enable flash charts
	EnableChart : function(flashCont, dbChart) {
	
		var modUrl = $('#mod-url').attr('value');		
		var graphTypeEl = $('#' + flashCont.attr('id') + '_graph_type');
		var graphCountEl = $('#' + flashCont.attr('id') + '_count_graph');
		var graphCount = 0;
		if (graphCountEl.attr('checked')) {
			graphCount = 1;
		}
		var chartType = graphTypeEl.attr('value');
		var chart = Subscribe.Base.CreateChart(chartType, flashCont.attr('name'), flashCont.attr('id'), graphCount, dbChart);
		
		//inject flash content
		flashCont.html(chart);			
	},
	
	
	//create new flash chart object
	CreateChart : function(chartType, series, chartId, countOnly, dbGraph) {
	
		var chartFile = Subscribe.Base.GetChartType(chartType, series);
		var width = 771;
		if ($('#' + chartId + '_db').attr('value')) {
			width = 375;	
		}
		var stUrl = $('#static-common').attr('value');
		var modUrl = $('#mod-url').attr('value');
		var flashFile = $.flash({
			swf: stUrl + '/Common/Fusion/' + chartFile,
			width: width,
			height: 330,				
			hasVersion: 10,
			expressInstaller: stUrl + '/Common/Fusion/expressInstall.swf',
			params: {
				wmode: 'opaque',
				bgcolor: '#ffffff'
			},
			flashvars: {
				chartWidth: width,
				chartHeight: 330,
				DataURL: modUrl + '/graph/swf/' + chartId + '/?type=' + chartType + '&count=' + countOnly + '&dbGraph=' + dbGraph
			}				
		});
		
		return flashFile;
	},
	
	//enable flash charts
	GetChartType : function(code, series) {		
		if (series == 'single') {
			var graphFile = 'FCF_Column3D.swf';
		} else {
			var graphFile = 'FCF_MSColumn3D.swf';
		}
		
		if (code == 'barchart') {
			if (series == 'single') {
				return 'FCF_Column2D.swf';
			} else {
				return 'FCF_MSColumn2D.swf';
			}
		} else if (code == 'linechart') {
			return 'FCF_MSLine.swf';
		} else if (code == 'areachart') {
			return 'FCF_MSArea2D.swf';
		} else if (code == 'piechart') {
			return 'FCF_Pie2D.swf';
		} else if (code == '3dpiechart') {
			return 'FCF_Pie3D.swf';
		} else if (code == 'horizontalbarchart') {
			if (series == 'single') {
				return 'FCF_Bar2D.swf';
			} else {
				return 'FCF_MSBar2D.swf';
			}
		}
		
		return graphFile;
	},
	
	//show domain element
	Show : function(name) {
		var parent = $('#' + name).parent().parent();		
		if (parent.attr('class') == 'form-single-element-cell') {
			parent = parent.parent();
		}
		parent.show();
	},
	
	//hide domain element
	Hide : function(name) {		
		var parent = $('#' + name).parent().parent();
		if (parent.attr('class') == 'form-single-element-cell') {
			parent = parent.parent();
		}
		parent.hide();
	},
	
	//enable dropdown filter
	EnableDropDownFilter : function(elFilter, elFiltered) {

		if ($('#' + elFilter).length != 0) {		

			var elFd = $('#' + elFiltered);
			var fElN = '__fl_' + elFd.attr('id')
			var cloned = elFd.clone();			
			
			elFd.parent().append(
				cloned
					.css('display', 'none')
					.removeAttr('name')
					.attr('id', fElN)
			);
		
			//clean up class definition
			$.each(cloned.find('option'), function() {
				$(this).attr('class', $(this).attr('class').replace(/ /g,''));
			});
						
			//filter drop down options
			elFd.find('option[class!=id-' + $('#' + elFilter).attr('value').replace(/ /g,'') + '][value!=""]').remove();
		
			//.unbind('change')
			$('#' + elFilter).change(function() {
		
				//var elFdP = elFd.parent();
				//elFd.remove();
				//elFdP.append($('#' + fElN).clone().attr('id', elFiltered).attr('name', elFiltered).show());			
				//elFd = $('#' + elFiltered); 
			
				elFd.html($('#' + fElN).html());
			
		
				//elFd.empty();
				//$.each($('#' + fElN).find('option'), function() {
				//	elFd.append($(this).clone());
				//});
			
				//filter drop down options
				elFd.find('option[class!=id-' + $('#' + elFilter).attr('value').replace(/ /g,'') + '][value!=""]').remove(); 
			});
		}
	},
	
	//enable dropdown filter
	/*EnableDropDownFilter2 : function(elFilter, elFiltered) {		
		if (filter[elFiltered].length > 0) {
			var fOpt = 'id-' + $('#' + elFilter).attr('value');
			var fEl = $('#' + elFiltered).empty();
			for(var i=0; i<filter[elFiltered][fOpt].length; i++) {
				var oE = filter[elFiltered][fOpt][i];
				fEl.append($('<option></option>').val(oE.code).html(oE.value));
			}
		}
		
		$('#' + elFilter).change(function() {
		
			var fOpt = 'id-' + $('#' + elFilter).attr('value');
			var fEl = $('#' + elFiltered).empty();
			for(var i=0; i<filter[elFiltered][fOpt].length; i++) {
				var oE = filter[elFiltered][fOpt][i];
				fEl.append($('<option></option>').val(oE.code).html(oE.value));	
			}
		});
	},*/
	
	ShowErrorDialog : function(message) {
		var dlg = $('<div>' + message + '</div>').dialog({
			modal: true,
			bgiframe: true,
			autoResize: true,
			draggable: false,
			resizable: false,
			title: 'Notice',
			buttons: { 
				"Ok": function() { 
					$(this).dialog("close");
				}
			}
		});
	},
	
	ShowLoadingDialog : function(message) {
		$('<div><div id="form-loading-container" class="float-left" style="width: 100%"><div class="img-loading float-left"></div><div class="float-left" style="padding: 1px 0 0 2px; font-weight: bold;">Please wait while your request is being processed...</div></div></div>').dialog({		
			modal: true,
			bgiframe: true,
			draggable: false,
			resizable: false,
			closeOnEscape: false,
			title: 'Notice',
			width: 330,
			height: 50,
			open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); }
			
		});
	},
	
	//confirm remove
	ConfirmDialog : function(message, func) {			
		var dlg = $('<div>' + message + '</div>').dialog({
			modal: true,
			bgiframe: true,
			autoResize: true,
			draggable: false,
			resizable: false,
			title: 'Please Confirm',
			buttons: { 
				"Ok": function() {
					func();
					$(this).dialog("close");
				},
				
				"Cancel": function() { 
					$(this).dialog("close");
				}
			}
		});
	},
	
	//confirm remove
	ShowMiniDialog : function(cont, title, width, height, func) {			
		cont.dialog({
			modal: true,
			width: width,
			//height: height,
			autoResize: true,
			autoOpen: false,
			draggable: false,
			resizable: false,
			title: title,
			buttons: { 
				"Ok": function() {					
					if (func()) {
						//$(this).dialog("close");
					}
				},
				"Close": function() { 
					$(this).dialog("close"); 
				} 
			}
		}).dialog('option', 'title', title).dialog('open');
	},
	
	OpenPopup : function(url, width, height) {
		shrwindow = window.open(url, 'shrwindow', 'dependent,toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=' + width + ',height=' + height + ',left = 358,top = 134');
	},
	
	isEmail: function(value) {
    	// contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
    	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
	},
	
	//filter end time dropdown and remove elements that are before start time
	FilterEndTime : function(el1, el2) {

		//create hidden drop down with times
		if ($('#time-clone').length == 0) {
			$('body').append($('<select id="time-clone" style="display: none;"/>').html(el1.html()));
		}
		
		//restore original values
		var val = el1.attr('value');
		var el2V = el2.attr('value');
		el2.html($('#time-clone').html()).attr('value', '00:00');
		$.each(el2.find('option'), function(index, value) {
				if ($(this).attr('value') <= val) {
					$(this).remove();
				}
		});
		
		el2.append('<option value="24:00">24:00</option>');
		el2.attr('value', el2V);
	},
	
	TimeDifference : function(from, to) {
	
		var fromA = from.split(':');
		var toA = to.split(':');

		var fromD = new Date(2000, 0, 1, fromA[0], fromA[1]);
		var toD = new Date(2000, 0, 1, toA[0], toA[1]);
	
		var difference = toD.getTime() - fromD.getTime();
		var hoursDifference = difference / 1000 / 60 / 60;
		
		return hoursDifference;
    	
    	//daysDifference = Math.floor(difference/1000/60/60/24);
	    //hoursDifference = Math.floor(difference/1000/60/60);
		//minutesDifference = Math.floor(difference/1000/60);
	    //secondsDifference = Math.floor(difference/1000);
	},
	
	GetFormattedTime : function(date) {
		var hr = date.getHours(), min = date.getMinutes();
		if (hr < 10) {
			hr = '0' + hr;
		}
		
		if (min < 10) {
			min = '0' + min;
		}
		
		return hr + ':' + min;
	},
	
	GetFormattedDate : function(date) {
		
		var d = date.getDate(), m = date.getMonth(), y = date.getFullYear();
		
		if (d < 10) {
			d = '0' + d;
		}
		
		if (m < 10) {
			m = '0' + (m + 1);
		}
		
		return y + '-' + m + '-' + d;
	},
	
	FieldsToURL : function(cont) {
		var url = '';
		$.each(cont.find('input, select'), function() {
			var id = $(this).attr('id');
			var val = $(this).attr('value');
			if (id) {
				url += '&' + id + '=' + val;
			}
		});
		
		$.each(cont.find('textarea'), function() {
			var id = $(this).attr('id');
			var val = $(this).html();
			if (id) {
				url += '&' + id + '=' + val;
			}
		});
		
		return url;
	},
	
	EmptyFields : function(cont) {
		cont.find('input, select').attr('value', '');
		cont.find('textarea').html('');	
	},	
	
	EnableCountryStateFilter : function() {
		
		//check if it is a base or hourly salary
		var loc = $('#cb_location_country').val();
		var sr = $('#cb_location_state_provice_region');

		if (typeof(countryStateMap) != 'undefined') {
			if (countryStateMap.hasOwnProperty(loc)) {
				var cV = ''; 
				if (sr.attr('type') == 'text') {
					var srParent = sr.parent();
					cV = sr.val();
					sr.remove();
					var srNew = $('<select class="input-dropdown-default" id="cb_location_state_provice_region" name="cb_location_state_provice_region"></select>');
					srParent.append(srNew);
				}
				
				$('#cb_location_state_provice_region').empty();
				$.each(countryStateMap[loc], function(index, value) {
					$('#cb_location_state_provice_region').append($('<option>').html(value).attr('value', index));
				});
				
				if (sr.attr('type') == 'text') {
					srNew.val(cV);
				}
			} else {
				if (sr.attr('type') != 'text') {
					var srParent = sr.parent();
					sr.remove();
					srParent.append($('<input type="text" class="input-text-default" title="" style="width:220px;" value="" id="cb_location_state_provice_region" name="cb_location_state_provice_region" />'));
				}
			}
		}
	},
	
	DisplayToolTip : function(el, title) {
	
		//left - middle
		//rightMiddle
		//leftMiddle
		//leftMiddle
	
		toolTipOn = true;
		el.qtip({
			content: title,
			position: {
		      corner: {
		         target: 'rightMiddle',
		         tooltip: 'leftMiddle'
		      }
		   },
			style: {
				name: 'red',
				tip: { // Now an object instead of a string
					corner: 'leftMiddle', // We declare our corner within the object using the corner sub-option
					size: {
						x: 20, // Be careful that the x and y values refer to coordinates on screen, not height or width.
						y : 10 // Depending on which corner your tooltip is at, x and y could mean either height or width!
					}
				}
			},
			show: {
				solo: false,
				ready: true 
			},
			api: {
				onShow : function() {
            		//var timeout = 3500; //ms
            		//var api = this; 
            		//setTimeout((function(){toolTipOn = false; api.hide().disable(true);}),timeout);
         		},
         		
         		onRender: function() {
         			var api = this;
					el.click(function() { api.hide().disable(true) });
				}
			},
			hide: false
		});
	}
};

/*!
 * Report builder
 *
 * Copyright (c) 2009 Subscribe-HR
 *
 */
Subscribe.Report = {
	//enables report field selector
	Init : function() {
		//enable sorting and drag and drop
		$("#report-fields").sortable({ connectWith: '#report-groups', containment: 'div.right-column-fields', opacity: 0.4, tolerance: 'pointer' });
		$('#report-groups').sortable({ 
			connectWith: '#report-fields', 
			containment: 'div.right-column-fields',
			opacity: 0.4, 
			tolerance: 'pointer',
			deactivate: function() {
				//enable/disable function dropdown
				Subscribe.Report.DeactivateFunctions();
			}
		});
		
		//enable remove buttons
		Subscribe.Report.ActivateRemoveButton();
		
		//enable/disable function dropdown
		Subscribe.Report.DeactivateFunctions();
		
		//enable ajax object changer
		$('#selectReportingObject').change(function() {
			Subscribe.Report.ChangeObject($(this).attr('value'));
		});
		
		//enable fields button
		$('#select-fields div.report-link-field').click(function() {
			var newContainer = $(this).parent().clone();
			$('#report-fields').append(newContainer);
			Subscribe.Report.ActivateRemoveButton();
			Subscribe.Report.DeactivateFunctions();
		});
		
		//enable groups button
		$('#select-fields div.report-link-group').click(function() {
			var newContainer = $(this).parent().clone();
			$('#report-groups').append(newContainer);
			Subscribe.Report.ActivateRemoveButton();
			Subscribe.Report.DeactivateFunctions();
		});
		
		$('input[name=update]').click(function() {
			Subscribe.Report.Save();
			return true;
		});
	},
	
	ActivateRemoveButton : function() {
		$('div.report-link-remove').click(function() {
			var container = $(this).parent();
			if (container!=null) {
				container.remove();
				Subscribe.Report.DeactivateFunctions();
			}
		});
	},
	
	DeactivateFunctions : function() {
		//found field that cannot be aggregated
		/*deactivate = true;
		$.each($('#report-fields div.report-dd-conatiner-total'), function() {
			if ($(this).html() == '') {			
				deactivate = true;
			}
		});
		//if groups exist then functions list need to be deactivated
		if (deactivate || $('#report-groups li').length > 0) {
			$('#functionHeading').css('display', 'none');
			$.each($('#report-fields div.report-dd-conatiner-function'), function() {
				$(this).css('display', 'none');
			});
		} else {
			$('#functionHeading').css('display', '');
			$.each($('#report-fields div.report-dd-conatiner-function'), function() {
				$(this).css('display', '');
			});
		}*/
	},
	
	ChangeObject : function(name) {
		
		$.ajax({
			type: 'POST',
			url: $('#mod-url').attr('value') + '/report/',
			dataType: 'json',
			data: 'ajaxRequest=1&request=getReportFields&objectName='+name,
			success: function(res){
				if (res) {
					$('#select-fields').empty();
					$.each(res, function(index, object) {
						Subscribe.Report.CreateEntry(name+'.'+index, object.elementName, object.recordType);
					});
				}
			}
		});
	},
	
	CreateEntry : function(name, textName, type) {
		
		//create a single report field entry
		var li = $('<li></li>')
			.attr('name', name)
			.attr('title', textName)
			.attr('unselectable', 'on');
		
		li.append($('<div></div>')
			.attr('class', 'report-container-field-name')
			.html(textName));
		
		li.append($('<div></div>')
			.attr('class', 'report-link-remove'));
		
		li.append($('<div></div>')
			.attr('class', 'report-link-group')
			.click(function() {
				var newContainer = $(this).parent().clone();
				$('#report-groups').append(newContainer);
				Subscribe.Report.ActivateRemoveButton();
				Subscribe.Report.DeactivateFunctions();
			}));
		
		li.append($('<div></div>')
			.attr('class', 'report-link-field')
			.click(function() {
				var newContainer = $(this).parent().clone();
				$('#report-fields').append(newContainer);
				Subscribe.Report.ActivateRemoveButton();
				Subscribe.Report.DeactivateFunctions();
			}));
		
		li.append($('<div></div>')
			.attr('class', 'report-dd-conatiner-function')
			.append($('#defaultFuncList')
				.clone()
				.css('display', '')));
				
		li.append($('<div></div>')
			.attr('class', 'report-dd-conatiner-sorting')
			.append($('#defaultSortList')
				.clone()
				.css('display', '')));
		
		if (type=='date' || type=='datetime') {
			li.append($('<div></div>')
				.attr('class', 'report-dd-conatiner-sorting')
				.append($('#defaultFrmtList')
					.clone()
					.css('display', '')));
		} else {
			li.append($('<div></div>')
				.attr('class', 'report-dd-conatiner-sorting')
				.html('&nbsp;'));
		}
		
		if (type=='number' || type=='currency' || type=='percentage') {
			li.append($('<div></div>')
			.attr('class', 'report-dd-conatiner-total')
			.append($('<input/>')
				.attr('type', 'checkbox')
				.attr('name', 'total')
				.attr('value', 1)));
		} else {
			li.append($('<div></div>')
				.attr('class', 'report-dd-conatiner-total'));
		}
		
		$('#select-fields').append(li);
	},
	
	Save : function() {
		//create save string
		var fStr = '';
		$.each($('#report-fields li'), function() {
			if (fStr) {
				fStr += ',';
			}
			var li = $(this);			
			fStr += li.attr('name');
			func = li.find('select[name=function]').attr('value');			
			frmt = li.find('select[name=format]').attr('value');
			sort = li.find('select[name=sorting]').attr('value');
			tot = li.find('input[name=total]').attr('checked');
			fStr += '|' + (sort?sort:'');
			fStr += '|' + (func?func:'');
			fStr += '|' + (tot?1:'');
			fStr += '|' + (frmt?frmt:'');			
		});
		
		//create group save string
		var gStr = '';
		$.each($('#report-groups li'), function() {
			if (gStr) {
				gStr += ',';
			}
			var li = $(this);			
			gStr += li.attr('name');		
			frmt = li.find('select[name=format]').attr('value');
			sort = li.find('select[name=sorting]').attr('value');
			gStr += '|' + (sort?sort:'');
			gStr += '|' + (frmt?frmt:'');			
		});
		
		$('#report_fields').attr('value', fStr);
		$('#report_grouping_fields').attr('value', gStr);
		
	}
};

/*!
 * Condition builder
 *
 * Copyright (c) 2009 Subscribe-HR
 *
 */
Subscribe.Workflow = {
	//enables report field selector
	Init : function(el, saveEl) {
				
		$('#' + el + ' a.workflow-condition-add').click(function() {
			Subscribe.Workflow.AddCondition(el);
			return false;	
		});
		
		$('#' + el + ' div.workflow-element-container select').change(function() {
			Subscribe.Workflow.EnableElementSelector($(this), el);
		});		
		
		$('input[name=update]').click(function() {
			Subscribe.Workflow.Save(el, saveEl);
		});
		
		//activate lookup options
		$.each($('select.workflow-condition-lookup'), function() {
			$(this).attr('name', 'workflow-condition-value');
			$(this).dropdownchecklist({ maxDropHeight: 150 });
		});
		
		$.each($('#' + el + ' .workflow-operator-container'), function() {
			$(this).find('select').unbind('change').change(function() {
				Subscribe.Workflow.EnableOperatorSelector($(this), el);				
			});
		});
		
		$('.wf-datepicker').datepicker({		
			changeMonth: true,
			changeYear: true,
			dateFormat: $('#date-format').attr('value'),
			constrainInput: false
		});
	},
	
	EnableOperatorSelector : function(oEl, el) {		
	
		var tElNam = oEl.parent().parent().find('.workflow-element-container').find('select').attr('value');
		var divVl = oEl.parent().parent().find('.workflow-value-container');			
		var tElTyp = $('#' + tElNam).attr('value');
		var tVa = oEl.attr('value');					
			
		//change selected	
		if (tVa == 'changed') {		
			divVl.empty();
		
		//other operator selected
		} else {
				
			divVl.empty();
			divVl = Subscribe.Workflow.CreateValueInput(tElTyp, divVl, tElNam, oEl, el);
		}
		
		//activate lookup options
		divVl.find('select.workflow-condition-lookup').dropdownchecklist({ maxDropHeight: 150 });
	},
	
	CreateValueInput : function(type, divVl, selVal, ddOp, el) {
	
		//boolean values
		if (type == 'boolean') {
			divVl.append($('#' + el + ' select.workflow-boolean-options').clone().attr('name', 'workflow-condition-value').removeAttr('class').addClass('workflow-select-visible'));
				
		//need to lookup values
		} else if (type == 'dropdown' || type == 'multiselect') {
			
			divVl.append($('#_lu_' + selVal)
				.clone()
				.css('display', '')
				.removeAttr('id')
				.attr('name', 'workflow-condition-value')
				.attr('class', 'workflow-condition-lookup')
				.attr('value', ''));
							
		//need date time functionality
		} else if (type == 'date' || type == 'datetime') {
					
			//divVl.append($('#' + el + ' select.workflow-date-options').clone().attr('name', 'workflow-condition-value').removeAttr('class').addClass('workflow-select-visible'));
			//ddOp.change(function() {					
				var tVa = ddOp.attr('value');
				if (tVa == 'isthis' || tVa == 'islast' || tVa == 'isnext' || tVa == 'wasmorethan' || tVa == 'islessthan' || tVa == 'changed') {
					divVl.append($('#' + el + ' select.workflow-date-options').clone().attr('name', 'workflow-condition-value').removeAttr('class').addClass('workflow-select-visible'));
				} else {
					var tEl = $('<input type="text" name="workflow-condition-value" class="input-text-default"/>').css('width', '90px');
					divVl.append(tEl);						
					var format = $('#date-format').attr('value');
					tEl.datepicker({
						changeMonth: true,
						changeYear: true,
						dateFormat: $('#date-format').attr('value'),
						constrainInput: false
					});
				}
				
			//});
			
		//simple input
		} else {
			divVl.append($('<input/>')
				.attr('type', 'text')
				.attr('class', 'input-text-default')
				.attr('name', 'workflow-condition-value')
				.attr('value', ''));
		}
		
		return divVl;
	},
	
	EnableElementSelector : function(selector, el) {
		var selVal = selector.attr('value');
		if (selVal != '') {
			var type = $('#' + selVal).attr('value');
			
			var divVl = $('<div></div>')
			.attr('class', 'workflow-value-container');
			
			//find the right operand type
			var op = '#' + el + ' select.workflow-other-operators';
			if (type == 'boolean') {
				var op = '#' + el + ' select.workflow-boolean-operators';
			} else if (type == 'date' || type == 'datetime') {
				var op = '#' + el + ' select.workflow-date-operators';
			}
				
			var divEl = $('<div></div>')
			.attr('class', 'workflow-operator-container');
			
			//append appropriate operand selection box
			var ddOp = $(op).clone().removeAttr('class').addClass('workflow-select-visible');
			divEl.append(ddOp);
			divVl = Subscribe.Workflow.CreateValueInput(type, divVl, selVal, ddOp, el);
		}
				
		//clean up after previously selected element
		var parentContainer = selector.parent().parent();
		parentContainer.find('div.workflow-operator-container').remove();
		parentContainer.find('div.workflow-value-container').remove();
		parentContainer.find('div.clear').remove();
		
		if (selVal != '') {
			//inject into the row container
			parentContainer.append(divEl).append(divVl);
			
			//create change event for operator dropdown
			ddOp.unbind('change').change(function() {
				Subscribe.Workflow.EnableOperatorSelector($(this), el);				
			});
		}
				
		parentContainer.append($('<div></div>').attr('class', 'clear'));
		
		//activate lookup options
		parentContainer.find('select.workflow-condition-lookup').dropdownchecklist({ maxDropHeight: 150 });
	},
	
	AddCondition : function(el) {
	
		//create row container
		var divRow = $('<div></div>')
			.attr('class', 'workflow-condition-row');
		
		//create element container
		var divElc = $('<div></div>')
			.attr('class', 'workflow-element-container');
		
		//create and enable element selector
		var selectEl = $('#' + el + ' select.workflow-element-options').clone().removeAttr('class').addClass('input-dropdown-default');
		selectEl.change(function() {
			Subscribe.Workflow.EnableElementSelector($(this), el);
		});
		
		//add row container to the parent container
		var mainCont = $('#' + el);
		divElc.append(selectEl);
		divRow.append(divElc).append($('<div></div>').attr('class', 'clear'));
		mainCont.find('div.wclear-fix').remove();		
		mainCont.append(divRow).append($('<div></div>').attr('class', 'wclear-fix'));
	},
	
	DateFieldOnChange : function() {
		
	},
	
	Save : function(el, saveEl) {
	
		var rVal = [], tEl, tOp, tVal;
		$.each($('#' + el + ' div.workflow-condition-row'), function() {
			tEl = $(this).find('div.workflow-element-container').find('select').attr('value');
			tOp = $(this).find('div.workflow-operator-container').find('select').attr('value');
			tVal = $(this).find('div.workflow-value-container').find('[name=workflow-condition-value]').val();
			
			if (tEl && tOp) { // && tVal!=null
				rVal[rVal.length] = {element: tEl, operator: tOp, val: tVal};
			}
		});
		
		$('#' + saveEl).attr('value', $.toJSON(rVal));
	}
};

//dropdown filtering array
filter = Array();
