/**
 * @author l250914
 */

if (!esg) var esg = {};
if (!esg.viewUtil)
	esg.viewUtil = {};

esg.viewUtil.modalBox = {
	/* 
	 * This code was adapted from a "Lightbox" article - http://particletree.com/features/lightbox-gone-wild/
	 */

	/**
	 * Show a <code>div</code> in a modal dialog. Requires that the page contains
	 * an (empty) <code>div</code> of class <code>modal_overlay</code>. 
	 * The modal_overlay should follow other markup, so that it renders after
	 * and covers other elements, preventing clicks outside the dialog.
	 * 
	 * @param {String} modalDiv the unique id of the dialog <code>div</code>
	 */
    modalOverlay : null,
    modalStack : [],
    modalBoxStartZindex : 5500,
    modalStackIncrement : 500,
    modalStackOverlayIncrement: 300,
    topModalInStack : null,
    modalStackPriorityModals : ["serviceError","timeOutError","customError","deleteGuard","progressThrobber"],
    modalsToExcludeFromDisplayAndHide : ["PhotoEditorDiv"],
    createNewModalBox : function(modalDiv) {
        modalDiv.getZInt = function(){return (this.getStyle('z-index').toInt())};
        return modalDiv;
    },
    show: function(modalDiv, parms){
		
		var skipOverlay = false, skipPositioning = false;
		
		if (parms && parms.skipOverlay)
			skipOverlay = parms.skipOverlay;
		
		if (parms && parms.skipPositioning)
			skipPositioning = parms.skipPositioning;	
		
        var modalOk = ($(modalDiv))?$(this.createNewModalBox($(modalDiv))):null;
        if (!modalOk) {
            console.error(modalDiv+' does not exist');
            return;
        } else 
            modalDiv = modalOk;
        
        var hasPriorityModal = false;
        if (this.modalStack.length) {
            this.topModalInStack = this.modalStack[this.modalStack.length-1];
            if (this.modalStackPriorityModals.contains(this.topModalInStack.id))
                hasPriorityModal = true;
        }
        if (hasPriorityModal) {
            var top = this.modalStack.pop();
            modalDiv.setStyle('display', 'block');
			modalDiv.setStyle('z-index', top.getZInt());
            this.modalStack.push(modalDiv);
            this.modalStack.push(top);
        }
        else {
            this.modalStack.push(modalDiv);
        }
        this.topModalInStack = this.modalStack[this.modalStack.length-1];

		var root = document.body;
		if (Browser.Engine.trident4 || Browser.Engine.trident5 && $('principal')) //for both IE6 and IE7
			root = $('principal');

        if (!this.modalOverlay) {
   			if ($('modal_overlay')) 
				this.modalOverlay = $('modal_overlay');
			else {
				this.modalOverlay = new Element('div', {
					'id': 'modal_overlay'
				});
				root.appendChild(this.modalOverlay);
			}
		}
		
        var zPos = (this.modalStack.length > 1)?this.modalStack[this.modalStack.length-2].getZInt() + this.modalStackIncrement:this.modalBoxStartZindex;         
        this.topModalInStack.setStyle('z-index',zPos);
        if (Browser.Engine.trident4) {
            // IE6 - must handle items that IE6 CSS can't support
            this.prepareIE('100%', 'hidden');
            this.hideSelects('hidden');
            if($('closeBtn'))
			{
                // PrintConfig close button for Custom Configurator.  Don't know why this is here. -DB 1/5/10
				$('closeBtn').setStyle('z-index', (this.createNewModalBox($('closeBtn').getParent())).getZInt() + 20);
			}
			(function(){this.modalOverlay.setStyle('height', document.getScrollSize().y);}).bind(this).delay(10); 
        }        
        if (!skipOverlay) {
            this.modalOverlay.setStyle('z-index', this.topModalInStack.getZInt() - this.modalStackOverlayIncrement);
            if (!this.modalsToExcludeFromDisplayAndHide.contains(this.modalOverlay.id))
                this.modalOverlay.setStyle('display', 'block');
        }    
        if (!this.modalsToExcludeFromDisplayAndHide.contains(this.modalOverlay.id))
        	this.topModalInStack.setStyle('display','block');

		if (!skipPositioning)		
			this.centerElement(modalDiv);
    },

	centerElement: function(elem) {
		elem = $(elem);
		elem.setStyles({
			'position': 'absolute',
            'top': Math.max(0, document.getScroll().y + parseInt((window.getSize().y - elem.getSize().y) / 2)),
            'left': '50%',
			'margin-left': -(parseInt(elem.getSize().x / 2))
        });
	},
    
	/**
	 * Hide a currently displayed dialog.
	 * 
	 * @param {String} modalDiv the unique id of the dialog <code>div</code>
	 */
    hide: function(modalDiv, resetOverlay){
        var modalOk = ($(modalDiv))?$(this.createNewModalBox($(modalDiv))):null;
        if (!modalOk) {
            console.error(modalDiv+' does not exist');
            return;
        } else 
            modalDiv = modalOk; 
			
		if (!resetOverlay) {
			resetOverlay = false;
		}
       
        if (!$(this.modalOverlay)) this.modalOverlay = $("modal_overlay");
        
        if (this.modalStack.length > 0) {
            $A(this.modalStack).each(function(item, index, array){
                if(item == modalDiv){
                    this.modalStack.splice(index,1);
                    this.topModalInStack = modalDiv;
                    return;
                }
            },this);
			
        }
        if (Browser.Engine.trident4) {
            // IE6 - must handle items that IE6 CSS can't support
            this.prepareIE("auto", "auto");
        }
        
		if ($(modalDiv)) {
            if (!this.modalsToExcludeFromDisplayAndHide.contains($(modalDiv).id || modalDiv))
                $(modalDiv).setStyle('display','none');
        }
		
		if (resetOverlay) {
			if ($(this.modalOverlay)) {
				$(this.modalOverlay).setStyle('display', 'none');
			}
		}
        
        if (this.modalStack.length > 0) {
			if ($(this.modalOverlay)) {
				this.modalOverlay.setStyle('z-index', this.modalStack[this.modalStack.length - 1].getZInt() - this.modalStackOverlayIncrement);
			}
        }
        else {
			if ($(this.modalOverlay)) {
				this.modalOverlay.setStyle('display', 'none');
			}
            this.hideSelects("visible");
        }    
		
    },

    prepareIE: function(height, overflow){
        bod = document.getElementsByTagName('body')[0];
        bod.style.height = height;
        bod.style.overflow = overflow;
    },
    getScroll: function(){
        var yScroll;
        
        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
        }
        else 
            if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
                yScroll = document.documentElement.scrollTop;
            }
            else 
                if (document.body) {// all other Explorers
                    yScroll = document.body.scrollTop;
                }
        this.yPos = yScroll;
    },
    
    
    setScroll: function(x, y){
        //window.scrollTo(x, y);
    },
    
    hideSelects: function(visibility){
		// This function is used to hide select elements in IE6 that do not respect
		// the ZOrder and therefore will "bleed through" a modal dialog.  This function
		// hides the select elements while the modal dialog is displayed.
		var modalBox = esg.viewUtil.modalBox;
		var topModal;
		
		if (modalBox.modalStack.length) {
			topModal = modalBox.modalStack[modalBox.modalStack.length - 1];
		}
		
		// to avoid CSS overrides when visible:
		if (visibility == 'visible')
			visibility = '';
		
		var selects = $$('select');
		selects.each(function(item, index) {
			// Check to see if this select element is inside the modal DIV
			// If so, we do not wish to hide it.
			if (!topModal || !(item.getParent('#'+topModal.id) === topModal))
	            item.style.visibility = visibility;
		});
    },
	
	updateOverlayHeight : function() {
		if (Browser.Engine.trident4)
			$('modal_overlay').style.height = esg.viewUtil.getPageSize()[1];
	}
};

esg.viewUtil.modalThrobber = esg.viewUtil.throbber = {
    moOverlayed:false,
	show: function(elevateModelOverlay){
        moOverlayed = (elevateModelOverlay && elevateModelOverlay == true);
		if (!$("progressThrobber")) {
			var dlg = new Element('div', {
				'class': "dialogbox",
				'id': "progressThrobber"
			});
			dlg.innerHTML = '<div class="dialogtopleft"><div class="dialogtopright clearfix"><div class="throbberContent"><img src="' + esg.viewUtil.staticAssetPath + '/Kodak_Gallery_Media/ECBO/images/icons/throbber.gif" alt="In Progress"/><br/><h3>Loading</h3>Please wait...</div></div></div><div class="dialogbotright"><div class="dialogbotleft"></div></div>';
			
			if ($('principal')) {
				$('principal').appendChild(dlg);
			}
			else {
				$(document.body).appendChild(dlg);
			}
		}
        esg.viewUtil.modalBox.show($("progressThrobber"),{
			skipOverlay: moOverlayed
		});

	},
	hide: function(resetOverlay){
		if (!resetOverlay) {
			resetOverlay = false;
		}
		if ($('progressThrobber')) {
			esg.viewUtil.modalBox.hide($('progressThrobber'));            
		}
		// catch a special case with anon slideshows munging the dom and getting the 
		// modalstack out of whack, look for orphan 'modal_overlay' element and hide.
		if (resetOverlay) {
			if ($('modal_overlay')) {
				$('modal_overlay').hide();
			}
		}
		
	},
	
	isVisibile : function() {
		return ($('progressThrobber') && $('progressThrobber').style.display == 'block');
	}
};

esg.viewUtil.serviceError = {
    show: function(){
		if (!$("serviceError")) {
			var dlg = new Element('div', {
				'class' : "dialogbox",
				'id' : "serviceError"
			});
			dlg.innerHTML = '<div class="dialogtopleft"><div class="dialogtopright clearfix"><div class="errorContent"><h3></h3><p><b> We were unable to process your request. <br/> Please try again.</b></p> <a id="closeServiceError" href="#" class="linkbutton"><span>OK</span></a></div></div></div><div class="dialogbotright"><div class="dialogbotleft"></div></div>';
			if (Browser.Engine.trident4) {
            	dlg.setStyle('top', $(document.body).getScroll().y + $(document.body).getSize().y/2 - dlg.getSize().y);
        	}
			$('principal').appendChild(dlg);
	        $("closeServiceError").addEvent('click', esg.viewUtil.serviceError.hide);
		}
        esg.viewUtil.modalBox.show("serviceError");
    },
    hide: function(event){
		if (event) event.stop();
        esg.viewUtil.modalBox.hide("serviceError");
    }
};

esg.viewUtil.timeoutError = {
    show: function(){
		if (!$("timeoutError")) {
			var dlg = new Element('div', {
				'class' : "dialogbox",
				'id' : "timeoutError"
			});
                    
			dlg.innerHTML = '<div class="dialogtopleft"><div class="dialogtopright clearfix"><div class="errorContent"><h3>Session Time-Out</h3><p>Your session has expired.<br/>Please start a new session.</p><a id="closeTimeoutError" href="#" class="linkbutton"><span>OK</span></a></div></div></div><div class="dialogbotright"><div class="dialogbotleft"></div></div>';
			if (Browser.Engine.trident4) {
            	dlg.setStyle('top', $(document.body).getScroll().y + $(document.body).getSize().y/2 - dlg.getSize().y);
        	}
			$('principal').appendChild(dlg);
	        $("closeTimeoutError").addEvent('click', esg.viewUtil.timeoutError.hide);
		}
        esg.viewUtil.modalBox.show("timeoutError");
    },
    hide: function(event){
		if (event) event.stop();
        esg.viewUtil.modalBox.hide("timeoutError");
        document.location = "/";
    }
};

esg.viewUtil.customError = {
    show: function(params){
		var header = params.title ? params.title : 'Error';
		var hideHeader = (params.hideHeader) ? params.hideHeader : false
		var message = params.message;
		var dlg = $("customError");
		if (!dlg) {
			dlg = new Element('div', {
				'class' : "dialogbox",
				'id' : "customError"
			});
		} else {
			esg.viewUtil.modalBox.hide("customError");
            $("closeCustomError").removeEvents('click');
		}
			
		dlg.innerHTML = '<div class="dialogtopleft"><div class="dialogtopright clearfix"><div class="errorContent">' +  ((!hideHeader) ? ('<h3>' + header + '</h3>') : '') + '<p>'  + message + '</p><a id="closeCustomError" href="#" class="linkbutton"><span>OK</span></a></div></div></div><div class="dialogbotright"><div class="dialogbotleft"></div></div>';
		if (Browser.Engine.trident4) {
        	//dlg.setStyle('top', $(document.body).getScroll().y + $(document.body).getSize().y/2 - dlg.getSize().y);
    	}
		$('principal').appendChild(dlg);
        $("closeCustomError").addEvent('click', esg.viewUtil.customError.hide);
	
		if (hideHeader && !$('customError').hasClass('hideHeader'))
				$('customError').addClass('hideHeader');
			else if (!hideHeader && $('customError').hasClass('hideHeader'))
				$('customError').removeClass('hideHeader');
		
        esg.viewUtil.modalBox.show("customError");
    },
    hide: function(event){
		if (event) event.stop();
        esg.viewUtil.modalBox.hide("customError");
    }
};

esg.viewUtil.deleteGuard = {
	show: function(param, param2) {
		if (!param2)
			param2 = 'You will not be able to undo this action.';
		if (param == 'photo')
			param2 = 'This photo will be permanently deleted from the album and any Slideshow in which it has been placed.';	

		if (!$("deleteGuard")) {
			var dlg = new Element('div', {
				id: 'deleteGuard',
				'class': 'dialogbox'
			});		
			dlg.innerHTML = '<div class="dialogtopleft"><div class="dialogtopright clearfix"><div class="throbberContent"><h4></h4><p>' + param2 + '</p><div class="options"><a class="linkbutton secondarybutton" id="btnConfirmDelete" href="#"><span>Delete</span></a><a class="linkbutton tertiarybutton" id="btnCancelDelete" href="#"><span>Cancel</span></a></div></div></div></div><div class="dialogbotright"><div class="dialogbotleft"></div></div>';
			if (Browser.Engine.trident4) {
            	dlg.setStyle('top', $(document.body).getScroll().y + $(document.body).getSize().y/2 - dlg.getSize().y);
        	}
			if ($('principal')) {
				$('principal').appendChild(dlg);
			}
			else {
				$(document.body).appendChild(dlg);
			}
	        //$("deleteGuard").addEvent('click', esg.viewUtil.deleteGuard.hide);
		}
        $$("#deleteGuard h4")[0].innerHTML='Are you sure you want to delete this ' + param + '?';
		$$('#deleteGuard .throbberContent p')[0].innerHTML=param2;
		esg.viewUtil.modalBox.show("deleteGuard");
		$$('#deleteGuard a').removeEvents('click');
	},
	hide: function(event) {
		if (event) event.stop();
        esg.viewUtil.modalBox.hide("deleteGuard");
	}
};

/*
 * Custom exitGuard, used when specific button or link is assigned with this event.
 * This is different from the browser default window.onbeforeunload() event. When that event
 * is fired, only a standard window prompt will be displayed. 
 */
esg.viewUtil.exitGuard = {
	show: function(title, message) {
		if (!title)
			title = 'Save your changes?';
		if (!message)
			message = 'Do you want to save the changes you have made?';
		
		if (!$("exitGuard")) {
			var dlg = new Element('div', {
				id: 'exitGuard',
				'class': 'exitGuard dialogbox'
			});		
			dlg.innerHTML = '<div class="dialogtopleft"><div class="dialogtopright clearfix"><div class="dialogContent"><h4>' + title + '</h4><p>' + message + '</p><div class="options"><span class="btngroupleft"><a class="linkbutton tertiarybutton" id="btnCancelChange" href="#"><span>Cancel</span></a></span><span class="btngroupright"><a class="linkbutton tertiarybutton" id="btnDontSaveChange" href="#"><span>Don&#39;t Save</span></a><a class="linkbutton" id="btnSaveChange" href="#"><span>Save</span></a></span></div></div></div></div><div class="dialogbotright"><div class="dialogbotleft"></div></div>';
			if (Browser.Engine.trident4) {
            	dlg.setStyle('top', $(document.body).getScroll().y + $(document.body).getSize().y/2 - dlg.getSize().y);
        	}
			if ($('principal')) {
				$('principal').appendChild(dlg);
			}
			else {
				$(document.body).appendChild(dlg);
			}
	        //$("deleteGuard").addEvent('click', esg.viewUtil.deleteGuard.hide);
		}
        $$("#exitGuard h4")[0].innerHTML = title;
		$$('#exitGuard .dialogContent p')[0].innerHTML = message;
		esg.viewUtil.modalBox.show("exitGuard");
		$$('#exitGuard a').removeEvents('click');
	},
	hide: function(event) {
		if (event) event.stop();
        esg.viewUtil.modalBox.hide("exitGuard");
	}
};

esg.viewUtil.warningDialog = {
	show: function(params) {
		var title = params.title ? params.title : 'Save your changes?';
//		var hideHeader = (params.hideHeader) ? params.hideHeader : false;
		var message = params.message ? params.message : 'Do you want to save the changes you have made?';
		
		if (!$("warningDialog")) {
			var dlg = new Element('div', {
				id: 'warningDialog',
				'class': 'warningDialog dialogbox'
			});		
			dlg.innerHTML = '<div class="dialogtopleft"><div class="dialogtopright clearfix"><div class="ancillary"><a id="closeWarningDialog" class="dialogclose" href="#" title="close">close</a></div><div class="dialogContent"><h4>' + title + '</h4><p>' + message + '</p><div class="options"><span class="btngroupleft"></span><span class="btngroupright"><a class="linkbutton tertiarybutton" id="btnCancelChange" href="#"><span>Cancel</span></a></span></div></div></div></div><div class="dialogbotright"><div class="dialogbotleft"></div></div>';
			if (Browser.Engine.trident4) {
            	dlg.setStyle('top', $(document.body).getScroll().y + $(document.body).getSize().y/2 - dlg.getSize().y);
        	}
			if ($('principal')) {
				$('principal').appendChild(dlg);
			}
			else {
				$(document.body).appendChild(dlg);
			}	    	
			$("closeWarningDialog").addEvent('click', esg.viewUtil.warningDialog.hide);
		}
		esg.viewUtil.modalBox.show("warningDialog");
        $$("#warningDialog h4")[0].innerHTML = title;
		$$('#warningDialog .dialogContent p')[0].innerHTML = message;
	},
	hide: function(event) {
		if (event) event.stop();
        esg.viewUtil.modalBox.hide("warningDialog");
	}
};


/**
 * Fixes footer for IE6 & IE7, which doesn't correctly update positions of
 * absolutely-positioned items when they are preceded by dynamic content.
 * 
 * This is obsolete as of Sep.09 because of the new footer sitemap.
 */
esg.viewUtil.fixFooter = function(){
	/*
	// only do this for IE; 'trident' specifies all verisons (6, 7, etc)
	if (Browser.Engine.trident) {
		// only do this if the footer exists
		if ($chk($('pagefooter'))) {
			// temporarily modify the CSS class
			$('pagefooter').addClass('transitional');
			
			// ... then change it back when the browser is idle
			setTimeout(function(){
				$('pagefooter').removeClass('transitional');
				console.log('fixed footer');
			}, 10);
		}
	}
	*/
};


/** Subtab bar for gallery pages **/
esg.viewUtil.getTabbedNavBarContents = function(current) {
	if (!current) current = 'photos';
	
	var upload = '<a id="btnUpload" class="linkbutton secondarybutton"><span id="photoPickerButtonUpload">Upload Photos</span></a>';
	
	var ancillary = new Element('div', {
		'class' : 'ancillary',
		'html' : (current == 'photos') ? upload : ''
	});
	
	var subtabs = new Element('ul', {
		 'class' : 'subtabs'
	});
	
	var anon = esg.ident.model.isAnon;
	
	var photostab = new Element('li', {
		'class' : 'photostab ' + ((current == 'photos' || (current == 'rearrange')) || (current == 'editcaptions') || (current == 'deletephotos')  || (current == 'bulkEdit') ? 'current' : ''),
		'html' : '<a href="albums.jsp"><span id="photoPickerPhotos">Photos</span></a>'
	});

	var contactstab = new Element('li', {
		'class' : 'contactstab ' + ((current == 'contacts') ? 'current' : '') + ((anon) ? 'disabled' : '')
	});
	
	var contactstaba = new Element('a', {
		'id' : 'contactsTabLink',		
		'href' : (anon) ? 'javascript:void(0);' : 'contacts.jsp',
		'html' : '<span id="photoPickerContacts">Contacts</span>'
		}
	);
	
	var commentstab = new Element('li', {
		'class' : 'commentstab ' + ((current == 'comments') ? 'current' : '') + ((anon) ? 'disabled' : '')
	});	
	
	var commentstaba = new Element('a', {
		'id' : 'commentsTabLink',		
		'href' : (anon) ? 'javascript:void(0);' : 'comments.jsp',
		'html' : '<span id="photoPickerComments">Comments</span>'
		}
	);	
	
	var sharehistorytab = new Element('li', {
		'class' : 'sharehistorytab ' + ((current == 'sharedHistory') ? 'current' : '') + ((anon) ? 'disabled' : '')
	});	
	
	var sharehistorytaba = new Element('a', {
		'id' : 'shareHistoryTabLink',
		'href' : (anon) ? 'javascript:void(0);' : 'sharedHistory.jsp',
		'html' : '<span id="photoPickerShareHistory">Share History</span>'
		}
	);	
	
	var projectstab = new Element('li', {
		'class' : 'projectstab '
	});	
	
	var projectstaba = new Element('a', {
		'id' : 'projectsTabLink',
		'href' : '/gallery/my-photo-projects.jsp',
		'html' : '<span>My Projects</span>'
		}
	);	
	
	if (anon) {
		var addTabLinks = function(){
		
			if (!$('shareHistoryTabLink')) {
				addTabLinks.delay(500);
				return;
			}
		
			var anonAlert = function(e){
				esg.share.controller.execute('showError', { 'message' : 'You must be logged in to access this tab.' });			
				return false;
			};
			
			$('contactsTabLink').addEvent('click', anonAlert);
			$('commentsTabLink').addEvent('click', anonAlert);
			$('shareHistoryTabLink').addEvent('click', anonAlert);
		}
		
		window.addEvent('domready', addTabLinks);
	}
	
	contactstab.appendChild(contactstaba);
	commentstab.appendChild(commentstaba);	
	sharehistorytab.appendChild(sharehistorytaba);	
	//projectstab.appendChild(projectstaba);
	
	subtabs.appendChild(photostab);
	subtabs.appendChild(contactstab);
	subtabs.appendChild(commentstab);
	subtabs.appendChild(sharehistorytab);
	//subtabs.appendChild(projectstab);
	
	var wrapper = new Element('div');
	wrapper.appendChild(subtabs);
	wrapper.appendChild(ancillary);
	
	return wrapper.getHTML();
};


/**
 * resize image for various display purposes.
 * set the default the width or height to render the image.
 */

esg.viewUtil.photoResize = function(photo, max){
		var orig_width = photo.width, orig_height = photo.height;
		if (!max) max = 250;
		if (photo.width > photo.height){
			if(photo.width > max) {photo.width = max; photo.height = orig_height*(max/orig_width);}
		}	else {
			if (photo.height > max) {
				photo.height = max;
				photo.width = orig_width * (max / orig_height);
			};
		}
		return photo;
};


// Core code from - quirksmode.org
// Edit for Firefox by pHaez
esg.viewUtil.getPageSize = function() {
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}


	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
};

/**
 * inPlaceTextEditor for edit comments, caption etc.
 * 
 */
esg.viewUtil.inPlaceEditor = {
	show: function(params) {
		var origText = params.edit;
		var editText = origText.replace(/<br\/*>/gi, "\r\n");
		var onCompleteEditEventStr = params.callback;	
		var editTxtFld = new Element('textarea', {
			'id': 'inPlaceEditor',
			'class': 'texteditfield',
			'html': Browser.Engine.trident ? '' : editText,
			'events': {
				select: function(event){
					event.stop();
					if(!Browser.Engine.trident) // IE hangs for select event
						esg.utility.txtCharCount('inPlaceEditor', 'editTextLengthCounter', 500);
					return false;	
				},
				focus: function(event){
					event.stop();
					esg.utility.txtCharCount('inPlaceEditor', 'editTextLengthCounter', 500);
					return false;
				},
				// blur always fires before the new target's click event; this makes it
				// impossible to cancel as the blur always does a save. Disabling for now.
//				blur: function(event){
//					event.stop();
//					var newText = $('inPlaceEditor').value;
//					if (editText == newText) {
//						esg.viewUtil.inPlaceEditor.cancel();
//					}
//					else {
//						esg.viewUtil.inPlaceEditor.save(onCompleteEditEventStr);
//					}					
//							
//					return false;			
//				},
				keyup: function(){
					esg.utility.txtCharCount('inPlaceEditor', 'editTextLengthCounter', 500);
				}
			}
		});				
		editTxtFld.store('origText', editText);	
		
		// In IE, we can't set the innerHTML of a textarea (which is why the 'html'
		// field is set to the empty string above). Instead we set the VALUE of the
		// textarea. Doing this sets the contents verbatim, so we have to unescape
		// the editText that was passed in. 
		if (Browser.Engine.trident) {
			editTxtFld.value = esg.utility.decodeHTML(editText);
		}
		var textLengthCounter = new Element('span', {
			'id': 'editTextLengthCounter',
			'class': 'textlength'
		})
		
		var saveEdit = new Element('a', {
			'id': 'saveInPlaceEdit',
			'class': 'saveInPlaceEdit',
			'html': 'Save',
			'events': {
				click: function(event){
					event.stop();
					var newText = $('inPlaceEditor').value;
					if (editText == newText) {
						esg.viewUtil.inPlaceEditor.cancel();
					}
					else {
						esg.viewUtil.inPlaceEditor.save(onCompleteEditEventStr);
					}					
					return false;	
				}
			}
		})
		
		var cancelEdit = new Element('a', {
			'id': 'cancelInPlaceEdit',
			'class': 'cancelInPlaceEdit',
			'html': 'Cancel',
			'events': {
				click: function(event){
					event.stop();
					esg.viewUtil.inPlaceEditor.cancel();
					return false;	
				}
			}
		})
		
		var inPleaceEditor = new Element('div', {
			'id': 'inPlaceEditContainer',
			'class': 'inplaceeditor' 
		}).adopt([textLengthCounter, cancelEdit, saveEdit, editTxtFld]);	

		return inPleaceEditor;
		},
		
	save: function(callbackstr){
		/* directly calling the callback function in different namespace. using eval instead of calling
		 * controller function.
		 */
		if (callbackstr){	
			console.info(callbackstr);		
			eval(callbackstr); 
			}
		},
	cancel:function(){
		var origComment = ($('inPlaceEditor')) ? $('inPlaceEditor').retrieve('origText') : '';
		var commentTextFld = $('inPlaceEditor').getParent('.commentText');
		commentTextFld.removeClass('editmode');
		commentTextFld.innerHTML = origComment.replace( /\r\n/g,"<br/>");
		esg.share.model.editing = false;
	}
}

esg.viewUtil.keepPhotoPullerMonitorInView = function(){
	
	// Keep the upload_dialog in view, by reacting to window scroll.
	//
	// 
	
	var ppmDlg = $('photoPullerMonitorInView_dialog');
	var modalOverlay = $('modal_overlay');
	
	
	if (ppmDlg) {
		var dlgWidth = ppmDlg.getSize().x;
		var dlgHeight = ppmDlg.getSize().y;
		
		var dlgMarginLeft = parseInt(ppmDlg.getStyle('margin-left'));
		var dlgMarginTop = parseInt(ppmDlg.getStyle('margin-top'));
		
		var docWidth = document.getSize().x;
		var docHeight = document.getSize().y;
		
		var docScrollX = document.getScroll().x;
		var docScrollY = document.getScroll().y;
		
		var newLeft = docScrollX + (docWidth - dlgWidth) / 2 - dlgMarginLeft;
		var newTop = docScrollY + (docHeight - dlgHeight) / 2 - dlgMarginTop;
	
		
		ppmDlg.setStyles({
			'left': '50%', //substituting with constant values as the css defined for dialog is position:fixed
			'top': '320px'
		});
		
		if (modalOverlay){
			modalOverlay.setStyles({
				'left':0,
				'top':(Browser.Engine.trident4)?docScrollY:0,
				'width':'100%',
				'height':(Browser.Engine.trident4)?docHeight:'100%'
			});
		}
	}
};

esg.viewUtil.addPhotoPullerMonitorWindowEvents = function(){
    if (Browser.Engine.trident4) {
        window.addEvents({
            'scroll': esg.viewUtil.keepPhotoPullerMonitorInView,
            'resize': esg.viewUtil.keepPhotoPullerMonitorInView
        });
    }
};   
		
esg.viewUtil.editorDialog = {
	show : function(params) {
		
		var id = params.id;
		var cssId = id + '_dialog'
		var cssEditId = id + '_edit';
		var title = params.title;
		var callback = params.callback;
		var defaultValue = params.text;
		
		var dlg = null;
		if (!$(cssId)) {
			dlg = new Element('div', {
				'class' : 'editDialog dialogbox',
				'id' : cssId
			});
			$('principal').appendChild(dlg);			
		} else {
			dlg = $(cssId);
			dlg.innerHTML = '';
		}
		
		var header = new Element('div', {
			'class' : 'header'
		});
		
		var headerText = new Element('h3', {
			'html' : title
		});
		
		var headerClose = new Element('a', {
			'id' : 'editGroupDialogClose',
			'href' : 'javascript:void(0);',
			'title' : 'Close',
			'class' : 'dialogclose',
			'events' : {
				'click' : function(e) {
					e.stop();
					esg.viewUtil.editorDialog.hide(id)					
				}
			}
		});
		
		header.appendChild(headerText);
		header.appendChild(headerClose);
		
		var topLeft = new Element('div', { 'class' : 'dialogtopleft' });
		var topRight = new Element('div', { 'class' : 'dialogtopright clearfix' });

		var dTopLeft = new Element('div', { 'class' : 'dpaneltopleft' });
		var dTopRight = new Element('div', { 'class' : 'dpaneltopright clearfix' });

		topRight.appendChild(header)
		
		var input = new Element('input', { 
			'type' : 'text',
			'name' : cssEditId,
			'id' : cssEditId,
			'value' : esg.utility.decodeHTML(defaultValue),
			'style' : 'color: #000;',
			'events' : {
				'select': function(event){
				if(!Browser.Engine.trident) // IE hangs for select event
					esg.utility.eraseField(this,event);
				},
				'focus': function(event){
					esg.utility.eraseField(this,event);
				},
				'blur': function(event){
					esg.utility.populateField(this,defaultValue,event);
				},
				'keydown': function(event){										
					esg.utility.eraseField(this,event);
				},
				'keyup': function(event){
					if (event.key == 'enter' && !$(id + '_yes').hasClass('disabledbutton')) {
						eval(callback);
						esg.viewUtil.editorDialog.hide(id);
						event.stop();
					}
					esg.viewUtil.editorDialog.changeText(id, defaultValue);
					esg.utility.populateField(this,defaultValue,event);					
				},
				'mousedown': function(event){					
					esg.utility.eraseField(this,event);
				},
				'mouseup': function(event){
					esg.utility.eraseField(this,event);
				},
				'contextmenu': function(event){					
					esg.utility.eraseField(this,event);
				}
			}
		
		});
		dTopRight.appendChild(input);
		
		
		dTopLeft.appendChild(dTopRight);	
		topRight.appendChild(dTopLeft);			
		
		var dBotLeft = new Element('div', { 'class' : 'dpanelbotleft' });
		var dBotRight = new Element('div', { 'class' : 'dpanelbotright' });
		dBotRight.appendChild(dBotLeft);

		topRight.appendChild(dBotRight);
		
		var footer = new Element('div', {
			'class' : 'changeGroupNameFooter clearfix'
		});
		
		var cancel = new Element('a', {
			'id' : id + '_no',
			'href' : 'javascript:void(0)',
			'class' : 'editDialogNo linkbutton tertiarybutton',
			'events' : {
				'click' : function(e) {
					e.stop();
					esg.viewUtil.editorDialog.hide(id);
				}
			},
			'html' : '<span>Cancel</span>'
		});
		
		var send = new Element('a', {
			'id' : id + '_yes',
			'href' : 'javascript:void(0)',
			'class' : ' editDialogYes linkbutton disabledbutton',		
			'events' : {
				'click' : function(e) {
					e.stop();	
					if (!this.hasClass('disabledbutton')) {
						eval(callback)
						esg.viewUtil.editorDialog.hide(id);
					}
				}
			},				
			'html' : '<span>Save</span>'
		});		
		
		footer.appendChild(send);		
		footer.appendChild(cancel);
		
		topRight.appendChild(footer)
		
		topLeft.appendChild(topRight);

		var botLeft = new Element('div', { 'class' : 'dialogbotleft' });
		var botRight = new Element('div', { 'class' : 'dialogbotright' });
		botRight.appendChild(botLeft);		
		
		dlg.appendChild(topLeft);
		dlg.appendChild(botRight);				
		
		if (Browser.Engine.trident4) {
        	dlg.setStyle('top',$(document.body).getScroll().y + $(document.body).getSize().y/2 - dlg.getSize().y);
    	}
			
        esg.viewUtil.modalBox.show(cssId);
		$(cssEditId).focus();
		$(cssEditId).select();
	},
	
	
	hide : function(id) {
		 esg.viewUtil.modalBox.hide(id + '_dialog')
	},
	
	changeText : function(id, defaultText) {
		var cssId = id + '_edit';
		var newName = $(cssId).value.trim();
		var button = $(id + '_yes');
			
			if ((!newName || newName == defaultText) && !button.hasClass('disabledbutton')) {
				button.addClass('disabledbutton');
				return;
			}
			
			if (button.hasClass('disabledbutton') && $(cssId).value != defaultText)
				button.removeClass('disabledbutton')
	}
};

esg.viewUtil.thumbResizer = function(img, size, retryCount, mode) {
	
	// no use resizing an image that doesn't exist
	if (img.src.length == 0)
		return;
	
	if (Browser.Engine.trident && (img.style.width || img.style.height)) {
		img.setStyle('width', 'auto');
		img.setStyle('height', 'auto');
	}
	
	if ((img.width == 0 || img.height == 0) && (!retryCount || retryCount < 5)) {
		if (!retryCount)
			retryCount = 0;
		(function() { esg.photoPicker.views.thumbResizer(img, size, ++retryCount, mode); }).delay(200);
		return;
	} else if (img.width == 0 || img.height == 0) {
		var newImg = Asset.image(img.src, {
			title : img.title
		});

		if (img.parentNode)
			img.parentNode.replaceChild(newImg, img);
		
		if (img.width == 0 || img.height == 0) {
			(function(){
				esg.photoPicker.views.thumbResizer(newImg, size, 0, mode);
			}).delay(250);
			return;
		}
	}
	
	var cmp = (mode != "album") ? img.width < img.height : img.width > img.height;
	
	if(cmp) {
		img.setStyle('height', size + "px"); 
		img.setStyle('width', 'auto');  
	}
	else {
        var origSize = {
            'height': img.height,
            'width': img.width
        };
            
		img.setStyle('width', size + "px");   
		img.setStyle('height', 'auto');
        var paddingVal = parseInt((size-(origSize.height*size/origSize.width))/2);
        img.setStyle('margin-top',paddingVal);
        img.setStyle('margin-bottom',paddingVal); 
	}
	// Set the image parent div back to display : block
	// after the images are resized and injected in side
	// their containers.
	
	if (img.getParent())
		img.getParent().setStyles({
	        'display': 'block'
	    });
	
	if (img.style.visibility == 'hidden') 
		img.setStyle('visibility','visible');
};   
		
