if ("https:" == document.location.protocol) {
	siteroot = 'https://secure12.hostek.net/secure1/newconnexion/'
} else {
	siteroot = ( /db/.test(location.hostname) ) ? '/newconnexion.net/' : '/';
}
$(document).ready(function(){
	var step = $('#step').val();
	var opt = $('#opt').val();
	 
	window.canceldialog = function() { 
		$('.boxy-wrapper').fadeOut();
	};
	switch( step ) {
		
		case '2' :
			
			var $startdate = $('#startdate');
			var $enddate = $('#enddate');
			var initday = new Date();
			$('#adtypedated').click( function() { 
				$startdate.attr( 'disabled', ! this.checked );
				$enddate.attr( 'disabled', ! this.checked );
				$('#daynumber').attr( 'disabled', this.checked );
				previewupdate( 'ad' );
			});
			$('#adtypeongoing').click( function() { 
				$startdate.attr( 'disabled', this.checked );
				$enddate.attr( 'disabled', this.checked );
				$('#daynumber').attr( 'disabled', ! this.checked );
				previewupdate( 'ad' );
			});
			
			if ( $startdate.val().length > 0 ) initday = new Date( $startdate.val() );
			$startdate.data( 'day', initday );
			var eday = $enddate.val();
			if ( eday.length > 0 ) eday = new Date( eday )
			else if ( $startdate.val().length > 0 ) eday =  new Date( $startdate.val() );
			$enddate.data( 'day', eday );
			
			function startcalinit() {
				$('#startcal').jCal({
					 day		: $startdate.data( 'day' )
					,endday		: $startdate.data( 'day' )
					,days		: 1
					,months		: 1
					,showyear	: false
					,dCheck		: function (day) {
									if( $enddate.data( 'day' ) > $startdate.data( 'day' ) ) {
										return ( day <= $enddate.data( 'day' ) );
									} else return ( true );
								}
					,callback	: function ($inst, day) {
									var dstart = [ 
										 day.getMonth() + 1
										,'/' 
										,day.getDate()
										,'/'
										,day.getFullYear()
									];
									$startdate.val( dstart.join('') );
									$startdate.data( 'day', day );
									$('#endcal').empty();
									endcalinit();
									$('#startcal').fadeOut();
									previewupdate( 'both' );
									return true;
								}
					,prevnextcallback: toggleprev
				});
				//console.info( 'startcal', $enddate.data( 'day' ) )
			};
			startcalinit();
			$startdate.click( function() { $('#endcal').fadeOut(); $('#startcal').fadeIn(); })
					  .blur( function() { $('#startcal').fadeOut() });
			
			function endcalinit() {
				$('#endcal').jCal({
					 day		: $enddate.data( 'day' ) || new Date()
					,endday		: $enddate.data( 'day' )
					,days		: 1
					,months		: 1
					,showyear	: false
					,dCheck		: function (day) {
									return ( day >= $startdate.data( 'day' ) );
								}
					,callback	: function ($inst, day) {
									var dend = [ 
										 day.getMonth() + 1
										,'/' 
										,day.getDate()
										,'/'
										,day.getFullYear()
									];
									$enddate.val( dend.join('') );
									$enddate.data( 'day', day );
									if( day > $startdate.data( 'day' ) ) {
										$('#startcal').empty();
										startcalinit();
									}
									
									$('#endcal').fadeOut();
									previewupdate( 'both' );
									return true;
								}
					,prevnextcallback: toggleprev
				});
				//console.info( 'endcal', $enddate.data( 'day' ) )
			};
			endcalinit();
			$enddate.click( function() { $('#startcal').fadeOut(); $('#endcal').fadeIn(); })
					.blur( function() { $('#endcal').fadeOut() });
			
			var wordlimit = opt > 1 ? 40 : 15;
			var $info = $('#info')
			var countfields = $('#info,#venue,#city,#state');
			countfields.data( 'limit', wordlimit ).data( 'showcount', $('#wordn') );
			countfields.keyup( function(e) { watchkey( e.target, e.which ) });
			countfields.blur( function() { countwords(this); });
			countfields.change( function() { previewupdate( 'ad' ); });
			
			var $headline = $( '#headline' );
			$headline.data( 'limit', wordlimit ).data( 'showcount', $('#wordn') );
			$headline.keyup( function(e) { watchkey( e.target, e.which ) });
			$headline.blur( function() { countwords(this); });
			$headline.change( function() { previewupdate( 'both' ); });
			
			countwords( $info[0] );
			$('#wordn').parent().show();
			previewupdate( 'ad' );
			
			var aboutwords = new Boxy(
				$('#aboutwords')
				,{ closeable: true, show: false });
			
			$('#showaboutwords').click( function(){ aboutwords.center().boxy.fadeIn(); });
			
			$('#starttime').clockpick({
				 starthour		: 0
				,endhour		: 23
				,minutedivisions: 2
				,useBgiframe	: true
				}
				,function(){ previewupdate( 'ad' ); this.focus(); 
			}).click( function(){ $('#CP_hourcont').css('left','300px') });
			$('#endtime').clockpick({
				 starthour		: 0
				,endhour		: 23
				,minutedivisions: 2
				,useBgiframe	: true
				}
				,function(){ previewupdate( 'ad' ); this.focus();
			}).click( function(){ $('#CP_hourcont').css('left','300px') });
			
			
			//if ( opt < 3 ) break;
			
			var ud = new Boxy( $('#uploadcon'), {
				title: 'Upload an Image', closeable: false, show: false
			});
			var tb = $( 'div.title-bar','td.boxy-inner' );
			$(tb[0]).css({ 
				 background		:'#9ACDD0'
				,color			: '#000'
				,'font-weight'	: 'bold'
				,'text-align'	: 'center'
			});
			$('h2',tb).css({ 'text-align': 'center','font-weight': 'bold' });
			
			setTimeout( function() { 
				$('#uploadifr').attr('src', siteroot + 'calendar/add_event/imgform.cfm');
			}, 1000 );
			
			$('#addimgX').bind('click keypress',function() { 
				
				if (this.checked) {
					ud.center().boxy.fadeIn();
					var cb = this;
					var $imgform = $('#uploadifr').contents().find('body').find('#imgform');
					$('#cancelbtn', $imgform).click( function() { 
						if ( $('#imgname').val() == '' ) {
							cb.checked = false;
							$('#addimg').val( 0 );
							previewupdate( 'both' );
						}
					});
				} else ud.boxy.fadeOut();
				
				$('#addimg').val( this.checked ? 1 : 0 );
				previewupdate( 'both' );
			});
			
			window.uploadComplete = function ( message, imgurl ) { 
				//console.info( message, imgurl );
				//$('#eminfo').val( message + imgurl );
				if ( imgurl.length ) {
					$('#tokenimg').attr( 'src', imgurl );
					$('#eminfo_ifr').contents().find('body').find('#tokenimg').attr('src',imgurl);
					$('#emifrm').contents().find('body').find('#tokenimg').attr('src',imgurl);
					$('#imgname').val( imgurl );
					ud.boxy.fadeOut();
					previewupdate( 'both' );
				} else {
					if ( $('#imgname').val() == '' ) $('#addimgX').attr('checked', false);
					$(tb[0]).css({ color: '#E76656'})
						.text('Upload Error, please try again or cancel.');
				}
			};
			
			if ( opt != 4 ) break;
			
			var $eminfo = $('#eminfo');
			var $embody = $('#eminfo_ifr').contents().find( 'body' );
			$eminfo.data( 'limit', 150 ).data( 'showcount', $('#emwordn') );
			//$embody.keyup( function(e) { watchkey( e.target, e.which ) });
			//$embody.blur( function() { countwords(this); });
			//$embody.change( function() { previewupdate('em'); });
			emcountwords( $eminfo[0] );
			$('#emwordn').parent().show();
			
			break;
		case '3' :
			var issues = $('#addpubdate input:checked').length;
			
			$('#addpubdate input').click( function() { 
				issues = $('#addpubdate input:checked').length;
				if ( opt > 2 ) {
					$('.selectedDay:first', '#adcal').trigger('click');
					if ( issues > 1 ) $('#emend').next('span').text( 'Last email' );
				}
				if ( opt == 4 ) $('.selectedDay:first', '#emcal').trigger('click');
			});
			
			datepickinit();
			
			break;
		case '4' :
			
			break;
		case '5' :
			
			break;
	};
	
	function mailpassinit() {
		var mpbox = new Boxy(
			'<iframe src="' + siteroot + 'pods/mailPasswd.cfm" frameborder="0" style="width:20em;.width:22em;height:15.5em;.height:16em;overflow:hidden;"></iframe>'
			,{ closeable: false, show: false });
		$('#pw').click( function() {
			mpbox.center().boxy.fadeIn();
			$( mpbox.getContent() ).contents().find('body').find('#email').focus();
			return false;
		});
	};
	
	if ( $('#pw').length > 0 ) mailpassinit();
	
	function datepickinit() {
		var $startrun = $('#startrun');
		var initday = new Date();
		if ( $startrun.val().length > 0 ) initday = new Date( $startrun.val() );
		$('#adcal').jCal({
			 day		: initday
			,days		: opt > 2 ? 60 * issues : opt * 15
			,months		: opt > 2 ? 3 : 2
			,showyear	: false
			,dCheck		: function (day) {
				var d = new Date();
				d.setDate(d.getDate() - 1);
				if( $('#renewid').val() > 0 ) {
					var erA = $('#startrun').val().split('/');
					d = new Date( erA[2], erA[0] - 1, erA[1] );
				} 
				return ( day >= d );
			}
			,getendday	: function (data, day) { return adendday( day ) }
			,callback	: function ($inst, day) {
				var sday = (day.getMonth() + 1 ) + '/' + day.getDate() + '/' + day.getFullYear();
				$startrun.val( sday );
				
				var eday = new Date( day );
				//console.info( ( opt > 2 ? (60 * issues) - 1 : opt == 2 ? 29 : 14 ) );
				eday.setDate( day.getDate() + ( opt > 2 ? (60 * issues) - 1 : opt == 2 ? 29 : 14 ) );
				
				var feday = (eday.getMonth() + 1 ) + '/' + eday.getDate() + '/' + eday.getFullYear();
				$('#endrun').val( feday );
				$inst.data('opt').endday = eday;
				
				var lastid = $('#adcal div.monthbox:visible:last' )[0].id.split('-');
				var lastd = new Date( lastid[1], lastid[2], 0 );
				//console.info( 'callback: ',lastd );
				if( eday > lastd ) {
					$('#adcal').find('div.btnnext').trigger('click');
					lastd.setMonth( lastd.getMonth() + 1 );
					if( eday > lastd ) setTimeout( function() {
						 	$('#adcal').find('div.btnnext').trigger('click');
						}
						, 500 );
				}
				
				return true;
			}
			,prevnextcallback: toggleprev
		});
		function adendday( day ) {
			var eday = new Date( day );
			eday.setDate( day.getDate() + ( opt > 2 ? (60 * issues) - 1 : opt == 2 ? 29 : 14 ) );
			return eday;
		};
		$('#adcal').data('opt').endday = $("#endrun").val();
		
		$("#startrun, #endrun").change( function() { 
			$('#adcal').val( $("#startrun").val(), $("#endrun").val() );
			//console.info( $("#startrun").val() ); 
		});
		
		if ( opt == 4 ) {
			$('#emcal').jCal({
				 day		: new Date( $('#emstart').val() )
				,days		: 20
				,months		: 2
				,showyear	: false
				,dCheck		: function (day) {
					var d = new Date( $('#inputdate').val() );
					d.setDate(d.getDate() + 2);
					return ( day > d && (day.getDate() == 1 || day.getDate() == 15) );
				}
				,getendday	: function (data, day) { return emendday( day ) }
				,callback	: function ($inst, day) {
					var emstart = ( day.getMonth() + 1 ) + '/' + day.getDate() + '/' + day.getFullYear()
					$('#emstart').val( emstart );
					var eday = emendday( day );
					var emend = ( eday.getMonth() + 1 ) + '/' + eday.getDate() + '/' + eday.getFullYear();
					$('#emend').val( emend );
					$inst.data('opt').endday = eday;
					
					var lastid = $('#emcal div.monthbox:visible:last' )[0].id.split('-');
					var lastd = new Date( lastid[1], lastid[2], 0 );
					if( eday >= lastd ) $('#emcal').find('div.btnnext').trigger('click');
					
					return true;
				}
				,prevnextcallback: toggleprev
			});
			
			function emendday( day ) {
				var d = day.getDate() == 1 ? 15 : 1;
				var m = day.getDate() == 1 ? day.getMonth() : day.getMonth() + 1;
				var eday = new Date( day );
				eday.setMonth( m + issues - 1 );
				eday.setDate( d );
				return eday;
			};
			
			$('#emcal').data('opt').endday = $("#emend").val();
			
		} // end opt 4
	};
	
	function toggleprev( $inst, btntype ) {
		var firstid = $('div.monthbox:visible:first', $inst )[0].id.split('-');
		var firstd = new Date( firstid[1], firstid[2] - 1, 1 );
		//console.info( 'toggleprev: ', $inst, btntype );
		//console.info( 'toggleprev: ', firstd.getMonth(), new Date().getMonth() );
		
		if( firstd.getTime() > new Date().getTime() ) {
			$inst.find('div.btnprev').show();
		} else $inst.find('div.btnprev').hide();
	};
	
	var delim = opt == 1 ? /[\W_-]+/ : /\W+/
	
	function wordcount( s ) {
		var x = s.replace( /<[^>]*>/g, ' ' )
			.replace( /&nbsp;/g, ' ' )
			.replace( /\s+/g, ' ' )
			.replace( /^ | $/, '' )
			.split( delim );
		var n = x.length;

		if ( opt == 1 ) { // count dash as delim, but not phone numbers (111-111-1111)
			var phonecount = s.match(/[^\d-]\d{3}-\d{3}-\d{4}/g);
			if ( phonecount ) n -= phonecount.length * 2;
			//console.info( 'phonecount: ', phonecount.length * 2  );
			var phonecount2 = s.match(/\d-\d{3}-\d{3}-\d{4}/g);
			if ( phonecount2 ) n -= phonecount2.length * 3;
		}
		
		// if all words were deleted, the array still has a length of 1
		if ( n == 1 ) n = x[0].length == 0 ? 0 : 1;
		return n;
	};
	var aKeys = [32,13,9,8,46,17,0]; // space, return, tab, bkspace, delete, control, ?
	function watchkey( obj,pressed,str ) {
		if ( $.data( obj, 'showcount' ).text() * 1 >= $.data( obj, 'limit' ) ) 
			countwords(obj)
		// if not up to the limit, only run when words are involved
		else if( pressed in aKeys ) countwords(obj);
	};
	function countwords( obj ) {
		//console.info( 'countwords: ', obj.id, $.data( obj, 'limit' ) );
		var  txt	= obj.value
			,limit	= $.data( obj, 'limit' )
			,count	= 0;
		
		count += wordcount( $( '#headline' ).val() );
		count += wordcount( $( '#venue' ).val() );
		count += wordcount( $( '#city' ).val() );
		count += wordcount( $( '#state' ).val() );
		count += wordcount( $( '#info' ).val() );
		/*
		console.info( 'headline: ', wordcount( $( '#headline' ).val() )  );
		console.info( 'venue: ', wordcount( $( '#venue' ).val() ) );
		console.info( 'city: ', wordcount( $( '#city' ).val() )  );
		console.info( 'state: ', wordcount( $( '#state' ).val() )  );
		console.info( 'info: ', wordcount( $( '#info' ).val() )  );
		*/
		if ( count > limit ) {
			var toomany = count - limit; // lose this many words
			var justenuf = wordcount( txt ) - toomany // txt is only the active field
			while ( wordcount( txt ) > justenuf ) txt = txt.substring(0, txt.lastIndexOf(' '));
			obj.value = txt;
			previewupdate( 'ad' );
			count = limit;
		}
		//var wordsleft = limit - count;
		$.data( obj, 'showcount' ).text( count );
		
		if ( opt == 1 ) {
			var remail = /(^|[\s\(<"])(\w[-._\w]*@\w[-._\w]*\w\.[a-zA-Z]{2,6})/g;
var reurl = /(^|\s|<|>|;|[^=]"|[^l]\()(http:\/\/)?(([\d\w-]{2,}\.)+([a-zA-Z]{2,6}))(\/[^\s&]+[#?=&@\.]*\w+)*(\b)/g;
			if ( remail.test( $( '#info' ).val() ) || reurl.test( $( '#info' ).val() ) )
				$( '#linkalert' ).fadeIn()
			else $( '#linkalert' ).fadeOut();
		}
	}
	
	$( '#daynumber,#starttime,#endtime' ).change( function() { //,#venue,#city,#state
		previewupdate( 'ad' ); 
	});
	$( '#areaid' ).change( function() { previewupdate( 'both' ) });
	//$( '#headline' ).bind( 'change', function() { previewupdate( 'both' ) });
	
	function previewupdate( el ){
		if( el == 'both' || el == 'ad' ) adpreviewupdate();
		if( opt == 4 && (el == 'both' || el == 'em') ) empreviewupdate();
	};
	
	function adpreviewupdate(){
		//console.info( el + ': ' + val );
		var $adpreview = $('#preview .adpreview');
		var adtype = $('input[name = datedongoing]:checked').val();
		
		if( adtype == 'ongoing' ) $adpreview.addClass( 'ongoing' )
		else $adpreview.removeClass( 'ongoing' );
		
		$adpreview.load(
			siteroot + 'f/formatevent.cfm'
			,{
				 opt			: $('#opt').val()
				,datedongoing	: adtype
				,eid			: ''
				,areaid			: $('#areaid').val()
				,headline		: $('#headline').val()
				,startdate		: $('#startdate').val()
				,enddate		: $('#enddate').val()
				,starttime		: $('#starttime').val()
				,endtime		: $('#endtime').val()
				,venue			: $('#venue').val()
				,city			: $('#city').val()
				,state			: $('#state').val()
				,info			: $('#info').val()
				//,addimg			: $('#addimg').attr( 'checked' )
				,img			: $('#imgname').val()
				,ajax			: true
			}
		);
	};
	
	function empreviewupdate(){
		var $emeditor = $('#eminfo_ifr').contents().find( 'body' );
		var acode = $('#areaid option:selected').attr( 'title' );
		$( 'h3.em img', $emeditor )[0].src = siteroot + 'img/site/dot-' + acode + '.gif';
		$( 'h3.em', $emeditor ).show();
		$( 'div.emheader', $emeditor ).text( formatDates() );
		$( '#emheadline font', $emeditor ).text( $('#headline').val() );
		
		tinyMCE.triggerSave(true,true);
		//emcountwords( $eminfo[0] );
		
		var $emprevu = $('#emifrm').contents().find( 'body' );
		$emprevu.html( $emeditor.html() ).css( 'height','auto' );
		$('#emifrm').height( $emprevu.height() );
	};
	
	var monthNames = 'January,February,March,April,May,June,July,August,September,October,November,December'.split(',');
	
	function formatDates() { 
		if( $('#startdate').val() == '' ) return '';
		var 
		 datestr = ''
		,sdA	= $('#startdate').val().split('/')
		,edA	= $('#enddate').val().split('/')
		var sd = sdA[1];
		var sm = sdA[0];
		var ed = edA[1];
		var em = edA[0];
		var sdate = (sm ? monthNames[sm - 1] : '') + ' ' + sd;
		datestr = sdate;
		if ( $('#enddate').val().length ) {
			if ( $('#startdate').val() != $('#enddate').val() ) {
				var showem = (sm == em) ? '' : monthNames[em - 1] + ' ';
				var edate = showem + ed;
				var dash = (sdate.length && edate.length) ? ' - ' : '';
				datestr = sdate + dash + edate;
			}
		}
		return datestr;
	};
	
	if ( /renew\.cfm/.test( location ) ) {
		//$('li p.cancel a.acancel','#review').click( function() { return false; });
		var $cancelbox = $('#cancelbox');
		var cbox = new Boxy(
			$cancelbox
			,{ closeable: true, show: false });
		$('li p a.acancel','#review').click( function() {
			//console.info( $(this).parent().hasClass( 'cancel' ) );
			$cancelbox.data( 'href', this.href );
			$cancelbox.data( 'cancelled', $(this).parent().hasClass( 'cancel' ) );
			$('#rb-cancel,#rb-deactive',$cancelbox ).attr('checked',false);
			cbox.center().boxy.fadeIn();
			return false;
		});
		$('#cancelbtn',$cancelbox ).click( function() { cbox.boxy.fadeOut(); });
		$('#rb-cancel',$cancelbox ).click( function() { 
			if ( ! $cancelbox.data( 'cancelled' ) )
				window.location.replace( $cancelbox.data( 'href' ) );
			cbox.boxy.fadeOut(); 
		});
		$('#rb-deactive',$cancelbox ).click( function() { 
			$('#deactivate').val(1);
			document.inputform.action = $cancelbox.data( 'href' );
			document.inputform.submit();
			cbox.boxy.fadeOut(); 
		});
	}
	
});

