$(document).ready(function () {
    if ($("#vurl").length > 0) {
        _gaq.push(['_trackPageview', $('#vurl').val()]);
        
    }
});
String.prototype.trim = function (){return this.replace(/^\s*/, "").replace(/\s*$/, "");}
String.prototype.say = function(){return alert(this)}

function setupSessionAspDotNet(fnCallback) {

    var fnAfterPost = function (data) { if (data.resultOk) { fnCallback(); } };

    runSessionAcquisitionAjax(null, function (data) {
        if (data.token == null) {
            document.location = '/account/home/default.asp';
            return;
        }
        $.post('/app/SessionAcquisition/NoRedir', { token: data.token }, fnAfterPost);
    });
}

function goToEndUserAccountPageAspx(destUrlValue) {
    runSessionAcquisitionAjax(destUrlValue, function(data) {
        if (data.token == 'null') {
            document.location = '/account/home/default.asp';
        }
        else {
            var tempForm = document.createElement("form");
            $(tempForm).attr('method', 'post');
            $(tempForm).attr('action', '/app/SessionAcquisition');
            $(tempForm).append('<input type=\'hidden\' name=\'token\' value=\'' + data.token + '\' />"');
            $('body').append(tempForm);
            tempForm.submit();
        }
    });
}

function runSessionAcquisitionAjax( destUrlValue, successFunction ) {

    var postObj = new Object();
    if((destUrlValue == null) || (destUrlValue == ''))
        postObj.destUrlVoid = 'destUrlVoid';
    else
        postObj.destUrl = destUrlValue;
            
    var ajaxOpts =  {
        traditional: true,
        type: 'POST',
        cache: false,
        url: '/Account/SessionAcquisition.asp',
        dataType: 'json',
        error: function(xmlrq, textStatus, errorThrow) {
            document.location = '/Error.asp';
        }
    };

    ajaxOpts.success = successFunction;
    ajaxOpts.data = postObj;
    
    $.ajax(ajaxOpts);
}
    

function currentEventGivingGroupId() { return $('#_EventGivingGroupId')[0].value; }

function seeWhosDonatedPage() {
    goToEndUserAccountPageAspx('/app/Fundraiser/AddOfflineDonation/' + currentEventGivingGroupId() );
}
function addEndoMondo() {
    goToEndUserAccountPageAspx('/app/Fundraiser/AddContent/' + currentEventGivingGroupId());
}
function addOfflineDonation() {
    goToEndUserAccountPageAspx('/app/Fundraiser/AddOfflineDonation/' + currentEventGivingGroupId() + '?action=add');
}
	
	function quickJump( myElement ){
		var destination = myElement[myElement.selectedIndex].value;
		if ( destination.length > 0 ){ 
			document.location.href = myElement[myElement.selectedIndex].value;
		}
	}
	
	
	function removeDefault( myElement, myDefault ){
		if ( myElement.value == myDefault ){
			myElement.value = "";
		}
	}
	
	function addDefault( myElement, myDefault ){
		if ( myElement.value == "" ){
			myElement.value = myDefault;
		}
	}
	
	
	// Only allows numbers to be entered
	function validateKeyPress( e ) {
		if ( !e ) var e = window.event;
		if ( e.charCode ) {
			if ( e.charCode == 0 || e.charCode == 9 || e.charCode == 46 || ( e.charCode > 47 && e.charCode < 58 ) ) {
				return true;
			} else {
				if (e.preventDefault) e.preventDefault();
				e.cancelBubble = true;
				return false;
			}
		} else {
			if ( e.keyCode == 0 || e.keyCode == 9 || e.keyCode == 46 || ( e.keyCode > 47 && e.keyCode < 58 ) ) {
				return true;
			} else {
				e.returnValue = false;
				e.cancelBubble = true;
				return false;
			}
		}
	}
	
	//This function ensures that the user cannot enter multiple decimal places in the amount fields
	function validateDecimalPlaces(e, textElement){


		var textBoxValue = textElement.value
		var decimalPlace=textBoxValue.indexOf('.');

		if (decimalPlace == -1)
		{ 
			return true;
		}
		else
		{
			if ( e.charCode ) {
				if ( e.charCode != 46) {
					return true;
				}
				else 
				{
					if (e.preventDefault) e.preventDefault();
					e.cancelBubble = true;
					return false;
				}
			}
			else
			{
				if ( e.keyCode != 46 ) {
					return true;
				} 
				else 
				{
					e.returnValue = false;
					e.cancelBubble = true;
					return false;
				}
			}
		}	
	}			
	
	// Only allows numbers to be entered
	function validateAmount( e, myElement ) {
		if ( !e ) var e = window.event;
		if ( e.charCode ) {
			if ( e.charCode == 0 || e.charCode == 46 || ( e.charCode > 47 && e.charCode < 58 ) ) {
				return true;
			} else {
				if (e.preventDefault) e.preventDefault();
				e.cancelBubble = true;
				return false;
			}
		} else {
			if ( e.keyCode == 0 || e.keyCode == 46 || ( e.keyCode > 47 && e.keyCode < 58 ) ) {
				return true;
			} else {
				e.returnValue = false;
				e.cancelBubble = true;
				return false;
			}
		}
	}
	
	// Only allows numbers to be entered
	function validateWholeAmount( e, myElement ) {
		if ( !e ) var e = window.event;
		if ( e.charCode ) {
			if ( e.charCode == 0 || ( e.charCode > 47 && e.charCode < 58 ) ) {
				return true;
			} else {
				if (e.preventDefault) e.preventDefault();
				e.cancelBubble = true;
				return false;
			}
		} else {
			if ( e.keyCode == 0 || ( e.keyCode > 47 && e.keyCode < 58 ) ) {
				return true;
			} else {
				e.returnValue = false;
				e.cancelBubble = true;
				return false;
			}
		}
	}
	


	function validateWebDirectory( e ) {
	
		// 65 - 90		(A-Z)
		// 97 - 122		(a-z)
		// 48 - 57		(0-9)
		// 95			(_)
		// 45			(-)
		
		var i;
		
		if ( !e ) var e = window.event;
		
		if ( e.charCode ) {
			i = e.charCode;
			if ( i == 95 || i == 45 || ( i >= 48 && i <= 57 ) || ( i >= 65 && i <= 90 ) || ( i >= 97 && i <= 122 ) ) {
				return true;
			} else {
				if (e.preventDefault) e.preventDefault();
				e.cancelBubble = true;
				return false;
			}
		} else {
			i = e.keyCode;
			if ( i == 95 || i == 45 || ( i >= 48 && i <= 57 ) || ( i >= 65 && i <= 90 ) || ( i >= 97 && i <= 122 ) ) {
				return true;
			} else {
				e.returnValue = false;
				e.cancelBubble = true;
				return false;
			}
		}
	}
	
	
	
	
	// Removes enter character
	function validateSingleLineString( e ) {

		if ( !e ) var e = window.event;

		if ( e.charCode ) {
			if ( e.charCode == 13 ) {
				childSearch(false);
				return true;
			}
		} else {
			if ( e.keyCode == 13 ) {
				childSearch(false);
				return true;
			}
		}
	}
	
	function igRound( valueElement, vxPrecision ){
		
		var dblMultiplier, dblRemainder, dblLowerBoundary, dblValue, dblPrecision
		
		dblValue			= valueElement.value;
		dblPrecision		= vxPrecision;
		dblMultiplier		= parseInt( dblValue / dblPrecision );	// Figure out how many times the precision factor will fit into the given value
		dblLowerBoundary	= dblMultiplier * dblPrecision;		// Work out the minimum possible value (max value is by definition min + dblPrecision)
		dblRemainder		= dblValue - dblLowerBoundary;		// What's the remainder? i.e. where are we between max and min
		
		if ( ( dblRemainder * 2 ) < dblPrecision ) {			// If the remainder is less than half the precision, round down.
			//alert("rounding "+vxValue+" to "+dblLowerBoundary);
			valueElement.value = dblLowerBoundary;
		} else {
			//alert("rounding "+vxValue+" to "+ (dblLowerBoundary + dblPrecision));
			valueElement.value = dblLowerBoundary + dblPrecision;		// If the remainder is half the precision or more, round up.
		}
		
	}
	
	function addOnLoadEvent(func)
	{
		var oldonload = window.onload;
		if (typeof window.onload != 'function') 
		{
			window.onload = function(){func()};
		} 
		else 
		{
			window.onload = function() 
			{
				if (oldonload){oldonload();}
				func();
			}
		}
	}
	
	function isValidEmail(email)
	{
		return email.value.match(/^[\S]+@[\S]+\.[\w]+$/)
	}
	
	function countChars(txtfield, countfield, maxchars)
	{
		//txtfield - id of field containing text to count
		//countfield - id of element (ideally a div) to display the count
		//maxchars - maximum number of chars allowed in txtfield
		
		txt = document.getElementById(txtfield).value
		txt = txt.replace(/\n/g, "")
		txt = txt.replace(/\r/g, "")
		div = document.getElementById(countfield)
		
		if(txt.length > maxchars)
		{
			div.innerHTML = "Characters to remove: " + ((maxchars - txt.length) * -1)
			div.style.color = "#ff0000"
			div.style.fontWeight = "bold"
			return false
		}
		else
		{
			div.innerHTML = "Characters remaining: " + (maxchars - txt.length) 
			div.style.color = "#000000"
			div.style.fontWeight = "normal"
			return true
		}
	}
	
	//Browser destection - code from http://www.quirksmode.org/js/detect.html
	// Properties exposed:
	// BrowserDetect.browser - browser name
    // BrowserDetect.version - browser version 
    // BrowserDetect.OS - OS name 

	var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

// Authorize handles

function AuthorizeCreditCardInfo() {
    $.blockUI();
    var isAuthorized = false;
    var data = new Object();

    data.CreditCardNumber = $('input[name="cardNumber"]').val();
    data.CardMonth = ($('select[name="cardToMonth"]').val() == null) ? $('input[name="cardToMonth"]').val() : $('select[name="cardToMonth"]').val();
    var tmpYear = ($('select[name="cardToYear"]').val() == null) ? $('input[name="cardToYear"]').val() : $('select[name="cardToYear"]').val();
    data.CardYear = (parseInt(tmpYear) < 2000) ? parseInt(tmpYear) + 2000 : tmpYear;
    data.CardholderName = $('input[name="cardHolderName"]').val();
    data.CardVerificationCode = ($('input[name="cardSecurityCode"]').val() == null) ? $('input[name="cvv"]').val() : $('input[name="cardSecurityCode"]').val();
    data.CardType = ($('select[name="cardType"]').val() == null) ? $('input[name="cardType"]').val() : $('select[name="cardType"]').val();
    data.Country = $('select[name="cardAddCountry"]').val();
    data.AddressLine1 = ($('input[name="AddressLine1"]').val() == null) ? $('input[name="cardAddLine1"]').val() : $('input[name="AddressLine1"]').val();
    data.AddressLine2 = ($('input[name="AddressLine2"]').val() == null) ? $('input[name="cardAddLine2"]').val() : $('input[name="AddressLine2"]').val();
    data.Town = ($('input[name="City"]').val() == null) ? $('input[name="cardAddTown"]').val() : $('input[name="City"]').val();
    data.County = $('select[name="addressRegionDrop"]').val();
    data.PostCode = ($('input[name="Zip"]').val() == null) ? $('input[name="cardAddPostcode"]').val() : $('input[name="Zip"]').val();
    data.DonationSourceId = parseInt($('#DonationSourceId').val());
    data.DonationId = 1;
    data.Amount = "1.00";

    $.ajax({
        type: 'Post',
        url: '/app/PaymentWebApi/Authorize',
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/json;',
        cache: false,
        async: false,
        success: function (result) {

            if (result.Success) {

                if (result.Data.IsAuthorized) {
                    isAuthorized = true;
                    
                }
            }
            else {
                alert('An unexpected error has occurred. Please try again.  If errors continue contact customer support.');
            }
            $.unblockUI();
        },
        error:function (xhr, ajaxOptions, thrownError){
            $.unblockUI();
            alert('An unexpected error has occurred. Please try again.  If errors continue contact customer support. ' + xhr.status + " " + thrownError);
        }
    });

    return isAuthorized;
}


