/*
Author: Andrew Masri 
Eye candy and stuff to hide/reveal content
*/


//var bgImageWidthNarrow = '69.7%'; NOW DEFINED IN config.js



	//image related TO DO LIST after the page has loaded
	addOnloadEvent(function() {
		
		//when the page has finished loading enable less important images to load - these have class="loadLast" and source="...."
		//copy the fake "source" attribute to the valid "src" attribute to cause the images to be finally loaded
		jQuery('.loadLast').each(function (){
			var src = jQuery(this).attr('source');
			jQuery(this).attr('src', src);
		});
		
		jQuery('.displayOnload').css("display", "block");	//display content that is hidden until the page has loaded
		
		onloadBgImage();	//fade in the bgImage and display the image title
		
		upgradeImages();	//replace any low quality background images with their hi quality counterpart 

		initBgImageCycling();	//cycle the pages background images - if this function is enabled			
	});



	//replace any low quality (marked with "upgradeMe") with it's hi quality counterpart
	function upgradeImages() {
		//find any upgradeable images
		jQuery('.upgradeMe').each( function() {
			var upgradeImage = jQuery(this);
			var replacementUrl = replaceThumbnail(this.src);	//determine the url of the high-quality image
			
			if (this.src != replacementUrl) {
				//load the image somewhere it won't be noticed
				jQuery('body').append('<img id="loadingImage" src="'+replacementUrl+'" style="width:1px;"/>');
				jQuery('#loadingImage').load(function(){
					upgradeImage.attr('src', replacementUrl); //upgrade the upgradeable image
					upgradeImage.removeClass('upgradeMe'); //remove the class marker
					jQuery('#loadingImage').remove(); //remove hidden loader image
				});
			}
		});
	}
	
	


	//used to fade in the background image - but only when it has fully loaded
	function onloadBgImage() {
		if (bgImg = jQuery('.autoResize')[0]) {

			//display content that is hidden until the page has loaded - this must be done before checking the image dimensions as IE requires elements to be visible for this
			jQuery('.displayOnload')[0].style.display = "block";

			//make the bgimage and similiar items transparent initially 
			jQuery('.autoResize').css("opacity", "0.0");
			jQuery('.bgFade').css("opacity", "0.0");
	
			switch (bgImageOption) {
				case 'constantHeight':
					bgImg.style.height = jQuery(window).height() - 25 +'px';	//auto fit bgImage to the window height
					bgImg.style.width = 'auto';
				//	bgImg.style.maxWidth = jQuery(window).width();
					jQuery('.autoResize').animate({ opacity: 1.0 }, 1000);
					break;
				
				case 'dualWidth':
					if (bgImg.width / bgImg.height > aspectRatioThreshold) {
						bgImg.style.width = '100%';

						//fade in the bacground image and other transparent elements
						jQuery('.autoResize').animate({ opacity: 1.0 }, 1000);
						jQuery('.bgFade').animate({ opacity: 0.0 }, 1000).animate({ opacity: 1.0 }, 2000);		//unfortunately, for IE, setting opacity destroys opacity in png images
					}
					else {
						bgImg.style.width = bgImageWidthNarrow;

						//fade in the bacground image and other transparent elements
						jQuery('.autoResize').animate({ opacity: 1.0 }, 1000);
						jQuery('.bgFade').animate({ opacity: 1.0 }, 1000);		//unfortunately, for IE, setting opacity destroys opacity in png images
					}
					break;			

				default:
					break;
			}
			

			if (bgImg.width > 100) {
				document.getElementById('mainContentContainer').style.minHeight = "100px";	// allow image to determine height
			}


			//the background image's title
			jQuery('#bgImageTitle').text(bgImg.title);
		}
	}




//////////////// Background Image Cycling Functions /////////////////////
	var bgImageTimerId = 0;
	var bgImageIndex = 0;	//this is the current image (on page load)
	var bgImages = new Array();


	//cycle the pages background images - if this function is enabled
	function initBgImageCycling() {
		if (cycleBgImages && jQuery('#bgImageNext').length) {

			//start the sequencing clock
			var bgImageTimerId = setTimeout ( "changeBgImage()", initBgImageDelay );	//start the sequencing timer which is used for the transition effects
			
			//get a list of background images
			i=0;
			jQuery('.imageQueue').each(function (){
				bgImages[i++] = document.getElementById(jQuery(this).attr('id'));
			});
			
		}		
	}



	//fade in the next background image and set the timer for the next bgImage transition
	function changeBgImage() {
		if (!cycleBgImages) { return; }	//the slideshow can be terminated when a user manually selects an image
	
		bgImageTimerId = setTimeout("changeBgImage()", bgImageInterval); //setup next timer event

		//next image
		if (++bgImageIndex == bgImages.length) {
			bgImageIndex = 0;
			if (!cycleBgImagesForever) {
				clearTimeout ( bgImageTimerId );			//stop cycling the background images
				cycleBgImages = false;						//signal to other processes that the cycling is inactive
				return;
			}
		}
		newImage = bgImages[bgImageIndex];
		oldImage = jQuery('#bgImage')[0];
		
		switchImage(oldImage, newImage, 'crossfade');
		
	}





/////////////////// Functions to allow Background Image Management /////////////////////

	var fileRef = false;	//this is used to pass data between these 2 functions
	var fileManager = false;	//the file manager window
	
	//called by File Manager app to save the selected image (or file)
	function saveImage(url) {
		//if a ckeditor window isn't open to accept the file then save it directly to server  
		if (!ckeditorInsertImage(url)) {
			//standlone filemanager mode - save directly to the server
			if (url.indexOf('&') != -1) {alert('web file names may not contain "&". Please rename the file.'); return;}
			url = replaceThumbnail(url)
			Post.Send('pageRef='+fileRef+'&pageId='+pageId+'&url='+encodeURI(url), base_url+'dataserver/ajaxInsertImage');
		}  
	}

	
	//open the File Manager app in a new window in order allow the user to upload/select an image
	function launchFilemanager(ref) {
		fileRef = ref;
//		var newwindow = window.open(base_url+'ajaxfilemanager/ajaxfilemanager.php', 'ajaxFileManager', 'width=782,height=500');
		if(!fileManager || fileManager.closed) {
			fileManager = window.open(base_url+'kfmFileManager/index.php?startup_folder='+uploadPath, 'FileManager', 'width=800, height=500, alwaysRaised=1, location=0, status=0');

			jQuery(window).bind('focus click', function() { fileManager.focus(); });	//don't let the filemanger get lost behind the parent window

		} else {
			fileManager.focus()
		}
		return false;
	}


	//opens the image finder dialog
	function launchFileFinder(ref) {
		fileRef = ref;
		popupDialog('#fileFinder');
	}
	
	
	


	//this function switches the target image and sets the appropriate image thumbnail in the image menu 
	function trySwitchImage(targetId, newImage){
		if (cycleBgImages) {
			clearTimeout ( bgImageTimerId );															//user has manually selected a bgImage thumbnail - stop auto cycling the background images
			jQuery('#bgImageNext').animate({ opacity: 0.0 }, crossfadePeriod).css('z-index', '-1');		//lose the duplicate crossfade image
			jQuery('#bgImage').css('z-index', '1');														//restore the main bg image
			cycleBgImages = false;																		//remember that we've finished cycling
		}	
		
		var oldImage = document.getElementById(targetId);

		if (oldImage.src != newImage.src) {		//check that the new image has not already been loaded
			var testImg = new Image;		
			testImg.src = newImage.src;			//first assign the url to a new test image
			if (testImg.onload) {
				testImg.onload = switchImage(oldImage, newImage, false);	//mozilla
			} else {
				switchImage(oldImage, newImage, false);
//				testImg.onreadystatechange = switchImage(oldImage, newImage);	//internet explorer
			}
		}
	}
	
	
	//this function replaces the old image with the new image - but doesn't check if the new image exists
	function switchImage(oldImage, newImage, effect) 		
	{		
		//halt any existing animations
		jQuery('.bgFade').stop(true);
		jQuery('#'+oldImage.id).stop(true);



		//unselect the old menu item and make it into a link item
		var imageMenu = document.getElementById('bgImageMenu');
		var thumbnail = imageMenu.getElementsByTagName("img");
		for (var i = 0; i < thumbnail.length; i++) {
			if (thumbnail[i].className != 'editorLink') {
				thumbnail[i].className = 'imageQueue';
				thumbnail[i].onmouseover = function(){
					hover(this);
				};
				thumbnail[i].onmouseout = function(){
					unhover(this);
				};
				
			}
		}
		//select the new image menu item and make it unclickable
		newImage.className = 'selected imageQueue';
//		newImage.click = '';
		newImage.mouseover = '';
		newImage.mouseout = '';
		
		if (effect) {
			//crossfade images to create a morph effect

			//set new image transparent and load it
			jQuery('#bgImageNext').css("opacity", "0.0").attr('src', newImage.src);

			//set the new image width based on it's aspect ratio
			nextImage = document.getElementById('bgImageNext');

			switch (bgImageOption) {
				case 'constantHeight':
					nextImage.style.height = jQuery(window).height() - 25 +'px';	//auto fit bgImage to the window height
					nextImage.style.width = 'auto';
					break;
				
				case 'dualWidth':
					if (nextImage.width / nextImage.height > aspectRatioThreshold) {
						nextImage.style.width = '100%';
					}
					else {
						nextImage.style.width = bgImageWidthNarrow;
					}
					break;			

				default:
					break;			
			}



			//crossfade the old/new images
			jQuery('#'+oldImage.id).animate({ opacity: 0.0 }, crossfadePeriod);

			jQuery('#bgImageNext').animate({ opacity: 1.0 }, crossfadePeriod, function(){	nextImage.style.zIndex = '1';
																							oldImage.style.zIndex = '0';
																							nextImage.id = 'bgImage';
																							oldImage.id = 'bgImageNext';
																						});
		} else {
			//create a sequential fade effect
			
			//replace the old image with the new image
			//fade out both the bgImage and other content 
			jQuery('.bgFade').animate({ opacity: 0.0 }, 500);
			jQuery('#bgImageNext').animate({ opacity: 0.0 }, 500);
			//switch the bgImages and fade-in the bgImage and other content - but provide a few seconds to display full-width images before fading in content that covers it   
			jQuery('#'+oldImage.id).animate({ opacity: 0.0 }, 500, function(){	oldImage.src = newImage.src; 
																				oldImage.title = newImage.title;

																				switch (bgImageOption) {
																					case 'constantHeight':
																						oldImage.style.height = jQuery(window).height() - 25 +'px';	//auto fit bgImage to the window height
																						oldImage.style.width = 'auto';
																						break;
																					
																					case 'dualWidth':
																						if (newImage.width / newImage.height > aspectRatioThreshold) {	//it's safer to check the newImage element dimensions as the switchover can take a while
																							oldImage.style.width = '100%';
																							jQuery('.bgFade').animate({ opacity: 0.0 }, 4000).animate({ opacity: 1.0 }, 1500);
																						}
																						else {
																							oldImage.style.width = bgImageWidthNarrow;
																							jQuery('.bgFade').animate({ opacity: 1.0 }, 1500);
																						}
																						break;			

																					default:
																						jQuery('.bgFade').animate({ opacity: 1.0 }, 1500);
																						break;			
																				}

																			}).animate({ opacity: 0.0 }, 100, function(){ jQuery('#'+oldImage.id).animate({ opacity: 1.0 }, 1500);}); //oldImage is a different element after the switch
		}


		//update the background image info fields (for page editors)

		//switch in the new image title
		jQuery('#bgImageTitle').animate({ opacity: 0.0 }, 400, function(){jQuery('#bgImageTitle').text(newImage.title);}).animate({ opacity: 0.70 }, 600);
		
		var newImageId = newImage.id.replace(/bgImage-/, '');
		Post.Send('imageId='+newImageId, base_url+'dataserver/bgImageInfo');
	}


	function hover(element) {
		id = element.id;
		
		if (!jQuery('#'+element.id).hasClass("selected")) {
			jQuery('#'+id).addClass("hover");
			element.style.cursor = 'pointer';
		} else {
			element.style.cursor = 'default';		
		}
	}

	function unhover(element) {
		id = element.id;
		jQuery('#'+id).removeClass("hover");
	}



	function removeImage(redirectUrl) {
		//get id of current background image
		var imageMenu = document.getElementById('bgImageMenu');
		var thumbnail = imageMenu.getElementsByTagName("img");
		for (var i = 0; i < thumbnail.length; i++) {
			if (thumbnail[i].className.indexOf('selected') != -1) {
				//trigger an ajax delete request
				var imageId = thumbnail[i].id;
				imageId = imageId.replace(/bgImage-/, '');

				if (confirm('Are you sure you want to remove the selected background? The image file won\'t be deleted.')) {
					//delete row from database (id is in the form 'table-rowId', and pageId is used in the user authorization check)
					Post.Send('id=images-'+imageId+'&pageId='+pageId+'&redirectUrl='+redirectUrl, base_url+'dataserver/ajaxDeleteRow');
				}
			}		
		}
	}
	
	
	
	
	//converts the specified thumbnail to it's original image counterpart (the system often creates thumbnails of original images) 
	function replaceThumbnail(filename) {
		filename = filename.replace('_thumb', '');
		return filename.replace('_mime.jpg', '');
	}
	
	
	//this function, while it works, also restricts element draggable area when inside a jquery-ui dialog box  
	//bind an thumbnail drop event to the selected elements so that they are replaced by their full-quality counterparts on drag/dropping into the ckeditor  
	//requires jquery-ui draggable module
	function bindImageDrop(selector) {
		jQuery(selector).draggable({
   			stop: function(event, ui) { 
				alert('dragstop'); 
			}, 
			containment: 'window',
			zIndex: 2700,
			insideParent: false
		});
	}	
	
