//Logger.log_level = CW_LOG_DEBUG;

// Namespace for all live-side stuff
Clockwork.Live  =  { };

// Spot for components to put their live-side js
Clockwork.Live.Components  = { };

Clockwork.Live.component_events  = { };  // e custom events
Clockwork.Live.page_components  = [];    // all the components on a page

 // Superclass for Live Components
Clockwork.Live.Components.Component = Class.create( {

	initialize:function( args ) {

		this.component_id = args.component_id;

		this.component_el = $('component_'+this.component_id);

		this.component_type = args.component_type;

		Clockwork.Live.page_components.push( this );

	},


	update : function( action, parms, onComplete ) {

		parms = parms || {};

		parms['action_' + this.component_id] = action;
		parms.json = 1;

		var message_target = null;

		if ( parms.message_target ) {
			message_target = parms.message_target;
		}
		else {

			if ( $$('.message').length > 0 ) message_target = $$('.message')[0];

			if ( $('messages_' + this.component_id) ) message_target = $('messages_' + this.component_id );

		}

		onComplete  =  onComplete || Prototype.emptyFunction;

		var updateComplete = function( ) {
			this.component_el = $('component_'+this.component_id);
			onComplete();
		}


        new Clockwork.Ajax.Updater( this.component_el,
									location.href, 
                                    {'method'         :  'post',
                                    'replace'         :  true,
                                    'parameters'      :  parms,
                                    'message_target'  :  message_target,
                                    'asynchronous'    :  true,
                                    'evalScripts'     :  true,
                                    'onComplete'      :  updateComplete.bind( this ) } );

	}

} );


Clockwork.Live.Components.TextpanderComponent = Class.create( Clockwork.Live.Components.Component, {

	initialize:function( $super, args ) {

		$super( args );

		this.component_el = $('component_'+this.component_id);
		this.headline_el = $$('#component_'+this.component_id+' .headline')[0];
		this.toggle_el = $$('#component_'+this.component_id+' .toggle')[0];
		this.toggle_open_el = $$('#component_'+this.component_id+' .toggle .open')[0];
		this.toggle_closed_el = $$('#component_'+this.component_id+' .toggle .closed')[0];
		this.content_el = $$('#component_'+this.component_id+' .content')[0];


		this.animate_images = null;

		if (args.animate_images) {
			this.animate_images = args.animate_images;
			this.animate_images.open_image_el = $$('#component_'+this.component_id+' .toggle .open img')[0];
			this.animate_images.closed_image_el = $$('#component_'+this.component_id+' .toggle .closed img')[0];
		}

		Event.observe(this.headline_el, 'click',this.toggle.bind(this));

	},


	toggle : function() {
		var d = this.content_el.getStyle('display');

		this.toggle_open_el.removeClassName( 'initial' );
		this.toggle_closed_el.removeClassName( 'initial' );

		if ( d == 'none' ) {
			this.toggle_open_el.hide();
			this.toggle_closed_el.show();
			if ( this.animate_images ) {
				this.animate_images.open_image_el.src = this.animate_images.closed;
				this.animate_images.closed_image_el.src = this.animate_images.opening;
			}
			
			CWjQuery(this.content_el).slideToggle();
			//Effect.BlindDown(this.content_el, {duration:.5, queue:'end'});

		} else {
			this.toggle_open_el.show();
			this.toggle_closed_el.hide();

			if ( this.animate_images ) {
				this.animate_images.open_image_el.src = this.animate_images.closing;
				this.animate_images.closed_image_el.src = this.animate_images.open;
			}
			
			CWjQuery(this.content_el).slideToggle();
			//Effect.BlindUp(this.content_el, {duration:.5, queue:'end'});
		}
	}


} ) ;



Clockwork.Live.Components.GallerySingleImageComponent = Class.create( Clockwork.Live.Components.Component, {

	initialize:function( $super, args ) {

		$super( args );
		this.gallery_id= args.gallery_id;
		this.component_el = $('component_'+this.component_id);
		
	},

	ajaxReload : function( gallery_asset_href ) {

		gallery_asset_href += '&action_' + this.component_id + '=ajax_reload&json=1';

        new Clockwork.Ajax.Updater( this.component_el,
									gallery_asset_href, 
                                    {'method':'get',
									'replace':true,
                                    parameters:{},
                                    asynchronous: true,
                                    evalScripts: false,
                                    onComplete:this.ajaxReloadComplete.bind( this ) } );

	},

	ajaxReloadComplete : function( rsp ) {
		this.component_el = $('component_'+this.component_id);
	}

} );


Clockwork.Live.Components.GalleryIndexComponent = Class.create( Clockwork.Live.Components.Component, {

	initialize : function( $super, args ) {

		$super( args );
		this.gallery_id= args.gallery_id;
		this.component_el = $( 'component_' + this.component_id );
		this.link_els = $$( '#component_' + this.component_id + ' a' );

		if ( ! args.is_lightbox_gallery ) {
			this.initialize_inline( );
		}
		
	},
	
	initialize_inline: function ( ) {
		this.link_els.each( function( link_el ) {

			var asset_href = link_el.readAttribute( 'href' );
			
			link_el.writeAttribute( {'href' : 'javascript:;' } );
			Event.observe( link_el, 'click', this.ajax_switch_asset.bind( this, asset_href, link_el ) );

		}.bind( this ) );	
	},

	ajax_switch_asset : function( asset_href, current_link_el ) {

		// find a GallerySingleImageComponent on the page with the same gallery id
		var image_component = null;

		for ( var i=0 ; i< Clockwork.Live.page_components.length ; i++ ) {

			var c = Clockwork.Live.page_components[i];

			if ( ( c.component_type == 'gallery_single_image' || c.component_type == 'ace_gallery_single_image') && c.gallery_id == this.gallery_id ) {

				image_component = c;
				break;

			} 

		}

		if ( image_component ) {

			image_component.ajaxReload( asset_href );

		}

		this.index_els = $$( '#component_' + this.component_id + ' li' );

		this.index_els.each( function( index_el ) {

			index_el.removeClassName( 'current' );
	
		} );
		

		$(current_link_el.parentNode).addClassName( 'current' );

	}	

} );

Clockwork.Live.Components.PageRatingComponent = Class.create( Clockwork.Live.Components.Component, {

	initialize:function( $super, args ) {

		$super( args );

		this.rating_type = args.rating_type;

		this.allow_comment = ( args.allow_comment == '1' ) ? true : false;

	},

	rate : function( value ) {

		this.current_value = value;

		if ( ! this.allow_comment ) {
			this.submit_rating( )
		}
		else {

			var rating_comment_el = this.component_el.down( '.rating_comment' );

			if ( rating_comment_el ) {
				rating_comment_el.show();
			}
			
		}

	},

	submit_rating : function( ) {

		var comment_el = this.component_el.down( 'textarea' );
		var comment = ( comment_el ) ? comment_el.value : null;

		var parms = { 'rating' : this.current_value,
		              'comment' : comment };

		this.update( 'rate', parms );

	}


} );




Clockwork.Live.Components.ASKSurveyComponent = Class.create( Clockwork.Live.Components.Component, {

	initialize:function( $super, args ) {

		$super( args );
		this.survey = args.survey;
		this.chart_color = '8cace9';
		this.progress = args.progress;
		this.total_questions = args.total_questions;
		this.questions = args.questions; // current questions to display
		this.component_el = null;
		this.survey_contents_el = null;
		this.survey_messages_el = null;
		this.back_button_el = null;
		this.next_button_el = null;
		this.progress_bar_el = null;
		this.component_el = $('component_'+this.component_id);

		this.load_barebones_html( );
	},

	load_barebones_html: function ( ) {
		/* Now that we're ready, ask the server for the bare-bones HTML to load the JSON data into*/
		var parameters  =  { };
		parameters['action_' + this.component_id]  =  'initialize';

		parameters  =  this.add_parameters_hook( parameters );

		/* We call this.display( ) on completion to populate the HTML */
		var options  =  { method      :  'post',
						  parameters  :  parameters,
						  onComplete  :  this.display.bind( this ) };

		new Ajax.Updater( { success: 'component_' + this.component_id }, location.href, options );
	},

	add_parameters_hook: function ( parameters ) {
		// Override in subclasses to add parameters necessary for any POSTs
		return parameters;
	},

	display: function( ) {

		if ( this.component_el == null) {
			this.component_el = $('component_'+this.component_id);
		}

		if ( this.survey_contents_el == null) {
			this.survey_contents_el = $$('#component_'+this.component_id+' .survey_contents')[0];
		}

		if ( this.survey_messages_el == null) {
			this.survey_messages_el = $$('#component_'+this.component_id+' .survey_messages')[0];
		}

		if ( this.progress_bar_el == null) {
			this.progress_bar_el = $$('#component_'+this.component_id+' .progress')[0];
		}

		if ( this.back_button_el == null) {
			this.back_button_el = $('component_'+this.component_id+'_back_button');
		}

		if ( this.next_button_el == null) {
			this.next_button_el = $('component_'+this.component_id+'_next_button');
		}


		var question_contents = '';

		for (var i=0; i<this.questions.length; i++) {
			question_contents += this.questions[i].html;
		}

		var contents = question_contents;
		
		var show_back_button = ( this.questions[0].sequence_index > 0 ) ? true: false;
		var show_next_button = true;


		if ( this.back_button_el != null ) {	
			if (show_back_button) {
				this.back_button_el.show();
			} else {
				this.back_button_el.hide();
			}
		}

		if ( this.next_button_el != null ) {	
			if (show_next_button) {

				var button_texts  =  this.button_texts || Clockwork.Live.Components.ASKSurveyComponent.button_texts;
				var next_button_text = button_texts[ 'next' ];
				if ( this.questions[ this.questions.length-1 ].question_number >= this.survey.highest_question_number ) {
					next_button_text = button_texts[ 'submit' ];
				}
				this.next_button_el.innerHTML = next_button_text;
				this.next_button_el.show();
			} else {
				this.next_button_el.hide();
			}
		}

		this.survey_contents_el.innerHTML = contents;

		this.hookup_events();
		this.update_progress();

	},

	highlight_errors : function( messages ) {
		var question_ids = Object.keys( messages );
		for (var i=0;i<this.questions.length;i++) {

			var question_id = this.questions[i].question_id;

			field_id = 'component_' + this.component_id + '_question_' + question_id;

			field_message_id = field_id+'_messages';

			if ( ! $( field_message_id ) ) {
				continue;
			}
		
			if (question_ids.include(question_id)) {

				Element.addClassName(field_id, 'submission_error');
				
				var field_messages		= messages[ question_id ];
				var field_messages_text	= '';
				
				for (var j=0;j<field_messages.length;j++) {
					var message = field_messages[j];
					message = this.format_message( message );
					field_messages_text += message;
				}
				
				$( field_message_id ).update( field_messages_text );
				
			} else {

				Element.removeClassName(field_id, 'submission_error');
				$( field_message_id ).update( '' );

			}

		}

		window.scrollTo( 0, 0);
	},

	hide_messages : function(messages) {

		this.survey_messages_el.innerHTML = '';
		this.survey_messages_el.hide();

	},
	
	format_message : function(message) {

		message = message.replace(/\[e\](.+)/g, function($str, $1) { return '<div class="message error"/>'+$1+'</div>';});
		message = message.replace(/\[i\](.+)/g, function($str, $1) { return '<div class="message info"/>'+$1+'</div>';});
		message = message.replace(/\[w\](.+)/g, function($str, $1) { return '<div class="message warn"/>"'+$1+'</div>';});
		
		return message;
	},

	show_messages : function(messages) {

		var message_text = '<div class="message"/>Please correct the following errors:</div>';
		/*
		var message_fields = Object.values(messages);
		for (var i=0;i<message_fields.length;i++) {
			var message_field = message_fields[i];

			for (var j=0;j<message_field.length;j++) {
				var message = message_field[j];
				message = this.format_message( message );
				message_text += message;
			}
		}
		*/
		this.survey_messages_el.innerHTML = message_text;
		this.survey_messages_el.show();

	},

	hookup_events : function () {

		Event.stopObserving(this.back_button_el, 'click');
		Event.stopObserving(this.next_button_el, 'click');

		if ( this.back_button_el ) {
			Event.observe(this.back_button_el, 'click',this.go_back.bind(this));
		}
		if ( this.next_button_el ) {
			Event.observe( this.next_button_el, 'click',this.go_next.bind(this));
		} 

	},


	go_next : function() {
		// client-side validate

		var answers = this.collect_answers();
		
		// send answers back, get next set of questions
		var parameters = {
			'survey_id': this.survey.survey_id
			,'answers': Object.toJSON( answers )
		};

		parameters['action_'+this.component_id] = 'get_next';

		parameters  =  this.add_parameters_hook( parameters );

		this.hide_messages();
		new Effect.Morph(this.survey_contents_el,{style:'opacity:0', duration:.5});

		new Ajax.Request(location.href,  {
		method:'post',
		parameters:parameters,
		onSuccess: function(rsp){
			var response = rsp.responseText || "no response text";
			jsondata = eval('('+response+')');
			if (jsondata.success) {
				if (jsondata.survey_complete) {
					
					// redirect using POST so that conditional content rules are followed
					var component_container = $( 'component_' + this.component_id );
					var redirect_form_el = new Element( 'form', { 
																	id: 'component_' + this.component_id + '_redirect_form',
																	name: 'component_' + this.component_id + '_redirect_form',
																	method: 'post'
																} );
																
					var post_value = new Element( 'input', { name: 'post_value_' + this.component_id, type: 'hidden', value: '1' } );
					redirect_form_el.insert( post_value );
					component_container.insert( redirect_form_el );

					if ( jsondata.redirect_url ) {
						
						redirect_form_el.action = jsondata.redirect_url;
						post_value.remove();
						redirect_form_el.submit( );
						
						return;
					}

					if ( this.survey.end_page_type == 'internal') {
						
						redirect_form_el.action = this.survey.end_page_url_internal;
						redirect_form_el.submit( );
						
						return;
					}
					else if ( this.survey.end_page_type == 'external' ) {
						window.location = this.survey.end_page_url;
						return;
					}
					else { // no end page set, show thankyou message
						this.component_el.replace(jsondata.complete_html);
						return;
					} 
				} else {
					this.progress = jsondata.progress;
					this.questions = jsondata.questions;
					this.display();
					new Effect.Morph(this.survey_contents_el,{style:'opacity:1', duration:.5});

				}
			} else {
				new Effect.Morph(this.survey_contents_el,{style:'opacity:1', duration:.5});
				this.show_messages(jsondata.messages);
				this.highlight_errors(jsondata.messages);
			}
		}.bind(this),
		onFailure: function(rsp){ log('Something went wrong: '+rsp) }
	  });
	},

	go_back : function() {

		var answers = this.collect_answers();

		// send answers back, get next set of questions
		var parameters = {
			'survey_id': this.survey.survey_id
			,'answers': Object.toJSON( answers )
		};

		parameters['action_'+this.component_id] = 'get_previous';

		parameters  =  this.add_parameters_hook( parameters );

		this.hide_messages();
		new Effect.Morph(this.survey_contents_el,{style:'opacity:0', duration:.5});

		new Ajax.Request(location.href,  {
		method:'post',
		parameters:parameters,
		onSuccess: function(rsp){
			var response = rsp.responseText || "no response text";
			jsondata = eval('('+response+')');
			if (jsondata.success) {
				this.progress = jsondata.progress;
				this.questions = jsondata.questions;
				this.display();
				new Effect.Morph(this.survey_contents_el,{style:'opacity:1', duration:.5});
			} else {
				new Effect.Morph(this.survey_contents_el,{style:'opacity:1', duration:.5});
				this.show_messages(jsondata.messages);
				this.highlight_errors(jsondata.messages);
			}
		}.bind(this),
		onFailure: function(rsp){ log('Something went wrong: '+rsp) }
	  });
	},

	update_progress : function() {
		// the progress bar may not be in the template, in which case return.
		if ( this.progress_bar_el == null ) return;

		if (this.total_questions <= 1 || this.questions.length == this.total_questions) {
			$$('#component_'+this.component_id+' .progress_bar')[0].hide();
			$$('#component_'+this.component_id+' .progress_label')[0].hide();
			return;
		}
		var outer_width = $$('#component_'+this.component_id+' .progress_bar')[0].getWidth();
		width = Math.floor(this.progress * outer_width);

		var post_morph_effect = function() {window.scrollTo( 0, 0);};

		new Effect.Morph(this.progress_bar_el,{style:'width:'+width+'px;', duration:.5, afterFinish:post_morph_effect});

	},

	collect_answers : function() {
		var answers = [];
		for (var i=0;i<this.questions.length;i++) {
			var question = this.questions[i];
			var answer = {'question_id':question.question_id,'text':''};

			// Do not store answers to rich texts and sections
			if (question.question_type == 'rich_text' || question.question_type == 'section') {
				continue;
			}

			if ( question.answer_type == 'text' || question.answer_type == 'textarea' ) {
				answer.text = $('component_'+this.component_id+'_question_'+question.question_id+'_answer').value;
			} else if (question.answer_type == 'option') {
				var selected_answer = null;
				if ( question.option_type == 'dropdown') {
					selected_answer = this.get_selected($('component_'+this.component_id+'_question_'+question.question_id+'_options'));
				}

				var selected_values = [];
				var selected_option_ids = [];
				for (var j=0;j<question.options.length;j++) {
					var option = question.options[j];
					var option_id = 'component_'+this.component_id+'_question_'+question.question_id+'_option_'+option.option_id;

					if ( question.option_type == 'dropdown') {

						if ( $(option_id).value == selected_answer ) {
							selected_values.push($(option_id).value);
							selected_option_ids.push(option.option_id);
						}

					} else {
						if ( $(option_id) && $(option_id).checked) {
							selected_values.push($(option_id).value);
							selected_option_ids.push(option.option_id);
						}
					}
				}
				answer.text = selected_values.join(',');
				answer.option_id = selected_option_ids.join(',');
			}
			answers.push(answer);
		}
		return answers;
	},

	get_selected : function(el) {
		if (el.selectedIndex == -1) return '';
		return el.options[el.selectedIndex].value;
	}


} );




Clockwork.Live.Components.ASKSurveyComponent.button_texts = {'back':'Back', 'next':'Next', 'submit':'Submit'};

Clockwork.Live.Components.DCMDataCaptureComponent = function( args ) {
    this.component_id = args.component_id;
    this.step = args.step;
    this.component_el = $('component_'+this.component_id);

    this.update_decedent_info_options = function() {
        this.estate_will_be_filed_container_el.hide();
        this.family_atty_exists_container_el.hide();
        this.estate_atty_exists_container_el.hide();

        if (this.estate_filed_option_els[0].checked) {
            this.estate_atty_exists_container_el.show();
        }

        if (this.estate_filed_option_els[1].checked || this.estate_filed_option_els[2].checked) {
            this.estate_will_be_filed_container_el.show();
            this.family_atty_exists_container_el.show();
        }
    }

    this.estate_filed_container_el = $('estate_filed');

    if (this.estate_filed_container_el) {
        this.estate_filed_option_els = this.estate_filed_container_el.select('input');

        this.estate_atty_exists_container_el = $('estate_atty_exists');
        this.estate_atty_exists_option_els = this.estate_atty_exists_container_el.select('input');

        this.estate_will_be_filed_container_el = $('estate_will_be_filed');
        this.family_atty_exists_container_el = $('family_atty_exists');


        for (var i=0;i<this.estate_filed_option_els.length;i++) {
            Event.observe(this.estate_filed_option_els[i], 'change', this.update_decedent_info_options.bind(this));
            /* Needed for IE7 */
            Event.observe(this.estate_filed_option_els[i], 'mouseup', function(){setTimeout(this.update_decedent_info_options.bind(this),100)}.bind(this));
        }

        for (var i=0;i<this.estate_atty_exists_option_els.length;i++) {
            Event.observe(this.estate_atty_exists_option_els[i], 'change', this.update_decedent_info_options.bind(this));
            /* Needed for IE7 */
            Event.observe(this.estate_atty_exists_option_els[i], 'mouseup', function(){setTimeout(this.update_decedent_info_options.bind(this),100)}.bind(this));
        }

        this.update_decedent_info_options();
    }


};


