/* ----------------------------------------------------------------------------  
 *  Album Selector widget
 *  (c) 2007 Third Light Ltd
 * ----------------------------------------------------------------------------
 */

// For the advanced search fields. 
if (!ALBUM_SELECTORS)
{
    var ALBUM_SELECTORS = new Array();
}

// AlbumSelectorLight
// Give it this HTML:
// <div id="strASContainer">
//    <a href="#" id="$strASSelect" class="ASSelect">Loading folders... please wait</a>
// </div>

var AlbumSelectorLight = Class.create({
    
	initialize: function(strASSelect, strASContainer, strASListHolder, strASFieldName, strASTaxonomyPath, strInitialLabel, strJSCallback, bNoWindowCallback) {
	    // Member variables
	    this.strASSelect        = strASSelect;	
		this.strASContainer     = strASContainer;
		this.strASListHolder    = strASListHolder;
		this.strASFieldName     = strASFieldName;
		this.strASTaxonomyPath  = strASTaxonomyPath;
		this.strInitialLabel    = strInitialLabel;
		this.strJSCallback      = strJSCallback;
		this.bNoWindowCallback  = bNoWindowCallback;
		this.nEffectDuration    = 0.2;
		this.taxonomy           = null;
        this.open               = false;
		// Store "this" as an attribute of the parent div, so that the album onclick
		// handler can find the right widget. See ASSetFormField.
		$(this.strASContainer).as = this;
		// Store in global array for advanced search.
        ALBUM_SELECTORS[this.strASContainer] = this;
		this.GetTaxonomy();
	},
	
	// Called when the taxonomy is loaded to attach an onclick-to-open handler.
    AttachOpenHandlers: function() {
        // First unattach Close handlers
        if (this.boundCloseFunction) {
          Event.stopObserving(document, "click", this.boundCloseFunction);
          Event.stopObserving(this.strASListHolder, "click", this.boundCloseFunction);
        }
        
        // Now attach open handlers
        this.boundShowFunction = this.ShowList.bindAsEventListener(this);
    	Event.observe (this.strASSelect, "click", this.boundShowFunction);
    },
    
    // Called when the drop-down is drawn so it can be closed from both a document and widget click.
    AttachCloseHandlers: function() {
        // First unattach Open handlers
        Event.stopObserving(this.strASSelect, "click", this.boundShowFunction);
        
        // Now attach close handlers
        this.boundCloseFunction = this.CloseList.bindAsEventListener(this);
        // Handler for the docment: click anywhere to close the list. 	
    	Event.observe (document, "click", this.boundCloseFunction);
    	// Handler for the DDLB. Maybe not necessary (document would catch it)
    	Event.observe (this.strASListHolder, "click", this.boundCloseFunction);
    }, 
    
    // Called from the constructor to load the taxonomy.   
    GetTaxonomy: function() {
    	this.LoadTaxonomy(function(){this.SetSelectLabel(this.strInitialLabel);}.bind(this));
    },

    LoadTaxonomy: function(onSuccess) {
    	var myself = this;
    	new Ajax.Request(this.strASTaxonomyPath, {
    		method: "get",
    		onSuccess: function(transport) {
    		    myself.SaveTaxonomy(transport);
    		    myself.AttachOpenHandlers();
    		    if(onSuccess)onSuccess();
    		},
    		onFailure: function(transport) {myself.GetTaxonomyFailed(transport)}
    	});
    },
    
    // Draws the drop down list box. This is the event handler for the open click (see AttachOpenHandlers).
    ShowList: function(e) {
        if (this.open) return;
        this.open = true;
        Event.stop(e);
        // Tweak for IE less than 7 to solve div over select issue.
        // This only *looks* like a comment! Do not delete.
    	/*@cc_on
            if (typeof(document.body.style.maxHeight) == "undefined") {
                var elASListOpacity = document.createElement("iframe");
                $(elASListOpacity).id = this.strASListHolder + "_opacity";
                elASListOpacity.src = "images/transparent.gif";
                elASListOpacity.height = 300;
                elASListOpacity.width = 300;
                elASListOpacity.style.position = "absolute";
                elASListOpacity.style.display = "none";
                elASListOpacity.zIndex = 0;
            	$(this.strASSelect).insert({after: elASListOpacity});
            }
        @*/
    	
        var elASListHolder = document.createElement("div");
    	$(elASListHolder).id  = this.strASListHolder; 
    	$(this.strASSelect).insert({after: elASListHolder});
        elASListHolder.className = "ASDropdown";
    	elASListHolder.setStyle({
			display: "none"
    	});
    	      
    	var myself = this;
    	var elASListOpacity = $(this.strASListHolder + "_opacity");
    	if (elASListOpacity) {
    	  // For iframe hack for IE use a parallel effect to wind
    	  // down the iframe at the same time as the ListHolder
    	  new Effect.Parallel([
        	new Effect.BlindDown(elASListOpacity, {
        	   sync: true
        	}),
        	new Effect.BlindDown(elASListHolder, {
        	   sync: true
        	})], {
            duration: this.nEffectDuration, 
            afterFinish: function() {
              myself.DrawTaxonomyIntoList(); 
              myself.AttachCloseHandlers()
            }
          });
    	} else {
    	  new Effect.BlindDown(elASListHolder, {
            duration: this.nEffectDuration, 
            afterFinish: function() {
              myself.DrawTaxonomyIntoList(); 
              myself.AttachCloseHandlers()
            }
          });
        }
    },
    
    // Stores the loaded taxonomy in a member variable.
    SaveTaxonomy: function(transport) {
    	this.taxonomy = transport.responseText;
    },
    
    // Message to display when AJAX request fails.
    GetTaxonomyFailed: function(transport) {
    	this.SetSelectLabel("Failed to load folders.");
    },
    
    // Removes the DDLB. This is the event handler for the click-to-close events (see AttachCloseHandlers).
    CloseList: function(e) {
        if (!this.open) return;
        this.open = false;
    	Event.stop(e);
        
		var elASListHolder = $(this.strASListHolder);
    	if (elASListHolder) {
    		elASListHolder.innerHTML = "";  
    		var myself = this;
            var elASListHolderOpacity   = $(this.strASListHolder + "_opacity");
            if (elASListHolderOpacity) {
              new Effect.Parallel([
                new Effect.BlindUp(elASListHolderOpacity, {sync: true}),
                new Effect.BlindUp(elASListHolder, {sync: true})
              ], {
                duration: this.nEffectDuration, afterFinish: function() {myself.TidyUp();}
              });
            } else {
              new Effect.BlindUp(elASListHolder, {duration: this.nEffectDuration, afterFinish: function() {myself.TidyUp();}});
            }
    	}
    },
    
    // Continues the CloseList function after the Sriptaculous effect finishes. See CloseList.
    TidyUp: function() {
        var elASListHolder          = $(this.strASListHolder);
    	if (elASListHolder) { 
    	    this.AttachOpenHandlers(); // this unattaches any close handlers
			
    	    // remove the list holder
			elASListHolder.remove();
			// The following is to remove the iframe hack required for IE 6
            var elASListHolderOpacity = $(this.strASListHolder + "_opacity");		
			if (elASListHolderOpacity) elASListHolderOpacity.remove();

			// Prompt screen redraw for Safari 3 glitch
			if (navigator.userAgent.indexOf("Safari") != -1) {
				window.resizeBy(-1,0);
				window.resizeBy(1,0); 	
			}
		}
	},
	
	// Called by ShowList when the Scriptaculous effect finishes.
    DrawTaxonomyIntoList: function() {
    	var elASListHolder = $(this.strASListHolder);
    	elASListHolder.innerHTML = this.taxonomy;
    	elASListHolder.setStyle({overflow: "auto"}); 
    },
    
    // Utility method to allow the widget to display various statuses.
    SetSelectLabel: function(strHTML) {
    	$(this.strASSelect).innerHTML = strHTML;    	
    }
});

// Wrapper for the HTML to call that sets up the widget.
function ASSetup(strASSelect, strASContainer, strASListHolder, strASFieldName, strASTaxonomyPath, strInitialLabel, strJSCallback, bNoWindowCallback) {
	var as = new AlbumSelectorLight(strASSelect, strASContainer, strASListHolder, strASFieldName, strASTaxonomyPath, strInitialLabel, strJSCallback, bNoWindowCallback);
}

// Event handler triggered by clicking a folder in the DDLB. This handler is attached
// in-line for rendering speed.
function ASSetFormField(elLI, nID, strName) {
	var arrAncestors = $(elLI).ancestors();
	var elAS = arrAncestors.find(ASHasAS);
	if (typeof(elAS.as) != "undefined") {
		elAS.as.SetSelectLabel(strName);
        var elInput = $(elAS.as.strASFieldName);
		elInput.value = nID;
        if(elInput.onchange) {
            elInput.onchange();
        }
		if(elAS.as.strJSCallback)elAS.as.strJSCallback(nID, strName);
		if (!elAS.as.bNoWindowCallback && window.AlbumSelectorLight_OnClick) window.AlbumSelectorLight_OnClick(nID, strName);
	}
}

function ASLaunchCreate(elLI, nType, bAllowTop) {
    var arrAncestors = $(elLI).ancestors();
	var elAS = arrAncestors.find(ASHasAS);
	if (typeof(elAS.as) != "undefined") {
        var objAS = elAS.as;
        if(!objAS.createForm) {
            objAS.createForm = new IMS.CreateAlbum(elAS, IMS.objAPI, {type:nType,createTop:bAllowTop,onSuccess: function(response) {
                $(objAS.strASFieldName).value=response.id;
                objAS.SetSelectLabel(response.name);
                if(objAS.strJSCallback) {
                    objAS.strJSCallback(response.id, response.name);
                }
                if (!objAS.bNoWindowCallback && window.AlbumSelectorLight_OnClick) {
                    window.AlbumSelectorLight_OnClick(response.id, response.name);
                }
                objAS.LoadTaxonomy();
            }});
        }
        objAS.createForm.show();
	}
}

// Looks for a parent element that has an AlbumSelectorLight widget attached. This
// allows ASSetFormField to retrieve its parent AS.
function ASHasAS(element) {
	if (typeof(element.as) != "undefined") return true;
	else return false;
}

