$(function(){

		LeadImageInit();
		PosterImageInit();

		$('.nodeCitySelect').change ( function() {
				var id = $(this).attr('rel');

				if ( $(this).val() == '_enter' ) { 
					// enter a new city

					$('#nodeGig_dateD' + id + 'Venue_select').hide();
					$('#DateVenueManual' + id ).show(); 
					$('#nodeGig_dateD' + id + 'City').val('Enter City');
					$('#nodeGig_dateD' + id + 'City').select();
				} else if ( $(this).val() != '' ) { 
					// existing city selected
					$('#nodeGig_dateD' + id + 'City').val($(this).val()); 
					$('#nodeCityHider' + id ).hide(); 


					var city = $(this).val().toLowerCase();
					var s = '';

					var request = {
						m: 'events_edit',
						rpc: 'venues',
						city: city
					}

					$('#nodeGig_dateD' + id + 'Venue_select').hide();
					$('#DateVenueManual' + id ).hide(); 
					$('#DateVenueSelectLoading' + id).show();

					$('#nodeGig_dateD' + id + 'Venue_stub').val(''); 
					$('#nodeVenueHider' + id).hide()

						$.getJSON ( 'index.php', request, function ( data ) {
								$('#DateVenueSelectLoading' + id).hide();

								var s = '';
								s = '<option value="">Select Venue...</option>' + "\n";
								s += '<option value="_enter">Venue is not listed...</option>';
								if ( data.cities.length > 0 ) {
									s += '<option value="">-----</option>'
										for ( var i in data.cities ) {
											s += '<option value="' +  data.cities[i].title + '">';
											s += data.cities[i].title;
											if ( data.cities[i].address != '' ) {
												s += ' - ';
												s += data.cities[i].address;
											}
											s += '</option>';
											$('#nodeGig_dateD' + id + 'Venue_select').html(s);
											$('#nodeGig_dateD' + id + 'Venue_select').show();
											$('#DateVenueManualCancel' + id ).show(); 
										}
								} else {
									$('#nodeGig_dateD' + id + 'Venue_select').hide();
									$('#DateVenueManual' + id ).show(); 
									$('#DateVenueManualCancel' + id ).hide(); 
								}

							});


				}

				
			});

		$('.DateVenueSelect').change ( function() {
			
				var id = $(this).attr('rel');

				if ( $(this).val() == '_enter' ) { 
					// enter a new city
 					$('#nodeGig_dateD' + id + 'Venue_select').hide();
					$('#DateVenueManual' + id ).show(); 
					$('#nodeGig_dateD' + id + 'Venue_stub').val('1'); 
				} else {
 					$('#nodeGig_dateD' + id + 'Venue').val( $(this).val() );
					$('#nodeGig_dateD' + id + 'Venue_stub').val(''); 
				}
			});

		$('.DateVenueManualCancel').click ( function() {
				var id = $(this).attr('rel');
				$('#DateVenueManual' + id ).hide(); 
				$('#nodeGig_dateD' + id + 'Venue_select').get(0).selectedIndex = 0;
				$('#nodeGig_dateD' + id + 'Venue_select').show();		   
			});


	});



var LeadImageOriginal = false;

var CMSthis = 'events_edit';

function LeadImageInit() {
	
	LeadImageOriginal = $('#LeadImage').html();

    var s = '';
    s += "\n";
	s += '<form method="post" enctype="multipart/form-data" action="/index.php" id="LeadImageForm" name="LeadImageForm" target="LeadImageIframe">';
    s += '<input type="hidden" name="m" value="' + CMSthis + '" />';
    s += '<input type="hidden" name="rpc" value="ImageUploadProcess" />';
    s += '<input type="hidden" name="LeadImageFilename" id="LeadImageFilename" value="" />';
    s += '<input type="file" name="ImageFile" id="LeadImageFile" onchange="LeadImageUploadProcess();" />';
	s += '</form>';
    s += "\n";
 	s += '<iframe name="LeadImageIframe" id="LeadImageIframe" src="about:blank" style="border: 0; height: 0; width: 0; padding: 0; position: absolute;"></iframe> ';

    $('#LeadImageUpload').html(s);

}


function LeadImageUploadProcess() {

    var filename = $( '#LeadImageFile' ).val();

    // Some browsers (IE<8) give full path as filename
    filename = filename.replace(/^.*\\/, '');
	
	$('#LeadImageFilename').val( filename );
    if ( filename.replace ( '/\s/', '' ).toString() === '' ) {
        return false;
    }

  	$( '#LeadImageIframe' ).bind ( 'load', function() { LeadImageUploaded(); } );
	$( '#LeadImageForm' ).submit();	

}

var LeadImageParams = new Array();
LeadImageParams.cropperSize = 240;

function LeadImageUploaded() {

	var filehash = $('#LeadImageIframe').contents().find("body").html();
	//	$('#LeadImageIframe').remove();

	var fileinfo = filehash.split('|');
	LeadImageParams.filename = fileinfo[0];
	LeadImageParams.previewWidth =  fileinfo[1];
	LeadImageParams.previewHeight =  fileinfo[2];
	var f = '/' + CMSthis + '/thumb/' + LeadImageParams.filename + '.x' + LeadImageParams.cropperSize + 'y' + LeadImageParams.cropperSize +'.jpg';

	$('#LeadImage').html( '<img src="" id="LeadImagePreview" />' );	

  	$('#LeadImage img').bind ( 'load',function() {

			$( this ).unbind ( 'load' );
			$('#LeadImage img').unbind ( 'load' );

			var size = ( LeadImageParams.previewWidth > LeadImageParams.previewHeight )
				? LeadImageParams.previewHeight
				: LeadImageParams.previewWidth;

  		    api = $.Jcrop( '#LeadImagePreview', {
 					onChange: showPreview,
 					onSelect: showPreview,
					setSelect:   [ 0, 0, LeadImageParams.cropperSize, LeadImageParams.cropperSize ],
					boxWidth: LeadImageParams.cropperSize, 
					boxHeight: LeadImageParams.cropperSize,
 					aspectRatio: 1
				});

			var s = '<input type="button" id="LeadImageCropButton" value="Crop" />';
			s += ' ';
			s += '<input type="button" id="LeadImageCancelButton" value="Cancel" />';
			$('#LeadImageUpload').html(s);

			$('#LeadImageCropButton').click( function() {
					LeadImageCropExecute();
				});

			$('#LeadImageCancelButton').click( function() {
					LeadImageCancel();
				});

 		});

	$('#LeadImage img').attr('src', f );

	if ( $('#PosterImagePreview').length == 0 ) {
		$('#PosterImage').html( '<img src="" id="PosterImagePreview" />' );	
		$('#PosterImage img').attr('src', f );

		var f = '/' + CMSthis + '/thumb/' + LeadImageParams.filename + '.x' + LeadImageParams.cropperSize + 'y' + LeadImageParams.cropperSize +'.jpg';

		$('#PosterImage').html( '<img src="" id="PosterImagePreview" />' );	
		$('#PosterImage img').attr('src', f );

		// save for form submit
		var meta = 'filename:' + LeadImageParams.filename;
		$('#nodePoster_image_upload').val ( meta ) ;

	}

	

}

function LeadImageCropExecute() {

 	// remove px
 	previewWidth = parseInt($('#LeadImage .jcrop-holder').css('width').replace('px', ''));
 	previewHeight = parseInt($('#LeadImage .jcrop-holder').css('height').replace('px', ''));

	api.destroy();

	// 240 is size of preview div
	var rx = 240 / LeadImageParams.coords.w;
	var ry = 240 / LeadImageParams.coords.h;

	jQuery('#LeadImage img').css({
			width: Math.round(rx * previewWidth ) + 'px',
				height: Math.round(ry * previewHeight ) + 'px',
				marginLeft: '-' + Math.round(rx * LeadImageParams.coords.x) + 'px',
				marginTop: '-' + Math.round(ry * LeadImageParams.coords.y) + 'px'
				});

 	LeadImageInit();

}

function LeadImageCancel() {
	api.destroy();
    $('#LeadImage').html( LeadImageOriginal );
	LeadImageInit();
 	$('#nodeLead_image_upload').val ('');
}

// Our simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showPreview(coords)
{

	if ( ! ( parseInt(coords.w) > 0 ) ) { 
		return false;
	}

	// make available for cropper
	LeadImageParams.coords = coords;

 	// remove px
 	previewWidth = parseInt($('#LeadImage .jcrop-holder').css('width').replace('px', ''));
 	previewHeight = parseInt($('#LeadImage .jcrop-holder').css('height').replace('px', ''));

	meta = '';
	meta += 'filename:' + LeadImageParams.filename;
	meta += ',x:' + coords.x;
	meta += ',y:' + coords.y;
	meta += ',w:' + coords.w;
	meta += ',h:' + coords.h;
	meta += ',previewWidth:' + previewWidth;
	meta += ',previewHeight:' + previewHeight;

	// save for form submit

 	$('#nodeLead_image_upload').val ( meta ) ;

}


function PosterImageInit() {
	
	PosterImageOriginal = $('#PosterImage').html();

    var s = '';
    s += "\n";
	s += '<form method="post" enctype="multipart/form-data" action="/index.php" id="PosterImageForm" name="PosterImageForm" target="PosterImageIframe">';
    s += '<input type="hidden" name="m" value="' + CMSthis + '" />';
    s += '<input type="hidden" name="rpc" value="ImageUploadProcess" />';
    s += '<input type="hidden" name="PosterImageFilename" id="PosterImageFilename" value="" />';
    s += '<input type="file" name="ImageFile" id="PosterImageFile" onchange="PosterImageUploadProcess();" />';
	s += '</form>';
    s += "\n";
 	s += '<iframe name="PosterImageIframe" id="PosterImageIframe" src="about:blank" style="border: 0; height: 0; width: 0; padding: 0; position: absolute;"></iframe> ';

    $('#PosterImageUpload').html(s);

}

function PosterImageUploadProcess() {

    var filename = $( '#PosterImageFile' ).val();

    // Some browsers (IE<8) give full path as filename
    filename = filename.replace(/^.*\\/, '');
	
	$('#PosterImageFilename').val( filename );
    if ( filename.replace ( '/\s/', '' ).toString() === '' ) {
        return false;
    }

  	$( '#PosterImageIframe' ).bind ( 'load', function() { PosterImageUploaded(); } );
	$( '#PosterImageForm' ).submit();	

}

function PosterImageUploaded() {

	var filehash = $('#PosterImageIframe').contents().find("body").html();

	var cropperSize = 240;
	var fileinfo = filehash.split('|');
	var filename = fileinfo[0];

	var f = '/' + CMSthis + '/thumb/' + filename + '.x' + cropperSize + 'y' + cropperSize +'.jpg';

	$('#PosterImage').html( '<img src="" id="PosterImagePreview" />' );	
	$('#PosterImage img').attr('src', f );

	// save for form submit
	var meta = 'filename:' + filename;
 	$('#nodePoster_image_upload').val ( meta ) ;

}


function log ( s ) {
    if ( $('#log').length == 0 ) {
        $('#background').prepend('<div id="log" style="background: #fc0;">C</div>');
    }
    $('#log').html(s);
}

