var connectionNotify = true;
var contentFirstRun = true;
var financeFirstRun = true;
var detailAccountID = 0;
var accountActivityFirstRun = true


/* Functions
***************************/
var formSubmitGood = true;

function ckCCForm() {
	formSubmitGood = true;
	validateCardName("Name on Card");
	validateExpMonth();
	validateExpYear();
	validateCcnum("Credit Card Number");
	validateCcv("CCV Number");
	validateAddress1("Billing Address"); 
	validateCity("City");
	validateState();
	validateZip("Zip");
	
	if (formSubmitGood == false) {
		alert("Sorry there are some errors on the form");
		return false;
	} else {
		return true;
	};
	
};

function IsNumeric(input) {
   return (input - 0) == input && input.length > 0;
};

function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
	};

function errorShow(theError,doIt) {
	if (doIt) {
		$('##'+theError).css('display','');
		$('##'+theError).css('color','##FF0000');	
	} else {
		$('##'+theError).css('display','none');
	};	
};

function vaidateGiveAmmount() {
	if (IsNumeric($('##giveAmmount').val())) {
		errorShow('giveAmmountError',false);
	} else {
		errorShow('giveAmmountError',true);
		formSubmitGood = false;
	};
};

function validateEmailFormat() {
	theEmail = $('##NewEmail').val();
	if (isValidEmailAddress(theEmail)) {
		errorShow('newEmailError',false);
	} else {
		errorShow('newEmailError',true);
		formSubmitGood = false;
	};
};

function validateEmailMatch() {
	email1 = jQuery.trim($('##NewEmail').val());
	email2 = jQuery.trim($('##matchEmail').val());
	if (email1 == email2) {
		errorShow('matchEmailError',false);
	} else {
		errorShow('matchEmailError',true);
		formSubmitGood = false;
	};
};

function validateCardName(defaultValue) {
	if ($('##ccname').val() != defaultValue) {
		errorShow('ccnameError',false);
	} else {
		errorShow('ccnameError',true);
		formSubmitGood = false;
	};
};

function validateExpMonth() {
	if ($('##expMonth').val() != 0) {
		errorShow('expMonthError',false);
	} else {
		errorShow('expMonthError',true);
		formSubmitGood = false;
	};
};


function validateExpYear() {
	if ($('##expYear').val() != 0) {
		errorShow('expYearError',false);
	} else {
		errorShow('expYearError',true);
		formSubmitGood = false;
	};
};

function validateCcnum(defaultValue) {
	if ($('##ccnum').val() != defaultValue) {
		errorShow('ccnumError',false);
	} else {
		errorShow('ccnumError',true);
		formSubmitGood = false;
	};
};

function validateCcv(defaultValue) {
	if ($('##ccv').val() != defaultValue) {
		errorShow('ccvError',false);
	} else {
		errorShow('ccvError',true);
		formSubmitGood = false;
	};
};


function validateAddress1(defaultValue) {
	if ($('##address1').val() != defaultValue) {
		errorShow('address1Error',false);
	} else {
		errorShow('address1Error',true);
		formSubmitGood = false;
	};
};

function validateCity(defaultValue) {
	if ($('##city').val() != defaultValue) {
		errorShow('cityError',false);
	} else {
		errorShow('cityError',true);
		formSubmitGood = false;
	};
};

function validateState() {
	if ($('##state').val() != 0) {
		errorShow('stateError',false);
	} else {
		errorShow('stateError',true);
		formSubmitGood = false;
	};
};

function validateZip(defaultValue) {
	if ($('##zip').val() != defaultValue) {
		errorShow('zipError',false);
	} else {
		errorShow('zipError',true);
		formSubmitGood = false;
	};
};


function syncGive(y,z) {
	var formObject = document.getElementById(y);
	var formObject2 = document.getElementById(z);
	document.getElementById(z).value = formObject.value;

}
function replaceTxt(y,z) {
	var newtext = "";
	var formObject = document.getElementById(y)

	if (formObject.value == newtext) {
		formObject.value = z ;
		}
}
function clearTxt(y,z) {
	var newtext = z;

	var formObject = document.getElementById(y)

	if (formObject.value == newtext) {
		formObject.value = '';
		}
}
String.prototype.trim = function() {
a = this.replace(/^\s+/, '');
return a.replace(/\s+$/, '');
};


var socialBoxPollingID = 0;
var theBoxLen = 0;	


function charCounterUpdate() {

	alert(theObj +' ' + theDest +' ' +limitType);

	


};

function updateTwitterCounter(theBoxID,theLimit) {
						
	var theObj = "#socailShareTextArea"+theBoxID
	var theDest = "#socialShareCharCount"+theBoxID
	
						
	theNewLen = $(theObj).val().length;
	
	if (theBoxLen != theNewLen) {
		
		theBoxLen = theNewLen;
	
	if (theBoxLen > theLimit){
	
		$(theDest).css("color","#FF0000");
	
	} else {
	
		$(theDest).css("color","#000000");
	
	}
	
	$(theDest).text(theBoxLen + " / " + theLimit);	
	
	};
};	

function toggleSocialShare(type,theID) {
	
	var currentStatus = $('#socialShareForm'+theID).css('display');
	var previousAction = $('#socialShareForm'+theID).attr('actionType');
	var theLimit = 140;
	
	$('#socialShareForm'+theID).attr('actionType',type);
	
	if (type == 'twitter') {
		
		$('#socialShareButton'+theID).attr('value','Tweet It');
		var theLimit = 140;
		
	};
	
	
	if (type == 'facebook') {
		
		$('#socialShareButton'+theID).attr('value','Post to your Wall');
		var theLimit = 1000;
		
	};
	
	
	if (currentStatus == 'none') {
	
		$('#socialShareForm'+theID).show('normal')
		
		startPollingSocialBox(theID,theLimit);
	
	
	} else {
		
		if (type == 'none' || previousAction == type) {
		
			$('#socialShareForm'+theID).hide('slow')
			stopPollingSocialBox();
		
		}
	}
	
	
	
};


function startPollingSocialBox(boxID,theLimit) {
						
	socialBoxPollingID = setInterval("updateTwitterCounter("+boxID+","+theLimit+")", 200);

};

function stopPollingSocialBox() {
	
	 clearInterval(socialBoxPollingID);

};


function sendMessage(theID) {
							
							
	
	$('#socialShareForm'+theID).hide('fast');
	$('#socialProcessing'+theID).show('fast');
	
	var actionType = $('#socialShareForm'+theID).attr('actionType');
		
	if (actionType == 'twitter') {
		
		URL  = '/twitter/tweetIt?json=1';
	}
	
	if (actionType == 'facebook') {
		
		URL  = '/fb/streamPublish?json=1';
	}
	
	$.ajax({type: 'POST', url: URL, data: { msg: $('#socailShareTextArea'+theID).val() },
		success: function(data){
			
			if (data.SUCCESS) {
				
				alert(data.MESSAGE);
				
				$('#socialProcessing'+theID).hide('fast');
				
				stopPollingSocialBox();
				
	
			} else {
				
				alert(data.ERROR, "Error", "Ok");
				
				$('#socialProcessing'+theID).hide('fast');
				$('#socialShareForm'+theID).show('fast');
				
				
			};
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			
			alert("Failed to get server response - Please try again", "Error", "Ok");
			$('#socialProcessing'+theID).hide('fast');
			$('#socialShareForm'+theID).show('fast');
			
		},
		dataType: 'json'
		});
			
			
	
};

function shareVideo(theLink,theTitle, postType) {
	
	var a  = confirm("A link to this video will be posted on your " + postType + " account. Is that ok?");	
	
	if (a) {
		
		if (postType == 'twitter') {
			
			URL = '/twitter/tweetIt?json=1'
			theMsg = 'Great Video from ' + theTitle + ' check it out: ' + theLink; 
			
		};
		
		if (postType == 'facebook') {
			
			URL = '/fb/postLink?json=1'
			theMsg = 'Great video from ' + theTitle;
			
		};
		
		$.ajax({type: 'POST', url: URL, data: { msg: theMsg, theURL: theLink },
		success: function(data){
			
			if (data.SUCCESS) {
				
				alert(data.MESSAGE);
				
	
			} else {
				
				alert(data.ERROR, "Error", "Ok");
				
			};
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			
			alert("Failed to get server response - Please try again later." , "Error", "Ok");
			
		},
		dataType: 'json'
		});
			
		
		
		
		
	};
	
	
};

function annoucmentTypeSelector(s) {
	
	
	$('#eventDetails').hide();
	
	$('#contactDetails').hide();
	
	$('#annoucementText').hide();
	
	$('#generalDetails').show();
	$('#submitButton').show();
	
	
	
	if (s == 'e'){
	$('#eventDetails').show();
	};
	if (s == 'c'){
	$('#contactDetails').show();
	};
	if (s == 's'){
	$('#annoucementText').show();
	};

	
};

function toggleFeatures() {
	var stdActive = $('#standardFeatures').attr('isActive');
	var advActive = $('#advancedFeatures').attr('isActive');
	
	if (stdActive == 1){
		
		$('#standardFeatures').hide();
		$('#standardFeatures').attr('isActive',0);
		
		$('#advancedFeatures').show();
		$('#advancedFeatures').attr('isActive',1);
		
		$('#moreFeaturesBttn').html("Back To Standard Features");
		
		
	} else {
		
		$('#advancedFeatures').hide();
		$('#advancedFeatures').attr('isActive',0);
		
		$('#standardFeatures').show();
		$('#standardFeatures').attr('isActive',1);
		
		$('#moreFeaturesBttn').html("Advanced Features");
		
		
	};
	
	
}

function IsNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}


function validateDiscountCode() {
	
	var theCode = $('#discCode').val();
	
	$.ajax(
	{
		
		type: 'POST', 
		
		url: '/ajax/validateDiscountCode', 
		
		data: {discountCode: theCode},
		
		success: function(data){
			if(data.SUCCESS)
			{
				
				$('#setupFee').text(data.CODE.SETUPFEE);
				$('#hostingFee').text(data.CODE.HOSTINGFEE);
				$('#processingFee').text(data.CODE.PROCESSINGFEE);
				$('#totalNow').text(data.CODE.TOTALNOW);
				
				
				alert('Good Code, check out that price reduction... Sweet');
				  
			} else {
				
				alert(data.MSG);
				
			};
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			alert("Failed to get server response - Check your network connection", "Error", "Ok");
			$('##freshBooksAdminSelect option[value='+ oldFBID +']').attr('selected', 'selected');
		},
		dataType: 'json'
	});
		
		   
};


function updateMyOrgStats() {
	
	
	
	updateFinanceData();
	updateActivityData();
	updateContentData();
	
	
	
	
	
	
	
	
};

function updateFinanceData() {
	
	if (financeFirstRun == false){
		
		$('#financeUpdating').show();
		
	}
	
	
	$.ajax(
	{
		
		type: 'POST', 
		
		url: '/corporation/myOrgFinancialJSON', 
		
		data: {filter: $('#theFilter').val()},
		
		success: function(data){
			if(data.SUCCESS)
			{
				
				$('#campaignNum').text(data.CAMAPIGNCOUNT);
				$('#donaitionsTotal').text(data.DONATIONSUM);
				$('#donaitionsNum').text(data.DONATIONCOUNT);
				$('#donationAvg').text(data.DONATIONAVG);
				$('#depositsNet').text(data.CORPPAYMENTSSUM);
				
				$('#financeUpdating').hide();
				$('.financialDataLoadingImg').hide();
				$('.financialDataPoint').show(); 
				
				financeFirstRun = false;
			} else {
				
				
			};
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if (connectionNotify == true) {
				alert("Failed to get server response - Check your network connection", "Error", "Ok");
				connectionNotify = false;
			}
		},
		dataType: 'json'
	});	
}

function updateContentData() {
	if (contentFirstRun == false){
		
		$('#contentUpdating').show();
		
	}
	$.ajax(
	{
		
		type: 'POST', 
		
		url: '/corporation/myOrgContentJSON', 
		
		data: {filter: $('#theFilter').val()},
		
		success: function(data){
			if(data.SUCCESS)
			{
				
				$('#channelsTotal').text(data.CHANNELCOUNT);
				$('#videosTotal').text(data.VIDEOCOUNT);
				$('#blogsTotal').text(data.BLOGCOUNT);
				$('#tweetsTotal').text(data.TWEETCOUNT);
				$('#accountTotal').text(data.ACCOUNTCOUNT);
				$('#announcementTotal').text(data.ANNOUCEMENTCOUNT);
				
				$('#contentUpdating').hide();
				$('.contentDataLoadingImg').hide();
				$('.contentDataPoint').show();
				contentFirstRun = false;
				
			} else {
				
				
			};
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if (connectionNotify == true) {
				alert("Failed to get server response - Check your network connection", "Error", "Ok");
				connectionNotify = false;
			}
		},
		dataType: 'json'
	});	
}

function updateAccountActivity(id,acctID,thefilter) {
	if (accountActivityFirstRun == false){
		
		$('.activityDataPoint'+id).hide();
		$('#activityUpdating'+id).show();
		
	}
	$.ajax(
	{
		
		type: 'POST', 
		
		url: '/corporation/accountActivityJSON/'+acctID, 
		
		data: {filter: thefilter},
		
		success: function(data){
			if(data.SUCCESS)
			{
				
				$('#logins'+id).text(data.LOGIN);
				$('#tweets'+id).text(data.TWEETS);
				$('#news'+id).text(data.NEWS);
				$('#videos'+id).text(data.VIDEO);
				$('#events'+id).text(data.EVENTS);
				$('#contacts'+id).text(data.CONTACTCHANNELS);
				$('#campaigns'+id).text(data.CAMPAIGNS);
				
				
				$('.activityDataLoadingImg'+id).hide();
				$('.activityDataPoint'+id).show();
				
				accountActivityFirstRun = false;
				
			} else {
				
				
			};
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if (connectionNotify == true) {
				alert("Failed to get server response - Check your network connection", "Error", "Ok");
				connectionNotify = false;
			}
		},
		dataType: 'json'
	});	
}



function updateActivityData() {
	if (contentFirstRun == false){
		
		$('#activityUpdating').show();
		
	}
	$.ajax(
	{
		
		type: 'POST', 
		
		url: '/corporation/myOrgActivityJSON', 
		
		data: {filter: $('#theFilter').val()},
		
		success: function(data){
			if(data.SUCCESS)
			{
				
				$('#logins').text(data.LOGINS);
				$('#tweets').text(data.TWEETS);
				$('#news').text(data.NEWS);
				$('#videos').text(data.VIDEO);
				$('#events').text(data.EVENTS);
				$('#contacts').text(data.CONTACTCHANNELS);
				$('#campaigns').text(data.CAMPAIGNS);
				
				$('#activityUpdating').hide();
				$('.activityDataLoadingImg').hide();
				$('.activityDataPoint').show();
				
				activityFirstRun = false;
				
			} else {
				
				
			};
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			if (connectionNotify == true) {
				alert("Failed to get server response - Check your network connection", "Error", "Ok");
				connectionNotify = false;
			}
		},
		dataType: 'json'
	});	
}

function updateStatLinks() {
	
	var locFilter = $('#theFilter').val();
	$('#appLoginsLink').attr('href','/corporation/appLogins/' + locFilter);
	
	
	
};


function displayUploader(imageLabel,imageLink,imageKey){
	
	
	$('#theImageKey').val(imageKey);
	$('#imageUploderLabel').text(imageLabel);
	$('#uploaderImage').attr('src',imageLink);
	$('#appImageOverView').hide();
	$('#appImageUploader').show();
		
};

function cancelImageUploader(imageLabel,imageLink){
	
	$('#appImageUploader').hide();
	$('#appImageOverView').show();
	
};

function uploadAppImage() {
	
	if (!$('#newImage').val()){
		alert('You must select a file to upload');
				
	} else {
		
		uploadForm.submit();	

		
	};
		
	
	
}
