/*
 * 	 imSociable - A JQuery Site Sharing 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
 *   
 */


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

$.sociable = function(obj, opts) {
	var $this = $(obj);
	var selected = '';
	var main_selected = '';
	var main_cntnr = '';
	//last selected used for sub items
	//var last_selected = '';
	//var last_main_selected = '';
	//var url_selected = '';
	var sub_cnt = 0;
	//var ar_apps = new Array();
	if (opts.sites_url) {
		doAjax('GET', opts.sites_url, '', opts.data_type, '', init);
	}
	
	function init(data) {
		var li, a, ul;
		var ln = data.length;
		var nRows = Math.ceil(ln/opts.num_cols);
		var cnt = 0;
		var rowNum = 0;
		
		var cntnr = $('<div></div>').addClass(opts.sociable_cntnr).attr('id', opts.sociable_cntnr_id).css('left', opts.sociable_cntnr_pos).appendTo($this);
		var hdr = $('<div></div>').addClass(opts.sociable_header).appendTo($(cntnr));
		var cntnt = $('<div></div>').addClass(opts.sociable_content).appendTo($(cntnr));
		
		for (var i=0; i<opts.num_cols; i++) {
			$('<div></div>').attr('id', 'imSociableCol'+i).addClass(opts.sociable_column).append($('<ul></ul>')).appendTo($(cntnt));
		}
		
		$.each(data, function(i, itm) {
			li = $('<li></li>').css('background', "url("+ opts.icon_base_url + itm.favicon  +") no-repeat scroll 0 55% transparent");
			a = getLabel(itm, li);
			$(a).appendTo($(li));
			$('#imSociableCol'+rowNum + ' ul').append($(li));
			cnt++;
			if (cnt == nRows) {
				cnt = 0;
				rowNum++;
			}
		});
	};
	
	function getLabel(itm, li) {
		var a = $('<a></a>').html(itm.site_name);
		var url = itm.submit_url;
		
		url = url.replace('PERMALINK', document.URL);
		url = url.replace('TITLE', document.title);
		$(a).attr({
			'href': url,
			'target': '_blank'
		});
		return a;
	};
	
	
	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);
	};
	
};

$.sociable.defaults = {
	control_btn: '',	
	sites_url: '',
	icon_base_url: '',
	sociable_cntnr: '',
	sociable_cntnr_id: '',
	sociable_header: '',
	sociable_content: '',
	sociable_cntnr_pos: '',
	sociable_column: '',
	data_type: 'json',
	num_cols: 2
	//main_selected_class: '',
	//sub_selected_class: ''
};
})(jQuery);
