(function(window){
	
	

	//Private Methods


	var CallHSApi = function(strBaseUrl, objParams, funCallBack){

		if(typeof funCallBack != 'string'){

			HSIndex.funCallBack = funCallBack;

			funCallBack = 'HSIndex.CallBack';

		}

		var strUrl = HSIndex.objSettings.SERVER_URL + "/api" + strBaseUrl + "?";

		objParams['response_type'] = 'JSON';

		objParams['json_callback'] = funCallBack;

		for(strKey in objParams){

			strUrl += "&" + strKey + "=" + objParams[strKey]; 

		}

		$("head").append($('<scr' + 'ipt type="text/javascript" src="' + strUrl + '"></scr' + 'ipt>'));

	}
	
	
	function HSLinkInput_focus(objEvent){
		if(this.value=='http://')this.value='';
	}
	
	function HSLinkInput_blur(objEvent){
		if (!(this.value.indexOf('http') >= 0)) { 
		$(this).val("http://" + $(this).val());	
		}
		
		if(this.value=='')this.value='http://';
	}
	function LnkLogin_click(objEvent){
		objEvent.preventDefault();
		FB.api('/me',LnkLogin_callback);
	}
	function LnkLogin_callback(objResponse){
		HSIndex.AuthUser(objResponse);
		
	}
	function AuthUser_callback(objResponse){
		if(objResponse.body.Success == 'true'){
			document.location = '/admin/share.php';
		}else{
			HSIndex.Alert('Login Unsuccessful');
		}
	}
	
	
	
	function lnkHelp_click(objEvent){
		var strHtml = $('#divHelpText').html();
		HSIndex.Alert(strHtml);
	}
	function divThankYou_callback(objNothing){
		document.location = HSIndex.objSettings.SERVER_URL + '/admin/share.php';
		
	}
	function RunSignUpPost_callback(response){
		//document.location = HSIndex.objSettings.SERVER_URL + '/admin/share.php';
		
		var strHtml = $('#divThankYou').html();
		HSIndex.Alert(strHtml, divThankYou_callback);
	}
	function PromptForPerms_callback(response){
		if(response.authResponse) {			
			HSIndex.response = response;			
			HSIndex.CreateUser(response);
		}else{
		    alert('There was a problem authenticating with Facebook');
		}
	}
	function HSMoreInfoBtn_click(objEvent){
		objEvent.preventDefault();
		var strHtml = $('#' + $(this).attr('more_info_ele')).html();
		HSIndex.Alert(strHtml);
	}
	function HSShareOnFacebook_click(objEvent){
		objEvent.preventDefault();
		HSIndex.PromptForPerms();
	}
	//Private Function
	function HSGetThisDealBtn_click(objEvent){
		objEvent.preventDefault();
		HSIndex.IdOffer = $(this).attr('id_offer');
		//$('.HSLinkInput').trigger('focus');
		HSIndex.SlideNext();
	}
	function HSSlideBack_click(objEvent){
		objEvent.preventDefault();
		HSIndex.IdOffer = null;
		HSIndex.SlideBack();
				
	}
	function CreateUser_callback(objResponse){
		HSIndex.IdUser = objResponse.idUser;
		var objData = {
						   method: 'feed',
						   message: '',
						   name: objResponse.body.Message_Title,
						   caption: objResponse.body.Message.Link,
					       description: objResponse.body.Message_Desc,
						   link: objResponse.body.Message_Url,
						   //picture: 'http://www.fbrell.com/f8.jpg',
						   actions: [
						        { name: 'HypeSpark', link: 'http://www.hypespark.com/' }
						   ],
						   user_message_prompt: 'Share your link with your friends'
				  };
		HSIndex.RunSignUpPost(objData);
	}
	function HSLinkInput_keypress(objEvent) {
	    if(objEvent.keyCode == 13) {
	    	HSShareOnFacebook_click(objEvent);
	    }
	}
	function lnkNav1_click(objEvent){
		objEvent.preventDefault();
		$('html,body').animate({scrollTop: $('.gradientbg').offset().top}, 1000); 
		if(HSIndex.IdOffer != null){
			HSSlideBack_click(objEvent);
		}
	}
	
	var objPublic = {
		objSettings:null,
		IdOffer:null,
		funCallBack:function(objData){},
		Init:function(objSettings){
			
			HSIndex.objSettings = objSettings;
			HSIndex.SetUpFacebook();
			HSIndex.SetUpSlider();
			
			//Events
			var jSlideBack = $('.HSSlideBack');
			jSlideBack.live('click', HSSlideBack_click);
			
			$('.LnkLogin').live('click', LnkLogin_click);
			$('.HSGetThisDealBtn').live('click', HSGetThisDealBtn_click);
			$('.HSMoreInfoBtn').live('click', HSMoreInfoBtn_click);
			$('.HSShareOnFacebook').live('click', HSShareOnFacebook_click);
			$('.HSLinkInput').keypress(HSLinkInput_keypress);
			$('#lnkHelp').live('click', lnkHelp_click);
			$('#lnkNav1').live('click', lnkNav1_click);
			$('.HSLinkInput').live('blur', HSLinkInput_blur);
			$('.HSLinkInput').live('focus', HSLinkInput_focus);
			
			
			
		},
		
		SetUpFacebook:function(){
			 FB.init({
			      appId      : HSIndex.objSettings['FB_APP_ID'], // App ID
			      channelURL : HSIndex.objSettings['SERVER_URL']  + '/channel.html', // Channel File
			      status     : true, // check login status
			      cookie     : true, // enable cookies to allow the server to access the session
			      oauth      : true, // enable OAuth 2.0
			      xfbml      : true  // parse XFBML
			  });
		},
		RunSignUpPost:function(objData){
			FB.ui(
					objData,
					RunSignUpPost_callback
			 );
		},
		PromptForPerms:function(funCallback){
			FB.login(PromptForPerms_callback,
				 {scope: 'email,publish_stream,offline_access'}
			);
			
		},
		CreateUser:function(response){			
			var strBaseUrl =  '/action/createUser';
			var objData = {
					FBUID:response.authResponse.userID,
					ACCESS_TOKEN:response.authResponse.accessToken,
					SCRAPE_URL:escape($('.HSLinkInput').val()),
					ID_OFFER: HSIndex.IdOffer
			};
			CallHSApi(strBaseUrl, objData, CreateUser_callback);

		},
		AuthUser:function(objResponse){	
			console.log(objResponse)
			if(objResponse && (typeof objResponse.id !='undefined')){
				var strBaseUrl =  '/action/authUser';
				var objData = {
						FBUID:objResponse.id
				};
				CallHSApi(strBaseUrl, objData, AuthUser_callback);
				
			}else{
				HSIndex.Alert('<div style="text-align:center;"><h3>You must first log in to Facebook</h3><p>You must first be logged in to Facebook to access your account.</p><p><a href="http://www.facebook.com/" class="button">Login to Facebook</a></div> ');
			}

		},
		SetUpSlider:function(){
	
	
			
	
			$('.flexslider').flexslider({
	
					animation: "slide",              //String: Select your animation type, "fade" or "slide"
	
					slideDirection: "horizontal",   //String: Select the sliding direction, "horizontal" or "vertical"
	
					slideshow: false,                //Boolean: Animate slider automatically
	
					slideshowSpeed: 3000,           //Integer: Set the speed of the slideshow cycling, in milliseconds
	
					animationDuration: 1000,         //Integer: Set the speed of animations, in milliseconds
	
					directionNav: false,             //Boolean: Create navigation for previous/next navigation? (true/false)
	
					controlNav: false,               //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
	
					keyboardNav: false,              //Boolean: Allow slider navigating via keyboard left/right keys
	
					mousewheel: false,              //Boolean: Allow slider navigating via mousewheel
	
					prevText: "Previous",           //String: Set the text for the "previous" directionNav item
	
					nextText: "Next",               //String: Set the text for the "next" directionNav item
	
					pausePlay: false,               //Boolean: Create pause/play dynamic element
	
					pauseText: 'Pause',             //String: Set the text for the "pause" pausePlay item
	
					playText: 'Play',               //String: Set the text for the "play" pausePlay item
	
					randomize: false,               //Boolean: Randomize slide order
	
					slideToStart: 0,                //Integer: The slide that the slider should start on. Array notation (0 = first slide)
	
					animationLoop: false,            //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
	
					pauseOnAction: true,            //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
	
					pauseOnHover: true,            //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
	
					controlsContainer: "",          //Selector: Declare which container the navigation elements should be appended too. Default container is the flexSlider element. Example use would be ".flexslider-container", "#container", etc. If the given element is not found, the default action will be taken.
	
					manualControls: "",             //Selector: Declare custom control navigation. Example would be ".flex-control-nav li" or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
	
					start: function(slider) {
						HSIndex.Slider = slider;
	
						//$('html,body').animate({scrollTop: $('.gradientbg').offset().top}, 1000); 
	
																						
	
	
					},           //Callback: function(slider) - Fires when the slider loads the first slide
	
					before: function(){},           //Callback: function(slider) - Fires asynchronously with each slider animation
	
					after: function(slider){
	
								
	
								/************************************************
	
								
	
								Matt, can you help me size the height of the slider container for each slide? My javascript sucks ballzzzzz.
	
								
	
								var $ht = $(slider.currentSlide).height();
	
								$(this).parent().parent().animate({height: $ht});
	
								
	
								*************************************************/
	
						HSIndex.funSlideAfter();
						HSIndex.funSlideAfter = function(){  };
	
					},            //Callback: function(slider) - Fires after each slider animation completes
	
					end: function(){
						//$('.HSLinkInput').trigger('focus');
					} 
				});
			
				
			},
			SlideNext:function(){
				//HSIndex.SetUpSlider();
				var objTarget = HSIndex.Slider.getTarget("next");
				HSIndex.Slider.flexAnimate(objTarget, true);
				$('html,body').animate({scrollTop: $('.gradientbg').offset().top}, 1000); 
				
				HSIndex.funSlideAfter = function(){ 	$('.HSLinkInput').trigger('focus'); };
				
			},
			SlideBack:function(){
				//Go to the prev slide
				
				HSIndex.Slider.flexAnimate(HSIndex.Slider.getTarget("prev"), true);
				
			},
			CallBack:function(objData){

				HSIndex.funCallBack(objData);

			},
			Alert:function(strHtml, funCallback){
				var objData = {
		        	'autoDimensions'	: false,
					'width'         		: 620,
					'height'        		: 'auto',
					'transitionIn'		: 'none',
					'transitionOut'		: 'none'
				};
				if(typeof funCallback != 'undefined'){
					objData.onClosed = funCallback;
				}
				
				$.fancybox(
						strHtml,
						objData
				);
			}
	}
	window.HSIndex = objPublic;		
	
	
	
})(window);

