var reloadOnClose = false;

// Takes a single element and catches 'onClick' to update the modal window
makeLinkModal = function(currentModalLink){

	currentModalLink.observe('click', function(event){
		new Ajax.Updater(modal.container, currentModalLink.readAttribute('href'), {
			method: 'get',
			evalScripts: true,
			onComplete: function(){
				modal.open();

				$('empty_modal').select('.close_button').each( function(element){
					element.observe("click", function(event){
						modal.close();
						Event.stop(event);
					});
				});
			}
		});

		Event.stop(event);
	});
}

// Takes a single element and catches 'onClick' to update the video modal window
makeLinkVideoModal = function(currentModalLink){

	currentModalLink.observe('click', function(event){
		new Ajax.Updater('empty_video_modal', currentModalLink.readAttribute('href'), {
			method: 'get',
			evalScripts: true,
			onComplete: function(response){
				video_modal.open();

				$('empty_video_modal').select('.close_button').each( function(element){
					element.observe("click", function(event){
						video_modal.close();
						Event.stop(event);
					});
				});
			}
		});

		Event.stop(event);
	});
}

// Takes an array of elements and catches them 'onClick' to update the modal window
makeLinksModal = function(linksArray){

	linksArray.each( function(currentModalLink){
		makeLinkModal(currentModalLink);
	});
}


// Globalise the modal object
var modal;
var video_modal

document.observe("dom:loaded", function() {

	// Create one modal box for all modal content
	modal = new Control.Modal('empty_modal',{
		fade: false,
		overlayOpacity: 0.25,
		fadeDuration: 0.25,
		width: 580,
		className: 'modal_window',
		afterClose: function(){
			modal.remoteContentLoaded=false;
			modal.container.update('');
			if ( reloadOnClose ){
				location.reload();
			}
		}
	});

	// Create one modal box for all modal video content
	video_modal = new Control.Modal('empty_video_modal',{
		fade: true,
		overlayOpacity: 0.75,
		fadeDuration: 0.45,
		width: 630,
		className: 'modal_window',
		afterClose: function(){
			video_modal.remoteContentLoaded=false;
			video_modal.container.update('');
			if ( reloadOnClose ){
				location.reload();
			}
		}
	});

	
	// Close the modal and reload the page - can be called from the modal window
	closeAndReload = function(){
		modal.container.update('');
		modal.container.hide();
		location.reload();
	}


	// Find all modal links and apply function
	makeLinksModal( $$('a.modal_link') ); 

	// Replace all standard tickertapes
	$$('.flash_tickertape').each( function(element){

		// Checks for a hyperlink and extracts the URL for use in flash params
		if ( element.down('a') ){
			hyperlink = element.down('a').readAttribute("href");
			params = {text: element.innerHTML.stripHTML(), is_onred: 'true', url: hyperlink};
		} else {
			params = {text: element.innerHTML.stripHTML()};
		}

		params.site_colour = site_colour;

		// Replace the div with a flash tickertape
		replaceTickerTape( element.readAttribute('id'), params );
		
	});
 

	$$('a.protectedUrl').each( function(element){
		element.observe('click', function(event){
			alert(commonSubTexts_json.msg_sharingprotectedcontent);
		});
	});

	/////////////////////
	// Reload page if language changed
	/////////////////////
	$('language-select').observe('change',function(event){
		$('language-form').submit();
	})


 	// Catch all hyperlinks to /modalvideos/ and cause to open in modal window instead
	$$('a').each( function(element){
		if ( element.readAttribute("href") ){

			if ( element.readAttribute("href").toString().include("/modalvideos/") ){
				makeLinkVideoModal(element);
			}

		}
	});


}); 


// Function to strip HTML from text and return
String.prototype.stripHTML = function() {
    var matchTag = /<(?:.|\s)*?>/g;
    return this.replace(matchTag, "");
};


// Replace ticker tape flash div
function replaceTickerTape( flash_div, flash_variables ){

	// Duplicate content into a print-only div
	$(flash_div).update('<div class=\"flash_element\" id=\"' + $(flash_div).readAttribute('id') + '_flashelement\">' + $(flash_div).innerHTML + '</div>' + '<div class=\"flash_alternative\">' + $(flash_div).innerHTML + '</div>');

	swfobject.embedSWF("/data/energize/assets/flash/ticker_tape.swf", $(flash_div).readAttribute('id') + '_flashelement', "435", "80", "8.0.0", '', flash_variables, {menu: "false", wmode: "opaque"});
}


// Globalise commonSubTexts_json
var commonSubTexts_json = {};

// Get all common subtexts and place into JSON for general use
new Ajax.Request("/data/energize/scripts/subtext_json_ajax.php", {
	onSuccess: function(transport){
		commonSubTexts_json = transport.responseText.evalJSON(true);
	}
});


function textCounter(fieldname,maxlimit) {
      if (fieldname.value.length > maxlimit) // if too long...trim it!
      fieldname.value = fieldname.value.substring(0, maxlimit);
      // otherwise, update 'characters left' counter
      else
//     cntfield.value = maxlimit - field.value.length;
      $('char_remaining').update(maxlimit - fieldname.value.length);
}


// Function to make any element follow the users view, so when scrolling the box remains in view
function elementFollowWindow(element){
	var originalOffY = element.offsetTop;
	var topPadding = 10;

	window.onscroll = function(){

		// If pageYOffset not found then use IE compliant method
		if( typeof( window.pageYOffset ) != 'number' ) {
			scrollOffY = document.documentElement.scrollTop;
  			} else {
			scrollOffY = window.pageYOffset;
		}

		if ( scrollOffY > originalOffY - topPadding ){
			newXPos = scrollOffY - originalOffY + topPadding;
		} else {
			newXPos = 0;
		}

		var queue = Effect.Queues.get('meetingplan_scroll');
		queue.each(function(effect) { effect.cancel(); });

		element.morph({ paddingTop: newXPos + 'px' }, { duration: 0.4, queue: {position: 'end', scope: 'meetingplan_scroll'} });

	}
}


// Apply needed JS to comment modal box
function activateMakeSuggestion(){

	if($('js_savesuggestion')){
		$('js_savesuggestion').observe("click", function(event){
			if(document.postcomment.comment.value.length=="0") {
				Event.stop(event);
			} else {
				var formValues = $("postcomment").serialize();
				var submitUrl = $("postcomment").readAttribute('action');

				new Ajax.Updater('empty_modal', submitUrl, {
					evalScripts: true,
					parameters: formValues
				});

				Event.stop(event);
			}					
		});
	}

	if($$('.close_button')){

		$$('.close_button').each( function(element){
			element.stopObserving("click");
			element.observe("click", function(event){
				Control.Modal.close();
				Event.stop(event);
			});

		});
	}
}
