/**
 * SocialFootPrint with jQuery
 *
 * Copyright (c) 2009 SocialFootPrint
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 */
(function ($){
    /**
     * Creates social footprint .
     *
     * @example $("#myelem").socialfootprint();
     * @result
     */	
	$.fn.socialfootprint = function(o){
        return this.each(function() 
        {
            new $sf(this, o);
        });
    };
	
    var defaults = {
			SHOW_DELAY : 1000,
			SHOW_DELAY_DETAIL : 800,
			MIN_SIZE_DETAIL : "30px",
			MAX_SIZE_DETAIL : "60px",
			// data
			socialnets : new Array(),
			company : "",
			accounts : new Array()
	};
    
    $.socialfootprint = function(e, o) {
    	this.options    = $.extend({}, defaults, o || {});
    	//constructor
    	var self = this;
    	this.setup(e);
    	this.buildSmallInfo();

    	$("#opendiv").click(function(){
    		self.toogleWidget(self);
    	});

    	$("#company_title_widget_title").empty();
    	$("#company_title_widget_title").append(this.options.company);

    	$("#slider").slider({ orientation: 'vertical', min: 0, max: 100, value: 100 });
    	$("#slider").bind('slide', function(event, ui) {
    		var maxScroll = $("#accounts_all_info_content_widget_into").attr("scrollHeight") - $("#accounts_all_info_content_widget_into").height();
    		var p = ((100 - ui.value) / 100) * maxScroll;
    		$("#accounts_all_info_content_widget_into").attr("scrollTop", p);

    		self.updateScrollBtn();
    	});

    	this.initScrollBtn();

    	$("#urlshow").css("opacity", 0.6);
    	
    	$("#accounts_all_info_content_widget_into_c").bind('mousewheel', function (event, delta) {
    		if (delta > 0){
    			self.scrollDelta(-90);
    		}
    		else {
    			self.scrollDelta(90);
    		}
    	});
    };
    
    
 // Create shortcut for internal use
    var $sf = $.socialfootprint;

    $sf.fn = $sf.prototype = {
    	socialfootprint: '0.1'
    };

    $sf.fn.extend = $sf.extend = $.extend;
    
    $sf.fn.extend({
    	isBuildBigWidget : false,
    	accountImgArr : new Array(),
		isAnimateSlide : false,
		isMouseOverSlide : false,
		isShowSmallWidget : true,
		isPlayAnimate : false,
		tempDeltaScroll: 0,
		
		setup: function(o)
		{
    		$(o).html('<div id="company_title_widget_into"><div id="company_title_widget_title"></div><div id="spacertitle"></div><div id="accounts_small_info_widget_into"></div></div><div id="accounts_all_info_content_widget_into_c"><div id="accounts_all_info_content_widget_into"></div><div id="sliderup"></div><div id="slider"></div><div id="sliderdown"></div></div><div id="opendiv" class="opendivdown"></div><div id="urlshow"></div>');
		},
    	getInfoById: function(from, id, value){
			var baseArr = from;
			var len = baseArr.length;
			for (var i = 0; i < len; i++){
				if (baseArr[i]["id"] == id){
					return baseArr[i][value];
				}
			}
			return "";
    	},

    	setInfoById: function(from, id, value, newval)
    	{
			var baseArr = from;
			var len = baseArr.length;
			for (var i = 0; i < len; i++){
				if (baseArr[i]["id"] == id){
					baseArr[i][value] = newval;
				}
			}
		},

		buildAccountWidget: function(){
		
			if (this.isBuildBigWidget)
				return;
		
			var baseArr = this.options.socialnets;
			var len = baseArr.length;
			
			if (baseArr[len - 1] == undefined){
				len--;
			}
			
			for (var i = 0; i < len; i++){
				var html = "<img class=\"account_button_widget\" src=\"" + baseArr[i]["active_icon"] + "\" alt=\"" + baseArr[i]["name"] + "\" width=\"30\"" + " id=\"button_widget_" + baseArr[i]["id"] + "\"" +"/>";
				$("#accounts_all_info_button_widget_into").append(html);
			}
		
			this.buildAccountDetail();
		
			this.isBuildBigWidget = true;
		},

		buildSmallInfo: function(){
			var baseArr = this.options.socialnets;
			var len = baseArr.length;
			var self = this;
			if (baseArr[len - 1] == undefined){
				len--;
			}
			
			var info = [];
			$("#accounts_small_info_widget_into").empty();
			for (var i = 0; i < len; i++){
				
				info[i] = {id: baseArr[i].id, count: 0};
		
				if (i != 0){
					baseArr[i].show = false;
				}
			}
		
			baseArr = this.options.accounts;
			var len1 = baseArr.length;
			for (var i = 0; i < len1; i++){
				for (var j = 0; j < len; j++){
					if (baseArr[i].base_id == info[j].id){
						info[j].count = info[j].count + 1;
						break;
					}
				}
			}
		
			baseArr = this.options.socialnets;
			for (var i = 0; i < len; i++){
				var html = '<div class="widgeticon" id="button_widget_' +  baseArr[i].id + '"><img alt="' +  baseArr[i].name + '" src="' + baseArr[i].active_icon + '"  /><div>' + info[i].count + '</div></div>';
				$("#accounts_small_info_widget_into").append(html);
				if (i != 0){
					$("#button_widget_" +  baseArr[i].id).css("opacity", 0.4);
				}
			}
		
			$("#accounts_small_info_widget_into").append('<div style="clear: both;"></div>');
			
			$(".widgeticon").click(function(){
		
				if (self.isShowSmallWidget){
					self.toogleWidget(self);
				}
				
				var len1 = self.options.socialnets.length;
				for (var i = 0; i < len1; i++){
					self.options.socialnets[i].show = false;
					$("#button_widget_" +  self.options.socialnets[i].id).css("opacity", 0.4);
				}
		
				var id = this.id.substring(14, this.id.length);
				$(this).css("opacity", 1);
				self.setInfoById(self.options.socialnets, id, "show", true);
				
				self.updateAccountsVisible();
			});
		
			$(".widgeticon").bind("mousemove",function(event){
				$("#urlshow").css("top", event.clientY + 20);
				$("#urlshow").css("left", event.clientX + 20);
			});
		
			$(".widgeticon").bind("mouseleave",function(){
				$("#urlshow").hide();
			});
		
			$(".widgeticon").bind("mouseenter",function(){
				var id = this.id.substring(14, this.id.length);
				var descr = self.getInfoById(self.options.socialnets, id, "descr");
				$("#urlshow").html(descr);
				$("#urlshow").show();
			});
		},

		updateAccountsVisible: function(){
			$(".account_info_detail_type").hide();
		
			$(".account_info_detail_widget").stop();
			$(".account_info_detail_widget").css("height", this.options.MIN_SIZE_DETAIL);
		
			baseArr = this.options.accounts;
			var len = baseArr.length;
			for (var i = 0; i < len; i++){
				var isShow = this.getInfoById(this.options.socialnets, baseArr[i].base_id, "show");
		
				if (isShow){
					$("#account_widget_" + baseArr[i].id).show();
					$("#account_info_detail_type_" + baseArr[i].base_id).show();
				}
				else {
					$("#account_widget_" + baseArr[i].id).hide();
				}
			}
		
			$("#accounts_all_info_content_widget_into").attr("scrollTop", 0);
			$('#slider').slider('option', 'value', 100);
			
			this.updateScrollBtn();
		},

		sortAccount: function(){
			var len = this.options.accounts.length;
			var arr = this.options.accounts;
		
			for (i = 1; i < len; ++i){
				for (j = 0; j < len - i; ++j){
					if (arr[j].base_id > arr[j + 1].base_id){
						var tmp = arr[j];
						arr[j] = arr[j+1];
						arr[j+1] = tmp;
					}
				}
			}
		
			for (i = 1; i < len; ++i){
				for (j = 0; j < len - i; ++j){
		
					if (arr[j].base_id != arr[j + 1].base_id){
						continue;
					}
		
					if (arr[j].name > arr[j + 1].name){
						var tmp = arr[j];
						arr[j] = arr[j+1];
						arr[j+1] = tmp;
					}
				}
			}
		
			for (i = 1; i < len; ++i){
				for (j = 0; j < len - i; ++j){
		
					if (arr[j].base_id != arr[j + 1].base_id){
						continue;
					}
		
					if (arr[j].rank > arr[j + 1].rank){
						var tmp = arr[j];
						arr[j] = arr[j+1];
						arr[j+1] = tmp;
					}
					else if ((!arr[j].rank) && (arr[j + 1].rank))
					{
						var tmp = arr[j];
						arr[j] = arr[j+1];
						arr[j+1] = tmp;
					}
				}
			}
		},

		buildAccountDetail: function(){
			this.sortAccount();
			var baseArr = this.options.accounts;
			var len = baseArr.length;
			var allHtml = "";
			var self = this;
			var currTypeAc = -1;
		
			for (var i = 0; i < len; i++){
		
				if (baseArr[i]["base_id"] == 2){
					this.accountImgArr.push(baseArr[i]);
				}
		
				var base_url = this.getInfoById(this.options.socialnets, baseArr[i].base_id, "base_url");
				if (base_url != ""){
					baseArr[i]["url"] = base_url + baseArr[i]["url"];
				}
		
				if (currTypeAc != baseArr[i]["base_id"]){
					$("#accounts_all_info_content_widget_into").append('<div id="account_info_detail_type_' + baseArr[i]["base_id"] + '" class="account_info_detail_type">' + self.getInfoById(this.options.socialnets, baseArr[i]["base_id"], "descr") + '</div>');
					currTypeAc = baseArr[i]["base_id"];
				}
		
				var imgUrl = this.getInfoById(this.options.socialnets, baseArr[i]["base_id"], "big_icon");
				var imgHtml = "<div class='imgdiv'><img src=\"" + imgUrl + "\" alt=\"icon\" /></div>";
				var html = "<div class=\"account_info_detail_widget\"" + " id=\"account_widget_" + baseArr[i]["id"] + "\" >" + imgHtml + "<div class='contentdiv' >" + baseArr[i]["name"] + "</div>" + "<span>" + baseArr[i]["descr"] + "</span>" + "</div>";
				$("#accounts_all_info_content_widget_into").append(html);
			}
		
			$(".account_info_detail_widget").bind("mousemove",function(event){
				$("#urlshow").css("top", event.clientY + 10);
				$("#urlshow").css("left", event.clientX + 40);
			});
		
			$(".account_info_detail_widget").click(function(){
				var id = this.id.substring(15, this.id.length);
				window.open(self.getInfoById(self.options.accounts, id, "url"));
			});
		
			$(".account_info_detail_widget").bind("mouseleave",function(){
				if (self.isPlayAnimate) return;
		
				$(this).stop();
				$("#accounts_all_info_content_widget_into").stop();
				$(this).find("img").stop();
		
				var topScroll = $("#accounts_all_info_content_widget_into").attr("scrollTop");
				$("#accounts_all_info_content_widget_into").animate({scrollTop:  topScroll - self.tempDeltaScroll}, self.options.SHOW_DELAY_DETAIL);
				$(this).animate({height: self.options.MIN_SIZE_DETAIL}, self.options.SHOW_DELAY_DETAIL);
		
		
				$(this).find("img").animate({height: "24px", width: "24px"}, self.options.SHOW_DELAY_DETAIL);
		
				$(this).removeClass('account_info_detail_widget_white');
		
				$("#urlshow").hide();
				}
		    );
		
			$(".account_info_detail_widget").bind("mouseenter",function(){
				if (self.isPlayAnimate) return;
		
				var id = this.id.substring(15, this.id.length);
				var url = self.getInfoById(self.options.accounts, id, "url");
				$("#urlshow").html(url);
				$("#urlshow").show();
		
				self.tempDeltaScroll = 0;
		
				$(this).stop();
				$("#accounts_all_info_content_widget_into").stop();
				$(this).find("img").stop();
				
				var allEl = $(".account_info_detail_widget:visible");
				var size = allEl.size();
				var endId = $(allEl[size - 1]).attr("id");
				if (this.id == endId){
					var topScroll = $("#accounts_all_info_content_widget_into").attr("scrollTop");
					self.tempDeltaScroll = 30;
					$("#accounts_all_info_content_widget_into").animate({scrollTop:  topScroll + self.tempDeltaScroll}, self.options.SHOW_DELAY_DETAIL);
				}
		
				$(this).animate({height: self.options.MAX_SIZE_DETAIL}, self.options.SHOW_DELAY_DETAIL);
		
				$(this).find("img").animate({height: "40px", width: "40px"}, self.options.SHOW_DELAY_DETAIL);
		
				$(this).addClass('account_info_detail_widget_white');
		
			});
			self.loadTwitterFoto(self);
			self.updateAccountsVisible();
		},

		loadTwitterFoto: function(self){
			if (this.accountImgArr.length > 0){
				var item = this.accountImgArr.shift();
				var accountUrl = item.url;
				var accountIds = accountUrl.split("/");
				var len = accountIds.length - 1;
				var accountId = "";
				for (var i = len; i >= 0; i--){
					if (accountIds[i] != ""){
						accountId = accountIds[i];
						break;
					}
				}
				
				var jsonApiBegin = "http://twitter.com/users/show/";
				var jsonApiEnd = ".json";
				var url = jsonApiBegin + accountId + jsonApiEnd;

				$.ajax({
					url: url,
					dataType : "jsonp",
					success: function (data, textStatus) {
						$("#account_widget_" + item.id).find(".imgdiv").find("img").attr("src", data.profile_image_url);
						window.setTimeout(function(){self.loadTwitterFoto(self);}, 200);
					}
				});
			}
		},

		toogleWidget: function(self){
			if (self.isPlayAnimate) return;
			self.isPlayAnimate = true;
		
			$("#accounts_all_info_content_widget_into").stop();
		
			if (self.isShowSmallWidget){
				self.buildAccountWidget();
		
				$("#accounts_all_info_content_widget_into").animate({height: "280px"}, self.options.SHOW_DELAY);
				$("#accounts_all_info_content_widget_into_c").animate({height: "280px"}, self.options.SHOW_DELAY, function () {
					self.isPlayAnimate = false;
					$("#sliderup").show();
					$("#sliderdown").show();
					$("#slider").show();
					$("#slider").find("a").show();
					self.updateScrollBtn();
				});
			}
			else {
				$("#sliderup").hide();
				$("#sliderdown").hide();
				$("#slider").hide();
				$("#slider").find("a").hide();
		
				$("#accounts_all_info_content_widget_into").animate({height: "1px"}, self.options.SHOW_DELAY);
				$("#accounts_all_info_content_widget_into_c").animate({height: "0px"}, self.options.SHOW_DELAY, function () {
					self.isPlayAnimate = false;
					$("#accounts_all_info_content_widget_into_c").hide();
				});
			}
			self.isShowSmallWidget = !self.isShowSmallWidget;
			$("#opendiv").toggleClass("opendivdown");
		},

		initScrollBtn: function(){
		
			$("#sliderup").click(function(){
				this.scrollDelta(-90);
			});
		
			$("#sliderdown").click(function(){
				this.scrollDelta(90);
			});
		
			this.updateScrollBtn();
		},

		scrollDelta: function(delta){
			var maxScroll = $("#accounts_all_info_content_widget_into").attr("scrollHeight") - $("#accounts_all_info_content_widget_into").height();
			var topScroll = $("#accounts_all_info_content_widget_into").attr("scrollTop");
			if (delta > 0){
				if (topScroll < maxScroll){
					var p = topScroll + 90;
					$("#accounts_all_info_content_widget_into").attr("scrollTop", p);
					this.updateScrollSlider();
				}
			}
			else {
				if (topScroll != 0){
					var p = topScroll - 90;
					$("#accounts_all_info_content_widget_into").attr("scrollTop", p);
					this.updateScrollSlider();
				}
			}
		},

		updateScrollSlider: function (){
			var maxScroll = $("#accounts_all_info_content_widget_into").attr("scrollHeight") - $("#accounts_all_info_content_widget_into").height();
			var topScroll = $("#accounts_all_info_content_widget_into").attr("scrollTop");
			var p = (1 - topScroll / maxScroll) * 100;
			$("#slider").slider( 'value' , p );
			this.updateScrollBtn();
		},

		updateScrollBtn: function (){
			$("#slider").slider( 'enable');
			$(".ui-slider-handle").show();
			
			var maxScroll = $("#accounts_all_info_content_widget_into").attr("scrollHeight") - $("#accounts_all_info_content_widget_into").height();
			var topScroll = $("#accounts_all_info_content_widget_into").attr("scrollTop");
			$("#sliderup").removeClass("slideren");
			$("#sliderdown").removeClass("slideren");
			if (topScroll == 0){
				$("#sliderup").addClass("slideren");
			}
			if (maxScroll == topScroll){
				$("#sliderdown").addClass("slideren");
			}
			
			if (maxScroll <= 0){
				$("#slider").slider( 'disable');
				$(".ui-slider-handle").hide();
			}
		}
    });
    
    $sf.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @name defaults
         * @descr Gets/Sets the global default configuration properties.
         * @type Hash
         * @param Hash d A set of key/value pairs to set as configuration properties.
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        }       
    });
})(jQuery);