﻿/************************************************************************************************
Variables
************************************************************************************************/
var popUps = new Array();	
var tabs = new Array();
var instructions;
var maxHeight;
var util;
var loading;
var selectedTabId = "";

/************************************************************************************************
Methods
************************************************************************************************/
function destroyPopUps(clearTarget) {
   for(var popUpName in popUps)
        popUps[popUpName].destroy(clearTarget); 
   popUps = new Array();   
}

function initPopUps() {                             
    
    for(var popUpName in popUps)
        popUps[popUpName].init();    
}

function preTabChange(newTabId,loadingId) {
    var tab;

    if(newTabId == selectedTabId) return false;
    
    if(loading) loading.toggleContent(false);

    //Set selected
    selectedTabId = newTabId
    
    //Find the loading area
    loading = new SearchCriteriaTab(newTabId,[loadingId]);    

    //Show the new tab and area if no loading area               
    for(var tabId in tabs) {       
        tab = tabs[tabId];        
        tab.toggleTab(tabId == newTabId);                                                                
        tab.toggleContent(tabId == newTabId && !loading);
    }    
    
    //Show the loading area
    if(loading) loading.toggleContent(true);
    
    return true;
    
}

function postTabChange() {
    if(!loading) return;
    var tabId = loading.options.tab[0].id
    var tab = tabs[tabId];    
    if(tab) {
        tab.toggleContent(true);
    }
    loading.toggleContent(false);        
}
				
				
/****************************************************************************************
JQuery Popup Implementation 
****************************************************************************************/
function SearchCriteriaPopup(popUpName,popUpId,hdnId,listId,targetId,editId,clearId,closeId) {       	
	var _self = this;
	   
	// set default values	
	_self.defaults = {
	    popUpName: null,            // popup name
		trigger: null,              // elem that will toggle the pop up
		popup: null,                // elem that is the popup
		popupOrig: null,            // initial popup element before Anthem re-wrap
		hdn: null,                  // hidden input that contains selected ids
		list: null,                 // ul that holds the list options
		target: null,               // ul where the selected options appear
		edit: null,                 // additional element to toggle the pop up
		clear: null,                // element that clears target
		instructions: instructions, // instructional copy
		maxHeight: maxHeight       // max height of the popup list - make it in integer		
	};
	
	// set instance values
	var opts = {
	    popUpName: popUpName,
	    trigger: $("#" + targetId),
	    popup: $("#" + popUpId).parent(),  //The Anthem wrapper around our original popup element
        popupOrig: $("#" + popUpId),	    
	    hdn: $("#" + hdnId),
	    list: $("#" + listId),
	    target: $("#" + targetId),	    
	    edit: $("#" + editId),
	    clear: $("#" + clearId),
	    close: $("#" + closeId)	    
    };
	
	// merge in custom options
	_self.options = $.extend({}, _self.defaults, opts);
}

SearchCriteriaPopup.prototype = {
	
	init: function() {
		var _self = this;
		var popup = _self.options.popup;
		var popupOrig = _self.options.popupOrig;
		var popupParentTag;
		
		// set up click events
		_self.bindEvents();
		
		// add initial instructions into target
		_self.initInstructions();
			
		// apply the maximum height for the popup list
		_self.setMaxHeight();
		
		// if using IE, insert iframe layer so the popup can overlay select boxes and flash elements
		if ($.browser.msie) {
			_self.insertIframeHack();
		}				
				
		// update the Anthem generated outter div
		if (!popup.hasClass("popup"))
		    popup.addClass("popup");
		if (!popup.hasClass("hidden"))
		    popup.addClass("hidden");
		popup.css({left: "-9999px"});

        // clear classes set on the inner div		
		if (popupOrig.hasClass("popup"))
		    popupOrig.removeClass("popup");    		    		    		    
		if (popupOrig.hasClass("hidden"))
		    popupOrig.removeClass("hidden");
		           		   				
		// reposition the popup in the DOM to avoid z-index issues
		popupParentTag = popup.parent().get(0).id.toLowerCase();
		if( popupParentTag != "bgwrapper")
		    popup.appendTo("#bgWrapper");
		
	},
	
	destroy: function(clearTarget) {
	    var _self = this;
	    
	    if(clearTarget) {	    		
		    _self.options.target.html("");
    		_self.targetDidChange();
        }	     
	       		
		_self.options.trigger.unbind("click", _self.togglePopUp);
		_self.options.close.unbind("click", {that: _self}, _self.togglePopUp);
		_self.options.popup.find("li a").each(function(i) {
		    $(this).unbind("click");
		    });
		_self.options.edit.unbind("click");	        	        
		_self.options.clear.unbind("click");	        	        
    },
	
	bindEvents: function() {
		var _self = this;
		_self.options.trigger.bind("click", {that: _self}, _self.togglePopUp);
		_self.options.close.bind("click", {that: _self}, _self.togglePopUp);
		_self.options.popup.find("li a").each(function(i) {
			$(this).bind("click", {that: _self}, function(event) {
					if ($(this).hasClass("selected")) {
						$(this).removeClass("selected");
						_self.clearItemFromTarget(event, $(this));
					} else {
						$(this).addClass("selected");
						_self.sendItemToTarget(event, $(this));
					}
				return false;
			});
		});
		_self.options.edit.bind("click", {that: _self }, _self.togglePopUp);
		_self.options.clear.bind("click", {that: _self }, _self.clearAllItemsFromTarget);
	},

	addInstructions: function() {
		var _self = this;
		_self.options.target.html("<li class='popBlurb'>" + _self.options.instructions + "</li>");
	},
	
	clearInstructions: function() {
		var _self = this;
		_self.options.target.find(".popBlurb").remove();
	},
	
	initInstructions: function() {		
	    var _self = this;        
        if(_self.options.target.children().length == 0 && !_self.instructionsPresent())
            _self.addInstructions()
    },
	
	instructionsPresent: function() {
		var _self = this;
		if (_self.options.target.find(".popBlurb").length > 0) {
			return true;
		} else {
			return false;
		}
	},
	
	targetDidChange: function() {
		var _self = this;
		var hdn = _self.options.hdn[0];			
		
		if (_self.options.target.children().length == 0) {
			_self.addInstructions();
		} else if (_self.options.target.children().length > 1) {
			_self.clearInstructions();
		}
		
		hdn.value = "";
		//Rebuild the id collection
		_self.options.popup.find(".selected").each(function() {			
			
			//Get the numeric identifier
            var id = $(this).attr("id").replace(_self.options.popUpName,"");                    
            
            //Verify id is valid
            if(id == undefined || id == "" || id == "0") return;
            
            //Verify doesn't exist            
            var ids = hdn.value.split(",");
            for(var i = 0; i < ids.length; i++){
                if(ids[i] == id) return;                
            }
                                    
            //Append to collection if valid                    
            if(hdn.value == '')
                hdn.value = id;
            else
                hdn.value += "," + id;
			
		});				
	},
	
	togglePopUp: function(event) {
		var _self = event.data.that;
		var popup = _self.options.popup;		
		var x = event.pageX - 25;
		var y = event.pageY - 70;
		
		if (popup.hasClass("hidden")) {
			_self.closeAnyOpenPopups();
			popup.removeClass("hidden");
			popup.css({position: "absolute", left: x + "px", top: y + "px"});
		} else {
			popup.addClass("hidden");
			popup.css({left: "-9999px"});
		}
		return false;
	},
	
	sendItemToTarget: function(event, element) {
		var _self = event.data.that;
		var text = element.text();
		var ident = element.attr("id");
		if (_self.instructionsPresent == true) {
			_self.clearInstructions();
		}
		_self.options.target.append("<li id='" + ident + "'>" + text + "</li>");
		_self.targetDidChange();
		return false;
	},
	
	clearItemFromTarget: function(event, element) {
		var _self = event.data.that
		var ident = element.attr("id");
		_self.options.target.find("#" + ident ).remove();
		_self.targetDidChange();
	},
	
	clearAllItemsFromTarget: function(event) {
		var _self = event.data.that;
		_self.options.target.html("");
		_self.options.popup.find(".selected").each(function() {
			$(this).removeClass("selected");
		})
		_self.targetDidChange();
		return false;
	},
	
	closeAnyOpenPopups: function() {
		var _self = this;
		$(".popup").each(function () {
			if (!$(this).hasClass("hidden") && $(this) != _self.options.popup) {
				$(this).addClass("hidden");
				$(this).css({left: "-9999px"});
			}
		});
	},
	
	insertIframeHack: function() {
		var _self = this;
		if(!_self.iframeAdded) {
		    _self.iframeAdded = true;
		    _self.options.popup.prepend("<iframe src='#' marginwidth='0' marginheight='0' align='bottom' scrolling='no' frameborder='0' style='position:absolute; left:0; top:0px; display:block; filter:alpha(opacity=0);'></iframe>");
		}
	},
	
	
	setMaxHeight: function() {
		var _self = this;
		var list = _self.options.popup.find("ul");

		if ($.browser.msie) {
			// for some reason list.scrollHeight returns undefined, so we use list[0].scrollHeight
			if (list[0].scrollHeight > _self.options.maxHeight) {
				list.css("height", _self.options.maxHeight + "px");
			} else {
				list.css("height", "auto");
			}
		} else {
		list.css("max-height", _self.options.maxHeight);
	}
}
}
					
				
/****************************************************************************************
JQuery Tab Implementation 
****************************************************************************************/
function SearchCriteriaTab(tabId,contentIds,selectedClassName) {  
    var _self = this;
        
    var content = new Array(1);
    for(var i = 0; i < contentIds.length; i++){
        content[i] = $("#" + contentIds[i]);     
    }  
        
    _self.defaults = {
	    selectedClassName: null,    // tab selected className
		tab: null,                  // tab element
		content: new Array(1)       // content associated with this tab
	};
	
	// set instance values
	var opts = {
	    selectedClassName: selectedClassName,
	    tab: $("#" + tabId),
	    content: content   
    };
	
	// merge in custom options
	_self.options = $.extend({}, _self.defaults, opts);            
}	    

SearchCriteriaTab.prototype = {	    
    
   toggleTab: function(selected) {
        var _self = this;
        var tab = _self.options.tab;
        var className = _self.options.selectedClassName;
        
        if(!tab) return;
        if(selected==true){
            if(!tab.hasClass(className))
                tab.addClass(className);
        } else {
           if (tab.hasClass(className))		
	            tab.removeClass(className);
        }                                    
    },        
    
    toggleContent:  function(show) {
        var _self = this;
        var content = _self.options.content;
        var className = "displayNone";
        var item;
        
        if(!content) return;
        if(content.length <= 0) return;
        
        for(var i = 0; i < content.length; i++) {
            item = content[i];
            if(item) {
                if(show!=true){
                    if(!item.hasClass(className))
                        item.addClass(className);
                } else {
                   if (item.hasClass(className))		
                        item.removeClass(className);
                }     
            }
        }
        
    }         
}	
