﻿$(document).ready(function() {
	homeManager.init();
	
	feedManager.start();
});

function HomeManager(params) 
{
	
}

HomeManager.prototype = {
	init: function() {
		$("#loginMenu li").click(function() {
			$(this).addClass("active").siblings().removeClass("active");
			$("." + this.id).fadeIn(300).siblings().not("#loginMenu").fadeOut(300);
			
			var signUpManager = jQuery.data($('#sideBar #signUpBlock').get(0), 'manager');
			var signInManager = jQuery.data($('#sideBar #signInBlock').get(0), 'manager');
			
			signUpManager.clearErrors();
			signInManager.clearErrors();
		});

		$("#sideBar h4").toggle(function() {
			$(this).addClass("closed").siblings("div").slideUp(300);
		}, function() {
			$(this).removeClass("closed").siblings("div").slideDown(300);
		});
		
		$('#socialSelect li').click(function(e) {
			var target = e.target;
			
			$('#socialSelect li').removeClass('active');
				
			$(target).addClass('active');
			
			feedManager.destroy();
			
			if (target.id == 'twitter') {
				feedManager = new TwitterFeed();
			}
			else 
			if (target.id == 'faceBook') {
				feedManager = new FacebookFeed();
			}
			
			feedManager.start();
		});
		
		$('.seeAllTestimonials').click(function() {
			var dialog = new PixDialog('#testimonialsPopup', { title: 'All Testimonials', autoOpen: false, dialogClass: 'JOBPopup', width: 560, height: 507 });

			$('#testimonialsPopup ul').css('padding', '0px');
			//$('#testimonialsPopup .testimonialsInnerContainer').css('height', '500px');	
			$('#testimonialsPopup .testimonialsInnerContainer').css('overflow', 'auto');	
			
			dialog.onHiding = function() { dialog.destroy(); };

			dialog.show();
		});
		
		$('.serviceApi a').click(function() {
			contactUsPopup.show();
		});

		var noOfAnim = 0,
			isRunning = false,
			animSpeed = 2700,
			intervalSpeed = 12000,
			isInFullView = false,
			isAnimating = false,
			giveMeHeight,
			doAnimate;

		var testimonialsBelt = {
			parentElment: $("#testimonialsContainer ul"),
			childrenElem: $("#testimonialsContainer ul li"),
			childrenElemLength: $("#testimonialsContainer ul li").length,
			getCurItemHeight: function(curitemAnim) {
				giveMeHeight = $("#testimonialsContainer ul li").eq(curitemAnim).height();
				return giveMeHeight;
			},
			animate: function() {
				var animAmmount = testimonialsBelt.getCurItemHeight(noOfAnim) + 60;
				testimonialsBelt.parentElment.animate({ top: "-=" + animAmmount + "px" }, animSpeed);
				noOfAnim++;
				isRunning = true;
				testimonialsBelt.updateBelt();
			},
			updateBelt: function() {
				var updatedList = $("#testimonialsContainer ul li");
				var cloneCurnt = updatedList.eq(noOfAnim).clone();
				testimonialsBelt.parentElment.append(cloneCurnt);
				if (noOfAnim > (testimonialsBelt.childrenElem.length + 20)) {
					testimonialsBelt.resetBelt();
				}
			},
			resetBelt: function() {
				clearInterval(doAnimate);
				noOfAnim = 0;
				isRunning = false;
				$("#testimonialsContainer ul li")
						.eq(testimonialsBelt.childrenElemLength)
						.nextAll()
						.remove();
				if (!isInFullView) {
					testimonialsBelt.parentElment.animate({ top: "0" }, 500);
					doAnimate = setInterval(testimonialsBelt.animate, intervalSpeed)
				}
			}
		};

		// this section is updated see the wraped in a if() was needed for the new expanding testimonals
		testimonialsBelt.parentElment.hover(
		   function() {
		   	if (!isInFullView) {
		   		isRunning = false;
		   		clearInterval(doAnimate);
		   		$(this).stop();
		   	}
		   },
		   function() {
		   	if (!isInFullView) {
		   		doAnimate = setInterval(testimonialsBelt.animate, intervalSpeed);
		   		isRunning = true;
		   	}
		   });

		//init the belt	
		doAnimate = setInterval(testimonialsBelt.animate, intervalSpeed);

		$("#joinCTA").click(function(){
			$("<div/>").addClass("mainOverlay").prependTo("body");
			$("#signUpContainer").click();
			$("#signInUpContainer").css({zIndex:100});
			scrollTopVal = $("#signInUpContainer").offset().top - 100;
			
			$('html, body').animate({scrollTop:scrollTopVal},500);
			$(".mainOverlay").live("click", function() {
			$(this).fadeOut(300, function(){
								$(this).remove()
								$("#signInContainer").click()
							});
			});
			
			$(document).one("keydown", function(e) {
				var pressed = null;
				pressed = (e.keyCode ? e.keyCode : e.which);
	    
				if (pressed == 27) {
					$(".mainOverlay").click(); 
				}
			});
			
			return false;
		});
	}
};

/******************************Feeds*************************************/
var FeedBase = Class.extend
({
	init: function(params) {
	},
	
	start: function() {
	},
	
	destroy: function() {
	}
});

var TwitterFeed = FeedBase.extend({
	fileref: null,
	
	init: function(params) {
	},
	
	start: function() {
		this.fileref = document.createElement('script');
	
		this.fileref.setAttribute("type","text/javascript");
		this.fileref.setAttribute("src", "http://search.twitter.com/search.json?q=adoramapix&callback=TweetTick&rpp=50");
	
		document.getElementsByTagName("head")[0].appendChild(this.fileref);
		
		$('#faceBookFeedContainer').jScrollPaneRemove();
		$('#faceBookTitle').hide();
		$('#faceBookFeedContainer').hide();
		
		$('#twitterTitle').show();
		$('#twitterFeedContainer').show();
	},
	
	read: function(ob) {
		var container = $('#twitterFeedContainer');
		container.html('');
		
		var feed = this;
		
		$(ob.results).each(function(el){
			var str = '<li class="tweet"><span class="txt">' + feed.formatString(this.text) + '</span></li>';
			container.append(str);
		});
		
		container.jScrollPane();
	},
	
	formatString: function(str){
		str=' '+str;
		str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
		str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1@<a href="http://twitter.com/$2" target="_blank">$2</a>');
		str = str.replace(/([^\w])\#([\w\-]+)/gm,'$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>');
		return str;
	},
	
	destroy: function() {
		if (this.fileref != null) {
			$(this.fileref).remove();
		}
	}
});

var FacebookFeed = FeedBase.extend({
	init: function(params) {
	},
	
	read: function() {
		var api_key = '60fd0aadd86141ef35d967f98ce84e77';
		var channel_path = 'xd_receiver.htm'; 
		
		//FB_RequireFeatures(["Connect"], function() { FB.init(api_key, channel_path); FB.Connect.requireSession(); }); 
		
		var container = $('#faceBookFeedContainer');
		container.html('');
		
		var feed = this;
		
		FB_RequireFeatures(["Api"], function() { 
            FB.Facebook.appSecret = 'cf0f50b6f05df76627c6c1c30aeb2ca7';
			FB.Facebook.init(api_key, channel_path);
			
			FB.Facebook.apiClient.set_session({session_key:'1350a68292f5f5bac24ca556-100000470774912', user_id:100000470774912});
			
			FB.Facebook.get_sessionWaitable().waitUntilReady(function() {
				FB.Facebook.apiClient.stream_get(7936578506, null, null, 20, null, function(result, exception) {
					if (exception != null) {
						alert(exception);
						return;
					}
					
					$(result.posts).each(function(el){
                        var str = '<li class="tweet"><span class="txt">' + feed.formatString(this.message) + '</span></li>';
                        
                        container.append(str);
                    });
                    
                    if (container.css('display') == 'block') {
						container.jScrollPane({dragMaxHeight: 12});
                    }
				});
			});
		}); 
	},
	
	start: function() {
		this.read();
		
		$('#twitterFeedContainer').jScrollPaneRemove();
		$('#twitterTitle').hide();
		$('#twitterFeedContainer').hide();
		
		$('#faceBookTitle').show();
		$('#faceBookFeedContainer').show();
	},
	
	formatString: function(str){
		str= ' ' + str;
		str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,'<a href="$1" target="_blank">$1</a>');
		
		return str;
	},
	
	destroy: function() {
		if (this.fileref != null) {
			$(this.fileref).remove();
		}
	}
});

function TweetTick(ob)
{
	feedManager.read(ob);
}

var feedManager = new TwitterFeed();