var uploadQueue 	= {};
var validation 		= [];
var urlImageUpload 	= 'index.php?do=upload_image_ajax';
var urlFormPost 	= 'index.php?do=nominee_action&useJSON=1';
var urlLike 		= 'index.php?do=like&id=';
var urlComment 		= 'index.php?do=nominee_comment&useJSON=1&id=';
var urlGallery 		= 'index.php?do=Gallery-Section';
	

window.addEvent('domready', function() {
	
	registerSubmitNowSwitch();
	registerOverText();
	registerGalleryScroller();
	registerCommentStars();
	registerGalleryClicks();
	
	if( Browser.safari || Browser.Engine.webkit ) {
		$(document.body).setStyle( 'background-position', '49.9% top' );	
	}
	
	
	
});

window.log = function () {
	log.history = log.history || [];
	log.history.push(arguments);
	if (this.console) {
		console.log(Array.prototype.slice.call(arguments));
	}
};

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}

function registerGalleryClicks() {
	
	var selTab;
	
	if( $('gallery_tabs') != undefined ) {
	
		$('gallery_tabs').getChildren('a').addEvent('click', function() { 
			
			$('gallery_tabs').getChildren('a').removeClass( 'selected' ); 
			this.addClass( 'selected' ); 
			gallerySection( apendURL( urlGallery ) );
			return false;
		});
		
		$('gallery_sort').getChildren('a').addEvent('click', function() { 
			
			$('gallery_sort').getChildren('a').removeClass( 'selected' ); 
			this.addClass( 'selected' ); 
			gallerySection( apendURL( urlGallery ) );
			return false;
		});
	}
}

function apendURL( url ) {
	
	var sortURL 	= $('gallery_tabs').getChildren('a.selected')[0].get( 'id' ).split( 'gallery_tab_' ).join( '' );
	var filterURL 	= '&filter=' + $('gallery_sort').getChildren('a.selected')[0].get( 'id' ).split( 'gallery_sort_' ).join( '' );
	
	if( sortURL != '' )
		sortURL = '&type=' + sortURL;
		
	return url + sortURL + filterURL;
}

function galleryGenericLike( nID, refreshPage ) {
	
	var request = new Request({
		method: 'get',
		url:urlLike + nID,
		onSuccess: function(responseText, responseXML) {  
			window.location.reload();
		}
	}).send();
}

function galleryLikeUpdate( nID, obj ) {
	
	$(obj).getChildren( 'span' )[0].set( 'html', '...' );
	
	var request = new Request.JSON({
		method: 'get',
		url:urlLike + nID,
		onSuccess: function(responseText, responseXML) {  
			$(obj).getChildren( 'span' )[0].set( 'html', responseText.totalVotes );
		}
	}).send();
}

function galleryLike( nID ) {
	
	$('gallery_listing').set( 'html', '<img class="loading" src="site.kaleidoscopecolorado.org/images/mediabox/loading.png" />' );
	
	var request = new Request({
		method: 'get',
		url:urlLike + nID,
		onSuccess: function(responseText, responseXML) {  
			gallerySection( apendURL( urlGallery ) );
		}
	}).send();
}

function gallerySection( url ) {
	
	$('gallery_listing').set( 'html', '<img class="loading" src="site.kaleidoscopecolorado.org/images/mediabox/loading.png" />' );
	
	var request = new Request.HTML({
		method: 'get',
		url:url,
		update: $('gallery_listing'),
		onSuccess: function(responseText, responseXML) {  
		}
	}).send();
}

function submitCommentForm() {	

	if( $defined( $('frmComments') ) ) {		
		
		var firstName 	= $('firstName').get( 'value' );
		var lastName 	= $('lastName').get( 'value' );
		var description = $('description').get( 'value' );
		var email 		= $('email').get( 'value' );
		var nomineeID 	= $('nomineeID').get( 'value' );
		var ratingOnly 	= ( $('rating').get( 'value' ) != '' && $('rating').get( 'value' ) != '0' && description == '' );
		var formData	= $('frmComments').toQueryString().parseQueryString();
		var detailPage	= ( parent.$( 'detail_comments_heading' ) != undefined );
		
		if(  ratingOnly || 
			( firstName != '' && lastName != '' && description != '' && email != '' && isValidEmail( email ) ) ) {
			
			if( detailPage ) {
				if( !ratingOnly ) {
					var comments = parseInt( ( parent.$( 'detail_comments_heading' ).getChildren( 'h2' ).getChildren( 'span')[0].get( 'html' ) ).toString().split( '(' ).join( '' ).split( ')' ).join( '' ), 10 );
					var template = parent.$('detail_comments_template').clone().erase( 'class' );
					var html = template.get( 'html' );
					
					html = html.split( '#firstName#' ).join( firstName );
					html = html.split( '#lastName#' ).join( lastName );
					html = html.split( '#date#' ).join( (new Date()).format("%m/%d/%Y") );
					html = html.split( '#description#' ).join( description );
					
					template.set( 'html', html );
					template.inject( parent.$('detail_comments'), 'top' );
					parent.$( 'detail_comments_heading' ).getChildren( 'h2' ).getChildren( 'span')[0].set( 'html', '(' + (comments+1) + ')' );
				}
				
				$('comments_entry').set( 'html', '<img class="loading" src="site.kaleidoscopecolorado.org/images/mediabox/loading.png" />' );
			}
			
			var request = new Request.JSON({
				method: 'post',
				url:urlComment + nomineeID,
				data: JSON.encode( formData ),
				onSuccess: function(responseText, responseXML) {  
					
					$('comments_success').setStyle( 'display', 'inline-block' );
					$('comments_entry').setStyle( 'display', 'none' );
					//parent.location.reload();
					//parent.Mediabox.close();
				}
			}).send();
		}
		else {
			$('comments_validation').setStyle( 'color', 'red' );	
		}
	}
}

function registerCommentStars() {	

	if( $defined( $('comment_stars') ) ) {		
		
		$$('.comment_star').addEvent('click', function() { setCommentStar( this ); });
		$$('.comment_star').addEvent('mouseenter', function() { setCommentStar( this ); });
				
		var counterComment = new WordCount('descriptionCount', {inputName:'description', countChars:false, limitWords:150 });
	}
}

function setCommentStar( obj ) {	
			
	var rating = obj.get( 'class').split( 'comment_star star_' ).join( '' );
	obj.getParent().removeClass( 'rating_1' ).removeClass( 'rating_2' ).removeClass( 'rating_3' ).removeClass( 'rating_4' ).removeClass( 'rating_5' );
	obj.getParent().addClass( 'rating_' + rating );
	$('rating').set( 'value', rating );
}

function registerGalleryScroller() {	

	if( $defined( $('detail_scroller') ) ) {		
		makeScrollbar( $('detail_scroller'), $('scrollbar1'), $('handle1') );
	}
}

function resetUpoadForm() {
	setSubmitNowSwitch();
}

function registerSubmitNowSwitch( id ) {	

	if( $defined( $('submit_now_middle') ) ) {
		
		$$('.btn_submit_now_middle').addEvent( 'click', function() {
			setSubmitNowSwitch( this.get( 'id' ) );
			return false;
		});
		
		$('numOfPeople').addEvent( 'change', function() {
			setReleaseUploads( parseInt( this.get( 'value' ), 10 ) );
		});		
		$('numOfPeople').fireEvent( 'change' );
		
		$('frmUpload').addEvent( 'submit', function() {
			alert('dd');
			return false;
		});
		
		var counterTile = new WordCount('fileTitleCount', {inputName:'fileTitle', countWords:false, limitChars:50 });
		var counterDesc = new WordCount('fileDescriptionCount', {inputName:'fileDescription', countWords:false, limitChars:250 });
		var counterStory = new WordCount('storyCount', {inputName:'story', countChars:false, limitWords:600 });
		
		if( id != undefined )
			setSubmitNowSwitch( id );
	}
}

function setDisplayByClass( className, display ) {
	$$('.' + className ).each( function( el ) {
		el.setStyle( 'display', display );
	});
}

function setUploadProgress( pct ) {
	$('uploading_status_bar_inner').setStyle( 'width', pct + '%' );
	$('uploading_status_pct').set( 'html', pct + '%' );
}

function submitUpoadForm() {
	
	// clear out values
	uploadQueue = {};
	validation 	= [];
	
	var formFields = $('frmUpload').toQueryString().parseQueryString();
	$each( formFields, function( value, key ) {
		
		if( key.indexOf("imageID") != -1 )
			$(key).set( 'value', '' );
	});
		
	validateForm();
	initUploadQueue();
	
	if( validation.length )
		showErrors( validation );
	else	
		uploadFiles();
		
	/*
	var uploader = new qq.FileUploader({
		element: document.getElementById('btn_upload'),
		action: 'http://www.denverwebcollective.com/client/test/upload.php',
		debug: true
	});
	*/
}

function validateForm() {

	var fields = { 
		'company'			:'Organization Name', 
		'firstName'			:'Contact First Name', 
		'lastName'			:'Contact Last Name', 
		'title'				:'Contact Title', 
		'phone'				:'Contact Phone', 
		'email'				:'Contact Email', 
		'fileTitle'			:'Submission Title', 
		'fileDescription'	:'Your Story', 
		'agreeToTerms'		:'Agree to Terms'
	};
	
	if( $('type').get( 'value' ) == 'narrative' ) {
		fields['story'] = 'Narrative';
	}
	
	$each( fields, function( value, key ) {
		
		if( $(key).get( 'value' ).split( ' ' ).join( '' ) == '' )
			validation.push( value + ' is a required filed.' );
		
		if( key == 'agreeToTerms' && !$(key).get( 'checked' ) )
			validation.push( 'You must agree to the terms to continue.' );
		
		if( key == 'email' && $(key).get( 'value' ).split( ' ' ).join( '' ) != '' && !isValidEmail( $(key).get( 'value' ).split( ' ' ).join( '' ) ) )
			validation.push( 'You must enter in a valid email address to continue.' );
	});
}

function uploadForm() {
	
	$('uploading_heading').set( 'html', 'Uploading Form Data' );
	
	var request = new Request.JSON({
		method: 'post',
		url:urlFormPost,
		data: JSON.encode( $('frmUpload').toQueryString().parseQueryString() ),
		onSuccess: function(responseText, responseXML) {  
			if( responseText != undefined && !responseText.success ) {
				showForm();
				showErrors( responseText.validation );
			}
			else {
				showUploading( 'complete' );
			}	
		}
	}).send();
}


function initUploadQueue() {
	
	var elTemp;
	
	$$('.release_upload').each( function( el ) {
		if( el.getStyle( 'display' ) == 'inline-block' ) {
			elTemp = el.getChildren('input')[0];
			addToUploadQueue( elTemp.get('id'), elTemp.get('id').split( '_' ).join( ' ' ).capitalize(), false );
		}
	});
	
	if( $('type').get( 'value' ) == 'video' ) {
		addToUploadQueue( 'upload', 'Video', false );
	}
	else {
		addToUploadQueue( 'upload_1', 'Narrative Image 1', true );
		addToUploadQueue( 'upload_2', 'Narrative Image 2', true );
		addToUploadQueue( 'upload_3', 'Narrative Image 3', true );
	}
}

function addToUploadQueue( id, display, ignoreValidation ) {
	
	if( $(id) != undefined && $(id).get( 'value' ) != '' )
		uploadQueue[id] = display;
	else if( !ignoreValidation )
		validation.push( display + ' is a required file.' );
}


function uploadFiles() {
	
	var first = true;
	
	$each( uploadQueue, function( value, key ) {
		
		if( first ) {
			
			var uploader = new qq.FileUploaderBasic ({
				 action:urlImageUpload,
				 debug: true,
				 onSubmit: function(id, fileName){        
					setUploadProgress( 0 );
					$('uploading_heading').set( 'html', 'Uploading ' + value + '...' );
				},
				 onProgress: function(id, fileName, loaded, total){        
					setUploadProgress( Math.round(loaded / total * 100) );
				},
				 onComplete: function(id, fileName, result){        
					setUploadProgress( 100 );
					$('imageID_'+key).set( 'value', result['imageID'] );
					delete uploadQueue[key];
					uploadFiles();
				}
			});
			
			uploader._onInputChange( document.getElementById( key ) );
			first = false;
			showUploading( 'start' );
		}
	});
	
	// finally, load the form data
	if( first ) {
		uploadForm();
	}
}

function showErrors( obj ) {
	
	var template = $('validation_template').clone().erase( 'class' );
	var html = template.get( 'html' );
	var out = '';
		
	$each( obj, function( value, key ) {
		
		out += html.split( '#error#' ).join( value );
	});
	$('validation').set( 'html', out );
	Mediabox.open( '#mb_comments', 'comments', '452 449' );
}

function showUploading( state ) {
	
	if( state == 'start' ) {
		
		$$('.form_only').each( function( el ) {
			el.setStyle( 'display', 'none' );
		});
		$$('.uploading_only').each( function( el ) {
			el.setStyle( 'display', 'inline-block' );
		});
	}
	else {
		
		setDisplayByClass( 'uploading_progress_only', 'none' );
		setDisplayByClass( 'uploading_complete_only', 'inline-block' );
	}
}

function showForm() {
	
	setDisplayByClass( 'uploading_progress_only', 'inline-block' );
	setDisplayByClass( 'uploading_complete_only', 'none' );
	
	$$('.form_only').each( function( el ) {
		el.setStyle( 'display', 'block' );
	});
	$$('.uploading_only').each( function( el ) {
		el.setStyle( 'display', 'none' );
	});
}

function setSubmitNowSwitch( id ) {	
		
	var hasID =	( id != undefined );
	
	$('btn_submit_now_video').removeClass( 'selected' );
	$('btn_submit_now_narrative').removeClass( 'selected' );
	
	
	if( !hasID ) {
		$('submit_now_bottom_container').setStyle( 'display', 'none' );
	}
	else {
		var type 				= id.split( 'btn_submit_now_' ).join( '' );
		var displayVideo 		= ( type == 'video' ) ? 'inline-block' : 'none';
		var displayNarrative 	= ( type == 'narrative' ) ? 'inline-block' : 'none';
		
		$('type').set( 'value', type );
		$('submit_now_bottom_container').setStyle( 'display', 'inline-block' );
		$(id).addClass( 'selected' );	
			
		$$('.video_only').each( function( el ) {
			el.setStyle( 'display', displayVideo );
		});
		$$('.narrative_only').each( function( el ) {
			el.setStyle( 'display', displayNarrative );
		});
	}
	
	OverText.update();
}


function setReleaseUploads( num ) {	
		
	var id, display;
	//alert(num );
	$$('.release_upload').each( function( el ) {
		id = el.get( 'id' ).split( 'release_upload_' ).join( '' );
		display = ( id <= num  ) ?  'inline-block' : 'none' ;
		el.setStyle( 'display', display );
	});
}


function registerOverText() {
	
	$$('.has_over_text').each( function( el ) {
		
		new OverText( el );
	});
}

function makeScrollbar(content,scrollbar,handle,horizontal,ignoreMouse){
	var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))
	var slider = new Slider(scrollbar, handle, {	
		steps: steps,
		mode: (horizontal?'horizontal':'vertical'),
		onChange: function(step){
			// Scrolls the content element in x or y direction.
			var x = (horizontal?step:0);
			var y = (horizontal?0:step);
			content.scrollTo(x,y);
		}
	}).set(0);
	if( !(ignoreMouse) ){
		// Scroll the content element when the mousewheel is used within the 
		// content or the scrollbar element.
		$$(content, scrollbar).addEvent('mousewheel', function(e){	
			e = new Event(e).stop();
			var step = slider.step - e.wheel * 30;	
			slider.set(step);					
		});
	}
	// Stops the handle dragging process when the mouse leaves the document body.
	$(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
}

var WordCount = new Class ({

	Implements: [Events, Options],

	options: {
		inputName: null,				//The input name from which text should be retrieved, defaults null
		countWords: true,				//Whether or not to count words
		countChars: true,				//Whether or not to count characters
		charText: 'characters',			//The text that follows the number of characters
		wordText: 'words',				//The text that follows the number of words
		separator: ', ',				//The text that separates the number of words and the number of characters
		liveCount: true,				//Whether or not to use the event trigger, set false if you'd like to call the getCount function separately
		eventTrigger: 'keyup',			//The event that triggers the count update
		limitChars:0,
		limitWords:0
	},

	initialize: function(targetId, options){
		this.setOptions(options);	
		this.target = $(targetId);
		
		if ((this.options.liveCount)&&(this.options.inputName)){
			var input = $(document.body).getElement('[name='+this.options.inputName+']');
			input.addEvent(this.options.eventTrigger, function(){
				this.getCount(input.get('value'),input);
			}.bind(this));
			input.addEvent('enter', function(){
				this.getCount(input.get('value'),input);
			}.bind(this));
			
			this.getCount(input.get('value'),input);
		}
	}, 
	
	getCount: function(text,input){
		var numChars = text.length;
		var numWords = (numChars != 0) ? text.clean().split(' ').length : 0;
		
		if( this.options.limitWords && numWords >= this.options.limitWords ) {
			$(input).set( 'value', text.clean().split(' ').slice( 0, this.options.limitWords ).join( ' ' ) );
			numWords = this.options.limitWords;
		}
		
		if( this.options.limitChars && numChars >= this.options.limitChars ) {
			$(input).set( 'value', text.substr( 0, this.options.limitChars ) );
			numChars = this.options.limitChars;
		}
		
		if ((this.options.countWords) && (this.options.countChars)) {
			var insertText = numWords + ' ' + this.options.wordText + this.options.separator + numChars + ' ' + this.options.charText;
		} else {
			var insertText = (this.options.countWords) ? numWords + ' ' + this.options.wordText : numChars + ' ' + this.options.charText;
		} 
		if (insertText){ this.target.set('html', insertText); if( OverText != undefined ) { OverText.update(); } }	
	}
});

