var PhotoManager = {
	linkName: 'lnkSetCover',
	leadPhoto: 'leadPhoto',
	leadPhotoLink: 'leadPhotoLink',
	mJournalId: 0,
	mOverLay: null,
	mModalWindow: null,
	imageData: null,
	imageCache: new Array(),	
    modalHtml: "<div id='ModalOverlay'></div><div id='ModalWindow' class='select-cover'></div>",
    windowHtml: '<p class="soft-close small"><a href="javascript:void(0);" onclick="PhotoManager.ClosePopup();" class="incognito">Close</a></p><h2>Select a New Cover Photo</h2><div id="thumbnails" class="photoGallery"></div>',
    ajaxHtml: "<div id='ajaxLoadDiv'><img src='/images2/ajaxWorking.gif' /></div>",
    photoHtmlTemplate: '<div class="thumbnail"><span><a href="javascript:void(0);" onclick="PhotoManager.setThumbnail(${photoId})"><img class="PhotoManagerPhoto" alt="${title}" src="${thumbnail}" /></a></span></div>',

    imgLoader: new Image(),
    imgPreloader: null,
    
    init: function() {
		Event.observe($(this.linkName),'click',this.showThumbnails.bind(this));
		this.mJournalId = currentJournalId;
		if(ImageData)
			this.imageData = ImageData;
    },
    
    showAjax: function() {
		this.mModalWindow.innerHTML = this.ajaxHtml;
    },
    
    setThumbnail: function(pId) {
		this.showAjax();
		JournalBO.setCoverPhoto(this.mJournalId,pId,function(){
					this.setThumbnail_Callback(pId);
				}.bind(this));
    },
    
    setThumbnail_Callback: function(pId) {
		var oNewLead = null;
		for(i = 0; i < this.imageData.length; i++){
			oImage = this.imageData[i];
			if(oImage.PhotoId == pId)
				oNewLead = oImage;
		}
		if(oNewLead) {
			oLead = $(this.leadPhoto);
			oLead.src = oNewLead.Thumbnail;
			oLead.alt = oNewLead.Title;
		
			oLink = $(this.leadPhotoLink);
			oLink.href=oNewLead.Href;
		
		}
		this.ClosePopup();
    },
    
    showThumbnails: function(url, imageGroup){
        try {
            
			var oBody = $$('body')[0];
			var oHtml = $$('html')[0];
            
            //In IE6, create an iFrame to cover the page
            if (typeof document.body.style.maxHeight === "undefined") //if IE 6
            {	
				oBody.setStyle({height: "100%",width: "100%"});
                oHtml.setStyle({height: "100%",width: "100%",overflow: "hidden" });
                
                if ($("ModalGalleryHideSelect") === null) //iframe to hide select elements in ie6 
                    oBody.insert("<iframe id='ModalGalleryHideSelect'></iframe>");
            }
            
            //Create Modal window
            oBody.insert(this.modalHtml);
           
            this.mOverLay = $('ModalOverlay');
            this.mModalWindow = $('ModalWindow');
            
            Event.observe(this.mOverLay,'click',this.ClosePopup.bind(this));
            if (this.detectMacXFF()) {
                this.mOverLay.addClassName("ModalOverlayMacFFBGHack");//use png overlay so hide flash
            }
            else {
                this.mOverLay.addClassName("ModalOverlayBG");//use background and opacity
            }
            	
            //Set the initial window HTML
            this.mModalWindow.update(this.windowHtml);       
           
            //Build thumbnail html
            if(this.imageData) {
				var oImageContents = '';
				for(i=0; i<this.imageData.length; i++) {
				    oImage = this.imageData[i];
					oImageContents += this.photoHtmlTemplate.replace('${thumbnail}',oImage.Thumbnail).replace('${title}',oImage.Title).replace('${photoId}',oImage.PhotoId);					
				}
				$('thumbnails').update(oImageContents);
			
			}
		
			//Fade in the overlay
            jQuery('#ModalOverlay').fadeTo("fast", 0.65, function(){
                jQuery("#ModalWindow").show();
                
                //IE6 Hack
                $$("img.PhotoManagerPhoto").each(function(e){ e.src = e.src; });  
                
            });
        
        } 
        catch (e) {
            alert(e);
        }
    },
    
    downloadPhotos: function(pStartIndex) {
		if(this.imageData != null && this.imageData.length > pStartIndex) {
			oImage = new Image();
			oImage.onload = this.downloadPhotos(parseInt(pStartIndex)+1);
			oImage.src=this.imageData[pStartIndex].Href;
		}
    },
    
    detectMacXFF: function(){
        var userAgent = navigator.userAgent.toLowerCase();
        if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) 
            return true;
    },
	
	
    
    ClosePopup: function(){
        jQuery('#ModalOverlay').fadeTo("fast", 0.0);
         jQuery("#ModalWindow").fadeOut("fast", function(){
            jQuery('#ModalWindow,#ModalOverlay,#ModalGalleryHideSelect').remove();
        });
        if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
            jQuery("body", "html").css({
                height: "auto",
                width: "auto"
            });
            jQuery("html").css("overflow", "");
        }
        return false;
    }
}
var Accordion = {

    openTextElement: null,
    clickedAnchor: null,
    scrollTo: false,
    
    init: function(){
    
        //If there is more than one review, Create Accordion
        //if ($$(".accordionHeader").length > 1) {
            jQuery("#Accordion").accordion({
                navigation: false,
                active: ".activeAccordion",
                header: '.accordionHeader',
                duration: 400,
                alwaysOpen: false,
                autoHeight: true,
				clickTarget: '.accordionLink'
            }).change(Accordion.setElement);
            
            //If only one item is in accordion, activate it
            
            //Activate panel from querystring - This is necessary because accordion navigation doesnt work with the current markup
            oCurrent = Accordion.getCurrentReviewId();
            if (oCurrent) {
                Accordion.open(oCurrent);
            }
            //Add click event that keeps track of selected anchor
            jQuery(".accordionLink").bind("click", function(){
                Accordion.clickedAnchor = $(this);
            });
        //}
        
        // Allow confirmation messages to expand accordion
        if ($('ReviewLink')) {
            $('ReviewLink').observe('click', function(e){
                var oReviewID = new IgoUgoJS.Util.Request().getValue("ConfirmID");
                Accordion.openRowItem(oReviewID);
            })
        }
    },
    
    open: function(pReviewId){
        jQuery('#Accordion').activate('#h_' + pReviewId);
        new Effect.ScrollTo('a_' + pReviewId);
    },
    
    setElement: function(){
        if (Accordion.clickedAnchor) {
            if (Accordion.scrollTo || ((Accordion.clickedAnchor.cumulativeOffset()[1] - Accordion.clickedAnchor.cumulativeScrollOffset()[1]) < 0 && $$('#Accordion div.selected').length > 0)) {
                new Effect.ScrollTo(Accordion.clickedAnchor.id);
                Accordion.scrollTo = false;
            }
			var underscorePosition = Accordion.clickedAnchor.id.lastIndexOf('_');
			if (underscorePosition != -1) {
				document.location.hash = "ReviewID:" + encodeURIComponent(Accordion.clickedAnchor.id.substring(underscorePosition+1));
			}			
        }
		return false;
    },
    
    closePhoto: function(pReviewId, pGallery){
        pGallery.closeSoftPopup();
        Accordion.openRowItem(pReviewId);
    },
    
    openRowItem: function(pReviewId){
        Accordion.clickedAnchor = $('a_' + pReviewId.toString());
        Accordion.scrollTo = true;
        if (jQuery('#h_' + pReviewId + '.selected').length == 0) 
            jQuery('#Accordion').activate('#h_' + pReviewId);
    },
    
    enableSorting: function(){
        Sortable.create("Accordion", {
            onUpdate: JournalUI.updateDisplayOrder,
            onStart: Accordion.collapseAll,
            handle: 'dragDrop',
            constraint: 'vertical',
            scroll: window,
            format: /^(.*)$/,
            tag: 'div'
        });
        
        //Make all panels autocollapse on drag
        $$(".handle").each(function(e){
            Accordion.makeAutoCollapse(e)
        });
    },
	
    disableSorting: function(){
        Sortable.destroy("Accordion");
        $$(".handle").each(function(e){
            e.onmousedown = null;
            e.onmouseup = null
        });
    },
    
    makeAutoCollapse: function(pElement){
        pElement.onmousedown = this.collapseAll.bind(this);
        //pElement.onmouseup = this.uncollapseAll.bind(this);
    },
    
    collapseAll: function(pElement){
        this.openTextElement = $$("div.showHide").select(function(e){
            return e.style.display != 'none'
        });
        jQuery("#Accordion").activate(true);
        //jQuery(".showHide").slideUp(100);
        return false;
    },
    
    uncollapseAll: function(pElement){
        if (this.openTextElement != null) 
            jQuery(this.openTextElement).slideDown(300);
    },
    
    getNewUrl: function(pAnchor){
        oLoc = window.location.href;
        oLocInString = oLoc.lastIndexOf("#");
        if (oLocInString > -1) {
            oLoc = oLoc.substring(0, oLocInString);
        }
        
        oLocInString = pAnchor.href.lastIndexOf("#");
        return oLoc + pAnchor.href.substring(oLocInString);
    },
    
    getCurrentReviewId: function(){
		var oHash = document.location.hash;
		if (oHash.lastIndexOf('ReviewID:') > -1) {
			var oPosition = oHash.lastIndexOf('ReviewID:');
			if (oHash.length > oPosition + 9) {
				oReviewID = oHash.substring(oPosition+9);
				oLinkExists = ($$('#a_' + oReviewID).length > 0);
				if (oLinkExists) {
	                return oReviewID;
	            }
			}
		} else if (oHash.length > 0) {
			var oReviewID = oHash.substring(1);
			oLinkExists = ($$('#a_' + oReviewID).length > 0);
			if (oLinkExists) {
				return oReviewID;
	        }
		}
		return null;
    }
};

var JournalUI = {
    defaultSeparatorText: 'Enter Heading',
	inPlaceEditControls: [],
    
    blockUI: function(){
        $('Accordion').setOpacity(0.5);
    },
    
    unblockUI: function(){
        $('Accordion').setOpacity(1);
    },
    
    detachJournalItem: function(pNode){
        if (confirm('Are you sure you want to remove this item from this journal?')) {
			JournalUI.blockUI();
			var oRemovedNode = pNode.up('div[rel]');
			if (oRemovedNode.readAttribute('rel') == 'Separator') {
				// NOOP
			} else if (oRemovedNode.readAttribute('rel') == 'Review') {
				Accordion.collapseAll();
			}
			var oRequest = new IgoUgoJS.Util.Request(IgoUgoJSConfigExt.currentUrl);
			var oJournalID = oRequest.getValue('JournalID');
			JournalBO.detachJournalItem(oJournalID, oRemovedNode.readAttribute('rel'), oRemovedNode.id.replace('s','').replace('r',''), JournalUI._detachJournalItemCallback, oRemovedNode);
        }
		return false;
    },
	
	_detachJournalItemCallback: function(pCompletedRequest) {
		var oSender = $(pCompletedRequest.context.id);
		Effect.DropOut(oSender);
		JournalUI.unblockUI();
		if (pCompletedRequest.value.toUpperCase() == 'REVIEW') {
			if (document.location.hash.length > 0) {
			document.location.hash = ' ';
			}
			if (document.location.search.length > 0) {
				document.location.search = '';
				return;
			}
			document.location.reload();
		}
	},
    
    addSeparator: function(){
        JournalUI.blockUI();
        var oRequest = new IgoUgoJS.Util.Request(IgoUgoJSConfigExt.currentUrl);
        var oJournalID = oRequest.getValue('JournalID');
        JournalBO.insertSeparator(oJournalID, JournalUI.defaultSeparatorText, JournalUI._addSeparatorCallback);
        return false;
    },
    
    _updateSeparatorTextCallback: function(pCompletedRequest){
		this.element.innerHTML = pCompletedRequest.value;
		this.leaveEditMode();
		JournalUI.unblockUI();
		//this.element.highlight();
    },
    
    applyBehaviors: function(){
        Accordion.enableSorting();
		JournalUI.enableInPlaceEditing();
    },
	
	enableInPlaceEditing: function() {
		if (JournalUI.inPlaceEditControls.length > 0) {
			JournalUI.inPlaceEditControls.each(function(pControl) {
				pControl.destroy();
			});
			JournalUI.inPlaceEditControls = [];
		}
		
		$$('div[rel=Separator]').each(function(pSeparator){
            var oIPE = new Ajax.InPlaceEditor(pSeparator.down(), '/', {
				cancelControl:'link',
                okText: 'Update',
				cancelText:'Cancel',
				clickToEditText: '',
				formClassName: 'editHeading',
				size: '30',
				onComplete: null,
				onEnterHover: null,
				onLeaveHover: null,
				onLeaveEditMode: function() { return false },
                externalControl: pSeparator.down('li', 0),
                externalControlOnly: true
            })
			JournalUI.inPlaceEditControls.push(oIPE);
        });
	},
    
    updateDisplayOrder: function(){
        JournalUI.blockUI();
        var oElements = $('Accordion').childElements();
        var oUpdatedDisplayOrder = [];
        oElements.each(function(pNode){
            if (pNode.readAttribute('rel') !== null) {
                var oNode = {
                    ObjectType: pNode.readAttribute('rel'),
                    ObjectID: pNode.id.replace('r','').replace('s','')
                };
                oUpdatedDisplayOrder.push(oNode);
            }
        });
		
		var oRequest = new IgoUgoJS.Util.Request(IgoUgoJSConfigExt.currentUrl);
        var oJournalID = oRequest.getValue('JournalID');
        JournalBO.updateJournalDisplayOrder(oJournalID, oUpdatedDisplayOrder.toJSON(), JournalUI.unblockUI);
    },
    
    _addSeparatorCallback: function(pCompletedRequest){
        var oSeparatorTemplate = new Template('<div class="separator dragDrop editElement hover_target handle" rel="Separator" id="s#{SeparatorID}" hover_container="EditControls_#{SeparatorID}"><h2 id="text_#{SeparatorID}">#{SeparatorText}</h2><ul class="hover_container" id="EditControls_#{SeparatorID}"><li><a class="ic i-write" href="javascript:void(0);" title="Edit">Edit</a></li><li><a class="ic i-remove" href="javascript:void(0);" title="Remove" onclick="javascript:JournalUI.detachJournalItem(this);">Remove</a></li></ul></div>');
        var oSeparatorVars = {
            SeparatorID: pCompletedRequest.value,
            SeparatorText: JournalUI.defaultSeparatorText
        };
        $('Accordion').insert({
            top: oSeparatorTemplate.evaluate(oSeparatorVars)
        });
		// If the new heading is outside the client viewport, scroll to focus on the new element
		if (JournalUI._calculateElementPosition("s" + oSeparatorVars.SeparatorID.toString())) {
			Effect.ScrollTo("s" + oSeparatorVars.SeparatorID.toString(), {offset: -100});
		}
        JournalUI.applyBehaviors();
        JournalUI.unblockUI();
		
		JournalUI.inPlaceEditControls.each(function(pControl) {
			if (pControl.element.id == 'text_' + oSeparatorVars.SeparatorID) {
				pControl.enterEditMode();
				$break;
			}
		})
		$("s" + oSeparatorVars.SeparatorID.toString()).shake(0.5);
    },
	
	// Returns true if the element is visible in the viewport, false otherwise
	_calculateElementPosition: function(pElementID){
		if ($(pElementID).cumulativeOffset().top - $(pElementID).cumulativeScrollOffset().top < 0) {
			return true;
		}
		return false;
	}
}

jQuery(Accordion.init);

// Extended default IPE to allow submitting to a function instead of a URL
Object.extend(Ajax.InPlaceEditor.prototype, {
	handleFormCancellation: function(e) {
		var oRemovedNode = this.element.up();
		var oSeparatorText = $F(this._controls.editor);
		
		if (oSeparatorText == JournalUI.defaultSeparatorText || oSeparatorText.strip().length == 0) {
			JournalUI.blockUI();
			var oRequest = new IgoUgoJS.Util.Request(IgoUgoJSConfigExt.currentUrl);
			var oJournalID = oRequest.getValue('JournalID');
			JournalBO.detachJournalItem(oJournalID, oRemovedNode.readAttribute('rel'), oRemovedNode.id.replace('s',''), JournalUI._detachJournalItemCallback, oRemovedNode);
		}
		
		this.wrapUp();
		if (e) Event.stop(e);
	},
    handleFormSubmission: function(e) {
		JournalUI.blockUI();
		var oSeparator = this.element.up();
		var oSeparatorText = $F(this._controls.editor);
		
		var oRequest = new IgoUgoJS.Util.Request(IgoUgoJSConfigExt.currentUrl);
        var oJournalID = oRequest.getValue('JournalID');
		if (oSeparatorText == JournalUI.defaultSeparatorText || oSeparatorText.strip().length == 0) {
			JournalUI.blockUI();
			JournalBO.detachJournalItem(oJournalID, oSeparator.readAttribute('rel'), oSeparator.id.replace('s',''), JournalUI._detachJournalItemCallback, oSeparator);
		} else {
			this.prepareSubmission();
			JournalBO.updateSeparatorText(oSeparator.id.replace('s',''), oJournalID, oSeparatorText, JournalUI._updateSeparatorTextCallback.bind(this));
		}
		
		if (e) Event.stop(e);
    },
	createControl: function(mode, handler, extraClasses) {
		var control = this.options[mode + 'Control'];
		var text = this.options[mode + 'Text'];
		if ('button' == control) {
			var btn = document.createElement('input');
			btn.type = 'submit';
			btn.value = text;
			btn.className = 'editor_' + mode + '_button';
			if ('cancel' == mode)
			btn.onclick = this._boundCancelHandler;
			this._form.appendChild(btn);
			this._controls[mode] = btn;
		} else if ('link' == control) {
			var link = document.createElement('a');
			link.href = 'javascript:void(0);';
			link.appendChild(document.createTextNode(text));
			link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
			link.className = 'editor_' + mode + '_link';
			if (extraClasses)
			link.className += ' ' + extraClasses;
			this._form.appendChild(link);
			this._controls[mode] = link;
		}
	}
});

function _showContentLinkingTool(pContentType, pElement) {
	if (!this.mContentToolInitialized) {
		this.mContentToolInitialized = true;
		var oCanvas = document.createElement('div');
		oCanvas.id='contentLinkCanvas'
		LightBox.appendChildToLight(oCanvas);
		var oTool = $('contentLinkFrame');
		oTool.parentNode.removeChild(oTool);
		LightBox.appendChildToLight(oTool);
	}
	var oRequest = new IgoUgoJS.Util.Request(IgoUgoJSConfigExt.currentUrl);
    var oJournalID = oRequest.getValue('JournalID');
	$('contentLinkFrame').src = '/share/addReview.aspx' + '?JournalID=' + oJournalID + "&ContentType=" + pContentType; 
	LightBox.showLightbox($('contentLinkFrame'), false, false);
	LightBox.disableOverlayClosing();
	return false;
}

function closeContentTool(pRequiresPageRefresh) {
	if (pRequiresPageRefresh) {
		if (document.location.hash.length > 0) {
			document.location.hash = ' ';
		}
		if (document.location.search.length > 0) {
			document.location.search = '';
			return;
		}
		document.location.reload();
	}
	LightBox.hideLightbox();
}

Event.observe(window,'load',PhotoManager.init.bind(PhotoManager));