YAHOO.namespace("ps.People");
(function () {
    var Dom  = YAHOO.util.Dom,
    	Ev   = YAHOO.util.Event,
    	Hist = YAHOO.util.History,
    	Ppl  = YAHOO.ps.People,
    	Bc   = false;

	var config = { title: '',
				   ajaxPath: '',
				   breadTitle: '',
				   breadcrumb: true,
				   details: true,
				   disableSearch: false,
				   officeOnly: '' };
	
	var setConfig = function (keys) {
		for(var i in keys) {
			if (YAHOO.lang.hasOwnProperty(keys, i)) {
				config[i] = keys[i];
			}
		}
	};

    // Private variables
    var previousState,
    	currentState,
    	results;
    
    // List of characters
	var alpha = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", 
	             "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "All"];
    
    var values = { search: '',
    	    	   char: '',
    	    	   lang: '',
		           lic: '',
		           office: 0,
		           page: 1,
		           limit: 10,
		           order: 'last_name',
		           id: '' };

	var updateValues = function (keys) {
		for(var i in keys) {
			if (YAHOO.lang.hasOwnProperty(keys, i)) {
				values[i] = keys[i];
			}
		}
	};
	
	var parseValues = function (strValues) {
		var tmpValues = {};
		var aPairs = strValues.split("&");
	 	for(var i=0; i<aPairs.length; i++) {
	     	var sPair = aPairs[i];
	     	if(sPair.indexOf("=") > 0) {
	         	var n = sPair.indexOf("=");
	         	var sParam = aPairs[i].substring(0,n);
	         	var sValue = aPairs[i].substring(n+1);
	         	tmpValues[sParam] = sValue;
	     	}
	 	}
	 	updateValues(tmpValues);
	};
	
	var stringifyValues = function () {
		var strValues = '';
		for(var i in values) {
			if (YAHOO.lang.hasOwnProperty(values, i)) {
				strValues += '&' + i + '=' + values[i];
			}
		}
		// Removed first ampersand
		strValues = strValues.substring(1);
		return strValues;
	};

	var getCurrState = function() {
		var currState = Hist.getCurrentState("criteria");
		return currState;
	};
	
	var getPrevState = function() {
		return previousState;
	};

	var recordHistory = function() {
		// Get new and current values
		var newState  = stringifyValues();
		var currState = getCurrState();

		if (newState !== currState) {
			previousState = currState;
			try {
				Hist.navigate('criteria', newState);
			} catch (e) {
				setupPage(newState);
			}
		}

	};
	
	var hideDetails = function() {
		values['id'] = '';
		recordHistory();
	};
	
	var setDetailsBody = function(content) {
        // Load HTML to details div tag
        document.getElementById('pplDetails').innerHTML = content; 
        
        var search = content; 
        var script; 
        // Find all javascript and append the code to the header to run commands      
        while (script = search.match(/(<script[^>]+javascript[^>]+>\s*(<!--)?)/i)) { 
            search = search.substr(search.indexOf(RegExp.$1) + RegExp.$1.length); 
           
            if (!(endscript = search.match(/((-->)?\s*<\/script>)/))) break; 
           
            block  = search.substr(0, search.indexOf(RegExp.$1)); 
            search = search.substring(block.length + RegExp.$1.length); 
            // Create script element, add text and append child
            var oScript = document.createElement('script'); 
            oScript.text = block; 
            document.getElementsByTagName("head").item(0).appendChild(oScript); 
        } 
    };

	var setupPage = function(strValues) {
		parseValues(strValues);

		if (values['id'] != '' && Dom.inDocument('pplDetails')) {
			// Empty the body and add the loading image first
			document.getElementById('pplDetails').innerHTML = '';
			YAHOO.util.Dom.addClass('pplDetails','loading');
			// Make sure page has been scrolled to the top
			scroll(0,0);
			// First get the content 
			var postData = 'id=' + values['id'];
	        YAHOO.util.Connect.asyncRequest('POST', '/server/associates/details', detailsCallback, postData); 
	        
	        // Hide search and set footer
	        YAHOO.util.Dom.addClass('boxMain','hide');
			YAHOO.util.Dom.removeClass('pplDetails','hide');	
		} else {
			// Make sure details is closed if open
			if (!Dom.hasClass('pplDetails', 'hide')) {
		        Dom.removeClass('boxMain', 'hide');
				Dom.addClass('pplDetails', 'hide');
        		Dom.addClass('quicklink', 'hide');
        		// Update breadcrumb
    			removeLastCrumb();
    			removeLastCrumb();
    			addCrumb('bcResults', 'span', config['breadTitle'], null);
			}
			// Setup form elements
			if (config['officeOnly'] == '' && config['disableSearch'] == false) {
				YAHOO.ps.Form.setDropDown("office", values['office']);
			}
			if (config['disableSearch'] == false) {
				YAHOO.ps.Form.setDropDown("lang", values['lang']);
				YAHOO.ps.Form.setDropDown("license", values['lic']);
				inputSearch.value = values['search'];
			
				// Make sure existing highlighted class has been removed
				for(var i in alpha) {
					Dom.removeClass('char' + alpha[i], 'selected');
				}
				// Highlight new character if not empty
				if (values['char'] != '') {
					Dom.addClass('char' + values['char'], 'selected');
				}
			}
			
			// Show wait screen since IE is slow to render
		    if (YAHOO.util.Dom.inDocument('wait')) {  
		    	YAHOO.ps.container.wait.show();
		    } 
	
			// Run AJAX request and post values to get results
			YAHOO.util.Connect.asyncRequest('POST', config['ajaxPath'], searchCallback, strValues); 
		}
	};
	
	var buildListView = function () {
		var html = '';
		// Get main list header

		// Build each agent for list view
		html += '<div class="row header">';
		html += '<div class="name">Name</div><div class="title">Title</div>';
		html += '<div class="phone">Phone Number</div><div class="office">Office</div>';
		html += '<div class="links">Email / Website</div></div>';
		
		for(var i in results) {
			if (YAHOO.lang.hasOwnProperty(results, i)) {
				// Build each agent for list view
				html += '<div class="row">';
				html += '<div class="name';
				if (config['details']) {
					html += '" onClick="YAHOO.ps.People.showDetails(' + results[i]['id'] + ');"';
				} else {
					html += ' nocursor"';
				}				
				html += '>' + results[i]['last_name'] + ', ' + results[i]['first_name'] + '</div>';
				html += '<div class="title';
				if (config['details']) {
					html += '" onClick="YAHOO.ps.People.showDetails(' + results[i]['id'] + ');"';
				} else {
					html += ' nocursor"';
				}				
				html += '>' + results[i]['title'];
				html += '</div><div class="phone';
				if (config['details']) {
					html += '" onClick="YAHOO.ps.People.showDetails(' + results[i]['id'] + ');"';
				} else {
					html += ' nocursor"';
				}				
				html += '>';
				
				if (results[i]['number_default'] == 'office' || results[i]['mobile_visibility'] > 0) {
					html += results[i]['number_office'];
				} else if (results[i]['number_default'] == 'direct' || results[i]['mobile_visibility'] > 0) {
					html += results[i]['number_direct'];
				} else if (results[i]['number_default'] == 'mobile' && results[i]['mobile_visibility'] == 0) {
					html += results[i]['number_mobile'];
				}

				html += '</div><div class="office';
				if (config['details']) {
					html += '" onClick="YAHOO.ps.People.showDetails(' + results[i]['id'] + ');"';
				} else {
					html += ' nocursor"';
				}					
				html += '>' + results[i]['office'] + '</div>';
				html += '<div class="links"><a href="javascript:void(0);" onClick="YAHOO.ps.Popup.contact.showAgent(\'\', ' + results[i]['id'] + ');">Email</a>';
				if (YAHOO.lang.isString(results[i]['web_address']) && results[i]['web_address'] != '') {
					html += '<span>/</span><a target="agent" href="' + results[i]['web_address'] + '">Website</a>';
				}
				html += '</div></div>';
			}
		}
		Dom.get('contentPic').innerHTML  = '';
		Dom.get('contentList').innerHTML = html;
	};
	
	var buildPictureView = function () {
		
		var html = '';
		for(var i in results) {
			if (YAHOO.lang.hasOwnProperty(results, i)) {
				// Build each agent for list view
				html += '<div class="pictureView"><div class="picImage">';
				if (config['details']) {
					html += '<a href="javascript:void(0);" onClick="YAHOO.ps.People.showDetails(' + results[i]['id'] + ');">';
				}
				// TODO: Show user image
				if (results[i]['photo'] != '') {
					html += '<img src="' + results[i]['photo'] + '" />';
				} else {
					html += '<img class="comp" src="/resources/images/logo-sm.gif" />';
				}
				if (config['details']) {
					html += '</a>';
				}
				html += '</div><div class="picInfo"><div class="title">' + results[i]['last_name'] + ', ' + results[i]['first_name'] + '</div>';
				if (results[i]['title'] != '') {
					html += '<div class="info"><div class="left">Title:</div><div class="right">' + results[i]['title'] + '</div></div>';
				}
				html += '<div class="info"><div class="left">Office:</div><div class="right">' + results[i]['office'] + '</div></div>';
				

				if (results[i]['number_default'] == 'office') {
					html += '<div class="info"><div class="left">Phone:</div><div class="right">' + results[i]['number_office'] + '</div></div>';
				} else if (results[i]['number_default'] == 'direct') {
					html += '<div class="info"><div class="left">Phone:</div><div class="right">' + results[i]['number_direct'] + '</div></div>';
				} else if (results[i]['number_default'] == 'mobile') {
					html += '<div class="info"><div class="left">Phone:</div><div class="right">' + results[i]['number_mobile'] + '</div></div>';
				}
				
				html += '<div class="links"><div class="left"><a href="javascript:void(0);" ';
				html += 'onClick="YAHOO.ps.Popup.contact.showAgent(\'\', ' + results[i]['id'] + ');">Send Email</a></div>';
				if (YAHOO.lang.isString(results[i]['web_address']) && results[i]['web_address'] != '') {
					html += '<div class="right"><a target="agent" href="' + results[i]['web_address'] + '">Visit Website</a></div>';
				}
				html += '</div></div></div>';
			}
		}
		Dom.get('contentList').innerHTML = '';
		Dom.get('contentPic').innerHTML  = html;
	};

	//////////////////////////////////
    // Search AJAX
	//////////////////////////////////
	var handleSearchSuccess = function(o) {
		if (YAHOO.util.Dom.inDocument('wait')) {  
		    YAHOO.ps.container.wait.hide();
		}
		// Run response Ajax response through common eval
		var response = YAHOO.ps.Ajax.eval(o);
		// If not false response was evaluated
		if (response !== false) {
	               
	        if (response['success'] <= 0) {  
				// Error message
    			//updateMessage(response['error'],'message',true);
	        } else { 
				// Setup the page variables
				var recordsReturned = response['users']['records'].length;
				var startIndex = (response['users']['page']-1) * response['users']['recordsPerPage'];
				var endIndex = startIndex + recordsReturned;
				var totalRecords = parseInt(response['users']['totalRecords'], 10);

				addNavigation(startIndex, endIndex, totalRecords, recordsReturned);
				
				if (totalRecords == 0) {
					Dom.removeClass('boxNoResults', 'hide');
					Dom.addClass('boxResults', 'hide');
				} else {
					Dom.removeClass('boxResults', 'hide');
					Dom.addClass('boxNoResults', 'hide');
					// Set results to global variable so changing tabs can populate field
					results = response['users']['records'];
					
					if (values['view'] == 0) {
						buildListView();
					} else {
						buildPictureView();
					}
				}               
	        }               
	    }    
	};
	                   
	var handleSearchFailure = function(o) {
		if (Dom.inDocument('wait')) {  
		    YAHOO.ps.container.wait.hide();
		}
	    if (o.responseText !== undefined){
			// Error message
	    }
	}; 
	
	var searchCallback =
	{
	    success:handleSearchSuccess,
	    failure:handleSearchFailure,
	    timeout:6000
	};
	
	//////////////////////////////////
    // Details AJAX
	//////////////////////////////////
	var handleDetailsSuccess = function(o) {
		if (YAHOO.util.Dom.inDocument('wait')) {  
		    YAHOO.ps.container.wait.hide();
		}
		// Run response Ajax response through common eval
		var response = YAHOO.ps.Ajax.eval(o);
		// If not false response was evaluated
		if (response !== false) {
	               
            YAHOO.util.Dom.removeClass('pplDetails','loading');                                
            if (response['success'] <= 0) { 
            	// Error
            } else {  
        		Dom.removeClass('quicklink','hide');
        		// Remove last crumb without click listener
        		removeLastCrumb();
        		addCrumb('bcResults', 'span', config['breadTitle'], hideDetails);
        		addCrumb('bcDetails', 'span', response['title'], null, 4);
				setDetailsBody(response['content']); 
            }                      
	    }    
	};
	                   
	var handleDetailsFailure = function(o) {
		if (Dom.inDocument('wait')) {  
		    YAHOO.ps.container.wait.hide();
		}
	    if (o.responseText !== undefined){
			// Error message
	    }
	}; 
	
	var detailsCallback =
	{
	    success:handleDetailsSuccess,
	    failure:handleDetailsFailure,
	    timeout:6000
	};

	var addNavigation = function(startIndex, endIndex, totalRecords, recordsReturned) {
		// Set page message
		var msg = '';
		if (totalRecords == 0) {
			msg = '<h2>No ' + config["title"] + ' Found</h2>';
		} else if (totalRecords > 0 && recordsReturned == totalRecords) {
			msg = '<h2>' + config["title"] + ' ' + (startIndex+1) + ' - ' + endIndex + '</h2>';
		} else {
			msg = '<h2>' + config["title"] + ' ' + (startIndex+1) + ' - ' + endIndex + 
			   	  '</h2> <span class="note">(of ' + totalRecords + ' ' + config["title"] + ' Total)</span>';	
		}
		Dom.get("boxTitle").innerHTML = msg;

		if (config['disableSearch'] == false) {
			paginator.setState({
				rowsPerPage : values['limit'],
				totalRecords : totalRecords,
				recordOffset : startIndex
			});
		}
	};

	var searchChange = function () {
		// Get top values and compare then against current values
		if (config['officeOnly'] == '') {
			values['office'] = dropOffice.options[dropOffice.selectedIndex].value;
		} else {
			values['office'] = config['officeOnly'];
		}
		values['lic']    = dropLicense.options[dropLicense.selectedIndex].value;
		values['lang']   = dropLang.options[dropLang.selectedIndex].value;
		values['search'] = inputSearch.value;
		// Clear char
		values['char'] = '';
		values['id']   = '';
		values['page'] = 1;

		// Make sure page has been scrolled to the top
		recordHistory();
	};
	
	var pageChange = function (page) {
		// Set variables
		var newPage = 1;
		if (YAHOO.lang.isNumber(page)) {
			newPage = page;
		}
		values['page'] = newPage;

		// Make sure page has been scrolled to the top
		//scroll(0,0);
		recordHistory();
	};
	
	var charChange = function (char) {	
		if (char == 'All') {
			values['char'] = '';
		} else {
			values['char'] = char;
		}
		values['search'] = '';
		values['lic']    = '';
		values['lang']   = '';
		values['page']   = 1;
		
		if (config['officeOnly'] == '') {
			values['office'] = '';
		} else {
			values['office'] = config['officeOnly'];
		}
		
		// Make sure page has been scrolled to the top
		//scroll(0,0);
		recordHistory();
	};
	
	var showDetails = function(id) {
		values['id'] = id;
		recordHistory();
	};
	

	var tabChange = function () {
		if (Dom.hasClass('contentList','yui-hidden')) {	
			values['view'] = 1;
			buildPictureView();
		} else {
			values['view'] = 0;
			buildListView();
		}
	};
	
	var removeLastCrumb = function() {
		if (config['breadcrumb']) {
			Bc.removeItem();
		}
	};
	
	var getCrumbItems = function() {
		var items = Bc.getItems();
		return items;
	};
	
	var addCrumb = function(id, node, text, click, margin) {
		if (config['breadcrumb']) {
			Bc.addItem(id, node, text, click, margin);
		}
	};
    
 	// Elements
    var pageTab,
    	paginator,
    	dropOffice,
    	dropLicense,
    	dropLang,
    	inputSearch;
    
    var initTabs = function() {
        // Create tab and set default view
		pageTab = new YAHOO.widget.TabView("boxAssociates");
		pageTab.addListener("activeTabChange", tabChange);
		pageTab.selectTab(0);
    };
    
    var initPaginator = function () {
    	paginator = new YAHOO.widget.Paginator({
			alwaysVisible : true,
			containers : ['boxNavTop', 'boxNavBottom'],
			firstPageLinkLabel : "First",
			previousPageLinkLabel : "Prev",
			nextPageLinkLabel : "Next",
			lastPageLinkLabel : "Last"
		});
    	paginator.subscribe('changeRequest', function(state) {
    		paginator.setState(state);
    		pageChange(state.page);
    	});
		paginator.render();
    };
    
    var initCharSelector = function () {
		var strAlpha = 'Find By Last Name: ';
		for(var i in alpha) {
			if (YAHOO.lang.hasOwnProperty(alpha, i)) {
				strAlpha += '<a id="char' + alpha[i] + '" href="javascript:void(0);" ' +
						    'onClick="YAHOO.ps.People.charChange(\'' + alpha[i] + '\');">' + alpha[i] + '</a>';
			}
		}
		Dom.get('boxAlpha').innerHTML = strAlpha;
    }
	
    // Get the DOM object for the results message and setup the map initializer
    Ev.onDOMReady(function () {
		// Set references to form elements
    	if (config['officeOnly'] == '' && config['disableSearch'] == false) {
    		dropOffice = Dom.get("office");
    	}
    	
    	if (config['disableSearch'] == false) {
    		dropLicense = Dom.get("license");
    		dropLang    = Dom.get("lang");
    		inputSearch = Dom.get("search");
    	}
    		
		if (config['breadcrumb']) {
			Bc = YAHOO.ps.Breadcrumb;
		}

    	// Set search button listener
    	Ev.addListener('searchAgentButton', 'click', searchChange);
    	
    	// Create a key listener for 'Enter' on search field
        var kbEnter = new YAHOO.util.KeyListener('search', { keys:[13] }, { fn:searchChange } );
        kbEnter.enable();

    	// Get the bookmark history and if not null over-ride all
    	var histValues = Hist.getBookmarkedState('criteria');
    	if (!YAHOO.lang.isNull(histValues)) {
    		parseValues(histValues);
    	}
    	
    	// Register initial value
    	var initValues = stringifyValues();
    	Hist.register('criteria', initValues, function(strValues) {
    		setupPage(strValues);
    	});
    	
    	Hist.onReady(function() {
			initTabs();
			
			if (config['disableSearch'] == false) {
				initPaginator();
				initCharSelector();
			}
				
			// run page setup
	    	var initValues = stringifyValues();
			setupPage(initValues);
    	});
    	
    	try {
    		Hist.initialize('yui-history-field', 'yui-history-iframe');
    	} catch (e) {
    		setupPage(initValues);
    	}
    });
    
    // Public functions
    Ppl.recordHistory   = recordHistory;
    Ppl.updateValues    = updateValues;
    Ppl.stringifyValues = stringifyValues;
    Ppl.setConfig		= setConfig;
    Ppl.charChange		= charChange;
    Ppl.hideDetails		= hideDetails;
    Ppl.showDetails		= showDetails;
})();