$(document).ready(function() {
	$(".joinLink").fancybox({
		'titlePosition'		: 'inside',
		'transitionIn'		: 'none',
		'transitionOut'		: 'none'
	});
	$(".joinLink").click(function() {
		$("#step1").show();
		$("#step2").hide();
		$("#step3").hide();
		$("#step4").hide();
		$("#forgotPasswordForm").hide();
		$("#emailNotFound").hide();
		$("#emailSent").hide();
		$("#loginForm").show();
		$("#usernameExistDiv").hide();
		$("#emailExistDiv").hide();
		$.fancybox.test();
	});
	
	$(".signUpLink").fancybox({
		'titlePosition'		: 'inside',
		'transitionIn'		: 'none',
		'transitionOut'		: 'none'
	});
	$(".signUpLink").click(function() {
		$('#step1').hide();
		$('#titleSignUpGigya').hide();
		$('#textSignUpGigya').hide();
		$('#imageColumn').hide();
		$('#titleSignUp').show();
		$('#textSignUp').show();
		$('#step2').show();
		$.fancybox.test();
	});
	
	$(".signInGigya").click(function() {
		$("#step1").show();
		$("#step2").hide();
		$("#step3").hide();
		$("#step4").hide();
		$("#forgotPasswordForm").hide();
		$("#emailNotFound").hide();
		$("#emailSent").hide();
		$("#loginForm").show();
		$("#usernameExistDiv").hide();
		$("#emailExistDiv").hide();
		$.fancybox.test();
	});
});

	var conf =  
        {  
        	APIKey: '2_H2BfsMySosJdUa6rIIvquyK9Yo40XTXwBKtqGJWhN7bq7N0whvZ0Cl_tOjUE71bE' //Dev & Live - Oil
           	//APIKey: '2_Y82PzwJ_chSFImHXaIDJClnLyJzmk-VFOavSsaNTzl6m901s_NNxRAS0xJ3bd3_N' //Local
		,enabledProviders: 'facebook,twitter,yahoo,google,linkedin'
        }; 
        
    var myPhotos = new Array();
    var friends, emails, dimension;
    var myProvider = '';
    
    var firstName = $("#firstName"),
		lastName = $("#lastName"),
		jobTitle = $("#jobTitle"),
		email= $("#email"),
		company = $("#company"),
		country = $("#country"),
		username = $("#username"),
		password1 = $("#password1"),
		password2 = $("#password2"),
		allFields = $([]).add(firstName).add(lastName).add(jobTitle).add(email).add(company).add(country).add(username).add(password1).add(password2),
			tips = $(".validateTips");
    
	$(function() {
		gigya.services.socialize.getUserInfo(conf, { callback: renderUI });  
		gigya.services.socialize.addEventHandlers(conf, { onLogin: renderUI, onLogout: renderUI });  
	

        
        gigya.services.socialize.showLoginUI(conf, {   
			useHTML: true
            ,showTermsLink: false
            ,height: 45
            ,width: 170
            ,containerID: 'divConnect'
            ,hideGigyaLink: true
        }); 
        
	});
	
	function renderUI(res){
		//console.log(res);
		if(res.user != null && res.user.isConnected){
			if($("#step1").css('display') == 'block'){
				$("#step1").hide();
			}
			
			if($("#step2").css('display') != 'block'){
				$("#step2").show();
				$.fancybox.test();
			}
			
			if($("#step3").css('display') == 'block'){
				$("#step3").hide();
			}
			
			myProvider = res.user.providers;
			
			if (res.user.providers == 'linkedin') {
				var rd_params = {  
					provider: 'linkedin',  
					fields : 'positions',  
					UID: res.user.UID,  
					callback:getExtraInformationLinkedin
				};
				gigya.services.socialize.getRawData(conf,rd_params);
				
			} else if (res.user.providers == 'facebook') {
				var rd_params = {  
					provider: 'facebook',  
					fields : 'current_location',  
					UID: res.user.UID,  
					callback:getExtraInformationFacebook
				};
				gigya.services.socialize.getRawData(conf,rd_params);
				$("#changeBtn").show();
			}
			
			getAccountInformation(res.user);
		}
	}
	
	function getAccountInformation(user){
		$("#firstName").val(user.firstName);
		$("#lastName").val(user.lastName);
		$("#email").val(user.email);
		$("#country").val(user.country);
		$("#username").val(user.email);
		$("#thumbnail").attr('src',user.photoURL);
		$("#source").val("gigya - " + user.providers);
		$("#UID").val(user.UID);
	}
	function getExtraInformationLinkedin(position){
		//console.log(position);
		var myXML = $(position.data);
		myXML.find('position').each(function () {
		    if ($(this).find('is-current').text() == 'true' ) {
		    	$("#company").val($(this).find('name').text());
		    	$("#jobTitle").val($(this).find('title').text());
		    }
		});
	}
	function getExtraInformationFacebook(location){
		//console.log(location.data);
		var myLocation = JSON.parse(location.data);		
		$("#country").val(myLocation[0].current_location.country);
	}
	
	function differentImages(){
		$("#wait1").show();  
		$("#additionalImagesContainer").html('');
		gigya.services.socialize.getAlbums(conf, { callback: differentImages_callback }); 
		$("#joinForm").fadeOut(function(){$("#additionalImages").fadeIn()});
	}

	function differentImages_callback(res){
		if (res.errorCode == 0) {  
              var myAlbums = res['albums'].asArray();     
                    
              if ( null!=myAlbums && myAlbums.length>0) {  
              	for (var j = 0; j < myAlbums.length; j++) {  
              		getPhotos(myAlbums[j]['albumID']);  
              	}
              } else {  
                  alert('No albums were returned');  
              }
          } else {  
              alert('Error :' + res.errorMessage);  
          }  
	}
	
	function getPhotos(albumID) {  
    	dimension = 0;
        gigya.services.socialize.getPhotos(conf, { callback:getPhotos_callback, albumIDs:albumID });  
    }  

    // Use the reponse of getPhotos and render HTML to display the first five Photos.  
    function getPhotos_callback(response) {  
    	var count = 0;
     		
        if (response.status == 'OK') {  
             myPhotos[dimension] = response.photos.asArray();  
             

             var html = "<table cellpadding=5><tr>";  
             for (var i = 0; i < myPhotos[dimension].length; i++) {  
                 html += "<td align=center valign='bottom'>";  
                 if (myPhotos[dimension][i].thumbnailURL)  
                     html += "<a href='javascript:selectImage(" + i + "," + dimension + ")'><img width='100' id='photos' src='" + myPhotos[dimension][i].photoURL + "' ></a><br>";  
                 html +="</td>";
                 
                 count++;
                 
                 if(count == 3){
                 	html += "</tr><tr>";
                 	count = 0;
                 }  
             }  
             html += "</tr></table>";  
             document.getElementById('additionalImagesContainer').innerHTML += html;  
             $("#wait1").hide();  
             dimension++;
         }  
     }   
     
     function selectImage(photoPos,dim){
     	$("#thumbnail").attr('src',myPhotos[dim][photoPos].photoURL);
     	$("#thumbnail").attr('style','margin-right:10px;');
     	$("#additionalImages").fadeOut(function(){$("#joinForm").fadeIn()});
     }
     
     function cancelAdditionalImages(){
     	$("#additionalImages").fadeOut(function(){$("#joinForm").fadeIn()});
     }
     
     function createAccount(){
     	//do ajax stuff
		var fullValid = true;
     	var allFields = $([]).add($("#firstName")).add($("#lastName")).add($("#jobTitle")).add($("#email")).add($("#company")).add($("#country")).add($("#username")).add($("#password1")).add($("#password2"));
		allFields.removeClass('ui-state-error');
		clearTips();
		
		aValid = checkLength($("#firstName"),"firstName",3,80);
		bValid = checkLength($("#lastName"),"lastName",3,80);
		cValid = checkLength($("#jobTitle"),"jobTitle",3,80);
		dValid = checkLength($("#email"),"email",6,80);
		eValid = checkLength($("#company"),"company",3,80);
		fValid = checkLength($("#country"),"country",3,80);
		gValid = checkLength($("#username"),"username",3,80);
		hValid = checkLength($("#password1"),"password1",3,80);
		iValid = checkRegexp($("#email"),/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
		jValid = checkEquality($("#password1"),$("#password2"));
		
		if(
			!aValid || 
			!bValid || 
			!cValid || 
			!dValid || 
			!eValid || 
			!fValid || 
			!gValid || 
			!hValid || 
			!iValid ||
			!jValid
		){
			fullValid = false;
			$("#loadingIcon").hide();
			$("#submitBtn").show();
			$("#usernameExistDiv").hide();
			$("#emailExistDiv").hide();
		}
		
		if (fullValid) {
			$.ajax({
				type: "post",
				url: "org/services/loginServices.cfc",
				data: {
					method: "CheckLoginEmail",
					Email: $("#email").val()
				},
				dataType: "html",
				// AJAX response handler.
				success: function( objResponse ){
					//console.log("emailExist Response:" + objResponse);
					if (objResponse == 1) {
						//alert("Email already on database");
						$("#emailExistDiv").show();
						$("#loadingIcon").hide();
						$("#submitBtn").show();
					} else {
						$("#emailExistDiv").hide();
						
						$.ajax({
							type: "post",
							url: "org/services/loginServices.cfc",
							data: {
								method: "CheckLoginUsername",
								Username: $("#username").val()
							},
							dataType: "html",
							// AJAX response handler.
							success: function( objResponse ){
								//console.log("usernameExist Response:" + objResponse);
								if (objResponse == 1) {
									//alert("Username already on database");
									$("#usernameExistDiv").show();
									$("#loadingIcon").hide();
									$("#submitBtn").show();
								} else {
									$("#usernameExistDiv").hide();
									
									$.ajax({
										type: "post",
										url: "/joinpostpage.cfm",
										data: {
											FName: $("#firstName").val(),
											LName: $("#lastName").val(),
											JobTitle: $("#jobTitle").val(),
											email: $("#email").val(),
											Company: $("#company").val(),
											Country: $("#country").val(),
											username: $("#username").val(),
											password: $("#password1").val(),
											confirmPassword: $("#password2").val(),
											Action: "Signup",
											GigyaSignUp: 1,
											MemberTypeID: 1,
											ListCode:$("#ListCode").val(),
											SkySourceCode: "A.B02M1",
											FormName: "Silo Site Membership",
											OwnerOfficeCode: "1-1LLX",
											zipcode:"",
											Employees:"",
											Industry:"",
											Major:"",
											Phone:"",
											Source:$("#source").val(),
											referrer:$("#referrer").val(),
											mac:$("#MacCode").val(),
											gigyaUID:$("#UID").val()
											},
										dataType: "html",
										// AJAX response handler.
										success: function( objResponse ){
											//alert(objResponse);
											$.ajax({
												type: "post",
												url: "org/services/sessionServices.cfc",
												data: {
													method: "getMemberID"
												},
												dataType: "html",
												// AJAX response handler.
												success: function( objResponse ){
													//console.log(objResponse);
													var objSplit = objResponse.split("|");
													
													var memberID = objSplit[0];
													var gigyaUID = objSplit[objSplit.length - 1];
													
													createAccount_controller(memberID, gigyaUID);
												},
												error: function( objResponse ){
													//console.log(objResponse);
													//alert("error: getMemberID");
												}	
											});
										},
										error: function( objResponse ){
											//alert("error");
										}	
									});
								}
							},
							error: function( objResponse ){
								//console.log(objResponse);
								//alert("error: CheckLoginEmail");
							}	
						});
						
					}
				},
				error: function( objResponse ){
					//console.log(objResponse);
					//alert("error: CheckLoginEmail");
				}	
			});
		}
  	
     }
     
     function createAccount_controller(MemberID, GigyaUID){
    	if($("#step1").css('display') == 'block'){
			$("#step1").hide();
		}
		
		if($("#step2").css('display') == 'block'){
			$("#step2").hide();
		}
		
		$.ajax({
			type: "post",
			url: "org/utilities/Utilities.cfc",
			data: {
				method: "getGigyaSignature",
				UID: GigyaUID
			},
			dataType: "html",
			success: function(objResponse){
				//alert(objResponse);
				var dateStr = Math.round(new Date().getTime() / 1000.0);
				
				var nr_params = {
					siteUID: MemberID,
					timestamp: dateStr,
					//callback:printResponse,
					PendingRegistration: 'true'
				}
				gigya.services.socialize.notifyRegistration(conf, nr_params);
			},
			error: function(objResponse){
			//alert("error: getGigyaSignature");
			}
		});
		
		if ((myProvider == 'twitter') || (myProvider == 'linkedin')) {
		
			if ($("#step3").css('display') != 'block') {
				$("#step3").show();
			}

			var fs_params = {
				useHTML: 'true',
				showEditLink: 'false',
				height: 360,
				width: 400,
				containerID: 'friendsContainer',
				showCaption: 'true',
				onSelectionDone: inviteFriends,
				onClose: inviteFriends_cancel,
				UIConfig: '<config><body><captions background-color="#FFFFFF" color="#00243a"></captions><texts color="#00243a"><links color="#00243a"></links></texts><controls><scrollingarrow color="#00243a"></scrollingarrow></controls><background background-color="#FFFFFF" frame-color="#FFFFFF"></background></body></config>'
			}
			
			gigya.services.socialize.showFriendSelectorUI(conf, fs_params); 
			
		} else {
			
			if ($("#step3").css('display') != 'none') {
				$("#step3").hide();
			}
			if ($("#step4").css('display') != 'block') {
				$("#step4").show();
			}
		}
     }

     function compareNames(a, b) {
		var nameA = a.lastName.toLowerCase( );
		var nameB = b.lastName.toLowerCase( );
		if (nameA < nameB) {return -1}
		if (nameA > nameB) {return 1}
		return 0;
	}
	
	function inviteFriends(res){
		//console.log(res);
		
		var params = {  
		    recipients: res.UIDs,   
		    body: 'I created an Oil & Gas IQ profile where I can network with colleagues and access resources such as podcasts, video, presentations and articles as well as events such as webinars, conferences and summits. First, you need to join Oil & Gas IQ! It’s free. Once you join, you can also create your own profile and have access to all of this valuable content.',   
		    subject: 'Take a look at the informative content on Oil & Gas IQ.',   
		    callback:printResponse  
		};  
		  
		gigya.services.socialize.sendNotification(conf,params);  
		
		if($("#step1").css('display') == 'block'){
			$("#step1").hide();
		}
		
		if($("#step2").css('display') == 'block'){
			$("#step2").hide();
		}
		
		if($("#step3").css('display') == 'block'){
			$("#step3").hide();
		}
		
		if($("#step4").css('display')!= 'block'){
			$("#step4").show();
		}
	}
	
	function inviteFriends_cancel(){
		if($("#step1").css('display') == 'block'){
			$("#step1").hide();
		}
		
		if($("#step2").css('display') == 'block'){
			$("#step2").hide();
		}
		
		if($("#step3").css('display') == 'block'){
			$("#step3").hide();
		}
		
		if($("#step4").css('display')!= 'block'){
			$("#step4").show();
		}
	}

	function updateTips(t) {
		$(".validateTips")
			.html($(".validateTips").html() + '<br />' + t)
			.addClass('ui-state-highlight');
		setTimeout(function() {
			$(".validateTips").removeClass('ui-state-highlight', 1500);
		}, 500);
	}
	
	function clearTips() {
		$(".validateTips").html('');
	}
	
	function checkLength(o,n,min,max) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			updateTips("Length of " + n + " must be between "+min+" and "+max+".");
			return false;
		} else {
			return true;
		}
	}
	
	function checkEquality(o,p){
		if (o.val().length < 1 || p.val().length < 1 || o.val() != p.val()){
			p.addClass('ui-state-error');
			updateTips("Passwords do not match");
			return false;
		} else {
			return true;
		}
	}
	
	function checkRegexp(o,regexp,n) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');
			updateTips(n);
			return false;
		} else {
			return true;
		}
	}
	
	function showWelcomeForm() {
		$('#step1').show();
		$('#titleSignUpGigya').show();
		$('#textSignUpGigya').show();
		$('#imageColumn').show();
		$('#titleSignUp').hide();
		$('#textSignUp').hide();
		$('#step2').hide();
		$.fancybox.test()
	}
	
	function showSignUpForm() {
		$('#step1').hide();
		$('#titleSignUpGigya').hide();
		$('#textSignUpGigya').hide();
		$('#imageColumn').hide();
		$('#titleSignUp').show();
		$('#textSignUp').show();
		$('#step2').show();
		$.fancybox.test()
	}
	
	function gigyaLogin(){
		$.ajax({
			type: "post",
			url: "org/controller/LoginController.cfc",
			data: {
				method: "Main",
				Action: "Login",
				MemberTypeID: 1,
				UserName: $("#UsernameGigya").val(),
				Password: $("#PasswordGigya").val()
				},
			dataType: "html",
			// AJAX response handler.
			success: function( objResponse ){
				var d = new Date();
				var dateStr = Math.round((d.getTime() / 1000));
				
				if(objResponse.search("<string>1</string>") > 0) {
					$.ajax({
						type: "post",
						url: "org/services/sessionServices.cfc",
						data: {
							method: "getMemberID"
						},
						dataType: "html",
						// AJAX response handler.
						success: function( objResponse ){
							//alert(objResponse);
							var objSplit = objResponse.split("|");
							
							var memberID = objSplit[0];
							var gigyaUID = objSplit[objSplit.length - 1];		
							
							$.ajax({
								type: "post",
								url: "org/utilities/Utilities.cfc",
								data: {
									method: "getGigyaSignature",
									UID: gigyaUID
								},
								dataType: "html",
								success: function( objResponse ){
									//alert(objResponse);
									
									var nr_params= {
										siteUID:gigyaUID,
										timestamp:dateStr,
										signature:objResponse,
										callback:printResponse
									}
									gigya.services.socialize.notifyLogin(conf, nr_params);
									window.location.reload(true);
								},
								error: function( objResponse ){
									//alert("error: getGigyaSignature");
								}	
							});
						},
						error: function( objResponse ){
							//alert("error: getMemberID login");
						}	
					});
				} else {
					alert("Your Username or Password are incorrect.");
				}
			},
			error: function( objResponse ){
				//alert("error: login");
			}	
		});
	}
	
	function gigyaForgotPassword(){
		$("#emailNotFound").hide();
		$("#emailSent").hide();
		$.ajax({
			type: "post",
			url: "org/controller/LoginController.cfc",
			data: {
				method: "EmailPassword",
				Email: $("#EmailGigya").val()
				},
			dataType: "html",
			// AJAX response handler.
			success: function(objResponse){
				if (objResponse.search("<string>1</string>") > 0) {
					$("#emailSent").show();
					$("#forgotPasswordForm").hide();
				} else {
					$("#emailNotFound").show();
				}
			},
			error: function( objResponse ){
				//alert("error: sign in");
			}
		});
	}
	
	function printResponse(res){
		//console.log(res);
	}
	
	// Create and Publish User's Action
    // This method is associated with the "btnPublishAction" click
    function showShareUI(title,description,link,action,image) {

	    // Constructing a UserAction Object
	    var act = new gigya.services.socialize.UserAction();

	    // Setting the default user message 
	    // (will be presented as default text in the edit box on the Share UI)
	    act.setUserMessage("Your comment here...");

	    // Setting the title and description 
	    // (will be presented in the preview on the Share UI)
	    act.setTitle(title);
	    act.setDescription(description);

        // Setting a link back to the publishing source
	    act.setLinkBack(link);

	    // Adding Action Link
	    act.addActionLink(action,link);

	    // Adding an image (will be presented in the preview on the Share UI)
        var image = {
            src: image,
            href: link,
            type: 'image'
        }
		act.addMediaItem(image);

		// Parameters for the showShareUI method, including the UserAction object
		var params = 
		{
		    userAction: act  // The UserAction object enfolding the newsfeed data.			                                  
		    ,onError: onError  // onError method will be summoned if an error occurs. 
			,showMoreButton: false // Enable the "More" button and screen
			,showEmailButton: true // Enable the "Email" button and screen
			,useHTML: true  // Use the HTML implementation of the Plugin (rather then Flash implementation)

		};
		
		var confShare =  
        {  
        	APIKey: '2_H2BfsMySosJdUa6rIIvquyK9Yo40XTXwBKtqGJWhN7bq7N0whvZ0Cl_tOjUE71bE' //Dev & Live - Oil
           	//APIKey: '2_Y82PzwJ_chSFImHXaIDJClnLyJzmk-VFOavSsaNTzl6m901s_NNxRAS0xJ3bd3_N' //Local
			,enabledProviders: 'facebook,twitter,yahoo,linkedin,google'
        };

		// Show the "Share" dialog
		gigya.services.socialize.showShareUI(confShare, params);

	}
	
	function showCommentsUI(gstreamid) {
	    var params =
    	    {
        	categoryID: '24078735',
			containerID: 'commentsDiv',
        	streamID: gstreamid,
        	cid:'',
			onError: function err(event)
			{
				alert('An error has occured' + ': ' + event.errorCode + '; ')
				alert('An error has occured' + ': ' + event.errorMessage + '; ' )
				alert('An error has occured' + ': ' + event.errorDetails + '; ' )
			}
            }	
	    gigya.services.socialize.showCommentsUI(conf,params);
	}
	// onError event handler
	function onError(event) {
	   // alert('An error has occured' + ': ' + event.errorCode + '; ' + event.errorMessage);
	}
