/*
 * 	 imWhoAmI - A JQuery Personal Plugin 
 * 	 @author Les Green
 * 	 Copyright (C) 2010 Intriguing Minds, Inc.
 *   Version 0.5
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.

 *   Demo and Documentation can be found at:   
 *   http://www.grasshopperpebbles.com
 *   
 */

//retrieve domain name - the document.domain property contains the domain of the server from which the page was loaded. 
//var myDomain = document.domain;

/*(function(){
	  $.getJSON('http://adam.kahtava.com/services/open-source/projects.json?project-host:username=github:adamdotcom&callback=?', function(data) {
	    alert(data);
	  });
	})();*/

;(function($) {
	$.fn.extend({
        imWhoAmI: function(options) { 
        	opts = $.extend({}, $.whoami.defaults, options);
			return this.each(function() {
				new $.whoami(this, opts);
			});
        }
    });	

$.whoami = function(obj, opts) {
	var $this = $(obj);
	var selected = '';
	var main_selected = '';
	var main_cntnr = '';
	var sub_cnt = 0;
	//var ar_apps = new Array();
	if (opts.menu_url) {
		doAjax('GET', opts.menu_url, '', opts.data_type, '', init);
	}
	
	function init(data) {
		var li, sp, ul, cId, pos, pop, nL;
		
		$this.append($('<div></div>').attr('id', opts.menu_cntnr));
		var mW = $('#'+opts.menu_cntnr).width();
		var mL = ($this.width() - parseInt(mW))/2 +'px';
		$('#'+opts.menu_cntnr).css('left', mL);
		
		ul = $('<ul></ul>');
		$(ul).appendTo($('#'+opts.menu_cntnr));
		$.each(data, function(i, itm) {
			li = $('<li></li>');
			if (itm.menuItem.list_class) {
				$(li).addClass(itm.menuItem.list_class);
			} 
			cId = getCntnrId(i, itm.menuItem);
			sp = getLabel(itm.menuItem, li, 'main', cId);
			$(sp).appendTo($(li));
			$(li).appendTo($(ul));
			
			//if ((itm.menuItem.menuItem) || (itm.menuItem.app_name)) {
				pos = $(li).offset();
			//}
			
			if (itm.menuItem.menuItem) {
				var subCntnr = $('<div></div>').addClass(opts.sub_cntnr_class).attr('id', cId).css('left', pos.left).appendTo($this);
				var subHdr = $('<div></div>').addClass(opts.sub_cntnr_hdr_class).appendTo($(subCntnr));
				var subMnu = $('<div></div>').addClass(opts.sub_menu_cntnr).appendTo($(subCntnr));
				var subs = getSubItems(itm.menuItem);
				$(subs).appendTo($(subMnu));
			} else if (itm.menuItem.app_name) {
				$(document.body).imSociable({
					control_btn: li,
					sites_url: opts.sociable_sites_url,
					icon_base_url: opts.sociable_icons_url,
					sociable_cntnr: opts.sociable_cntnr,
					sociable_cntnr_id: cId,
					sociable_header: opts.sociable_header,
					sociable_content: opts.sociable_content,
					sociable_cntnr_pos: pos.left,
					sociable_column: opts.sociable_column
				});	
			} else if (itm.menuItem.popup_text) {
				pop = $('<div></div>').addClass(itm.menuItem.popup_class).attr('id', cId).html(itm.menuItem.popup_text).appendTo($this);
				nL = pos.left - ($(pop).width()/2);
				$(pop).css('left', nL);
			}	
		});
	};
	
	function getCntnrId(index, itm) {
		var cId = '';
		if (itm.app_name) {
			cId = itm.app_name+index;
		} else if (itm.popup_text) {
			cId = 'imWhoAmIPopUp'+index;
		} else {
			cId = 'imWhoAmISubCntnr'+index;
		}
		return cId;  
	};
		
	function getSubItems(itm) {
		var li, sp;
		var ul = $('<ul></ul>');
		$.each(itm.menuItem, function(i, sub) {
			li = $('<li></li>');
			if (sub.list_class) {
				$(li).addClass(sub.list_class);
			}
			sp = getLabel(sub, li, 'sub', 'imWhoAmISub'+i);
			$(sp).appendTo($(li));
			if (sub.menuItem) {
				var subs = getSubItems(sub);
				$(subs).css('display', 'none').appendTo($(li));
			}
			$(li).appendTo($(ul));
		});
		return $(ul);
	};
	
	function getLabel(itm, li, level, id) {
		var sp = $('<a></a>').html(itm.label);
		if (itm.sep) {
			$(sp).addClass(opts.menu_group_sep);
		}
		if (itm.url) {
			$(sp).data("clickEvent", {url: itm.url});
			$(sp).attr({
				'href': itm.url,
				'target': itm.target
			});
		//} else if (itm.app_name) {
			
		} else {
			$(sp).data("clickEvent", {'level': level, 'state': 'closed', 'sub_cntnr': id});
			$(sp).hover(function() {
				$(this).css('cursor', 'pointer');
			}, function() {
				$(this).css('cursor', 'default');
			});
			addClickEvent(sp, li);
		}
		return sp;
	};
	
	
	function addClickEvent(sp, li) {
		var tf;
		var sCntnr = $(sp).data("clickEvent").sub_cntnr;
		$(sp).click(function() {
			if ($(sp).data("clickEvent").level == 'sub') {
				if ($(sp).data("clickEvent").state == 'closed') {
					$('>ul', li).slideDown('slow');
					tf = closeSelectedSub();
					selected = sp;
					updateClickData(sp, 'sub', 'open', sCntnr);
					/*$(sp).data("clickEvent", {
						'level': 'sub',
						'state': 'open'
					});*/
				}
				else {
					$('>ul', li).slideUp('slow');
					/*if (last_selected) {
						$(last_selected).slideDown('slow');
					}*/
					updateClickData(sp, 'sub', 'closed', $(selected).attr('id'));
					/*$(sp).data("clickEvent", {
						'level': 'sub',
						'state': 'closed'
					});*/
					selected = '';
				}
			} else {
				if ($(sp).data("clickEvent").state == 'closed') {
					$('#'+sCntnr).slideDown('slow');
					//$(this).addClass(opts.menu_selected);
					//$(this).addClass(opts.home_class + ' ' + opts.menu_group_sep);
					//$(li).siblings().slideUp('slow');
					if (main_cntnr) {
						//if sub open, close it
						tf = closeSelectedSub();
						$(main_cntnr).slideUp('slow');
						updateClickData(main_selected, 'main', 'closed', $(main_selected).attr('id'));
						/*$(main_selected).data("clickEvent", {
							'sub_cntnr': $(main_cntnr).attr('id'),
							'level': 'main',
							'state': 'closed'
						});*/
					}
					main_cntnr = $('#'+sCntnr);
					main_selected = sp;
					$(sp).data("clickEvent", {
						'sub_cntnr': sCntnr,
						'level': 'main',
						'state': 'open'
					});
				}
				else {
					//if sub open, close it
					tf = closeSelectedSub();
					$('#'+sCntnr).slideUp('slow');
					updateClickData(sp, 'main', 'open', sCntnr);
					/*$(sp).data("clickEvent", {
						'sub_cntnr': sCntnr,
						'level': 'main',
						'state': 'open'
					});*/
					main_cntnr = '';
					main_selected = '';
				}
			}
		});
	};
	
	function closeSelectedSub() {
		if (selected) {
			$(selected).siblings().slideUp('slow');
			var sCntnr = $(selected).data("clickEvent").sub_cntnr;
			updateClickData(selected, 'sub', 'closed', sCntnr)
			/*$(selected).data("clickEvent", {
				'level': 'sub',
				'state': 'closed'
			});*/
		}
		return true;
	};
	
	function updateClickData(el, level, state, id) {
		$(el).data("clickEvent", {'level': level, 'state': state, 'sub_cntnr': id});
	}
	
	function doAjax(t, u, d, r, fnBefore, fnSuccess) {
		$.ajax({
			type: t,
			url: u,
			data: d,
			dataType: r,
			beforeSend: fnBefore, //function(){$("#loading").show("fast");}, //show loading just when link is clicked
			//complete: function(){ $("#loading").hide("fast");}, //stop showing loading when the process is complete
			success: fnSuccess,//{ //so, if data is retrieved, store it in html
			error: showError
	 	}); //close $.ajax(
	};
	
	function showError(XMLHttpRequest, textStatus, errorThrown) {
		console.log(textStatus);
	};
	
};

$.whoami.defaults = {
	menu_url: '',
	menu_cntnr: '',
	sub_cntnr_class: '',
	sub_cntnr_hdr_class: 'imWhoAmISubHeader',
	sub_menu_cntnr: 'imWhoAmISubMenuCntnr',
	home_class: '',
	menu_selected: '',
	menu_group_sep: '',
	data_type: 'json',
	sociable_sites_url: '',
	sociable_icons_url: '',
	sociable_cntnr: '',
	sociable_header: '',
	sociable_content: '',
	sociable_column: ''
	//main_selected_class: '',
	//sub_selected_class: ''
};
})(jQuery);
