// JavaScript Document

PublicTraining = {
	
	pageUrl: '',
	
	mode: '',
	
	initialize: function(){
		
		$(document).ready( function(){

			//set the button pressed to the form, to this first of all
			$("input[type=image]").click(function(){
				$("input[name=ButtonPressed]").val( $(this).attr("name") );
			});

			//preload for button hover images
			$("#cartContainer input[type=image]").each(function(){
				$("<img />").attr("src", $(this).attr("src").replace(".gif","_hover.gif") );
			});

			//set the hover for buttons
			$("#cartContainer input[type=image]").hover(
				function(){
					if ( $(this).attr("src").indexOf("_hover") == -1 )
						$(this).attr("src", $(this).attr("src").replace(".gif","_hover.gif") )
				},
				function(){
					if ( $(this).attr("src").indexOf("_hover") > -1 )
						$(this).attr("src", $(this).attr("src").replace("_hover.gif",".gif") )
				}
			);
									
			//set only number for number fields
			$("table.cartTable input.qtyInput").keypress( PublicTraining.allowOnlyNumber );
			$("input.number").keypress( PublicTraining.allowOnlyNumber );
			
			//set the remove links functionality
			$("table.cartTable a.removeLink").click(function(){
		   		var itemId = $(this).parents("tr:first").find("input[name=ItemId]").val();
				$("#RemoveItemId").val( itemId );
				$("#registrationForm").submit();
				return false;
		   	});
			
			//set the checkout button fucntionality
			$("#buttonCheckOut").click(function(){
				if ( PublicTraining.validateForm() ){
					//go to billing info
					var isOAUGmember = $("#chkOAUGMember").is(":checked")?'1':'0';
					window.location.href = PublicTraining.pageUrl + '&Mode=BILLING&OAUGMember='+isOAUGmember;
				}
				return false;
			});
			
			//set the name="PaymentMethod" change
			var functionClickHandler = function(){
				var value = $("input[name=PaymentMethod]:checked").val();
				if ( value == 'PurchaseOrder' )
					$("#purchaseOrderContainer").css("visibility", "visible");
				else if ( value == 'PayPal' )
					$("#purchaseOrderContainer").css("visibility", "hidden");
			};
			$("input[name=PaymentMethod]").click( functionClickHandler );
			functionClickHandler();
			
			//make sure the cart item, shows the correct amount
			if ( PublicTraining.mode == 'CART' ){
				var count = 0;
				$("table#cartTable tbody tr input[name=QtysPost]").each(function(){
					var add = parseInt($(this).val());
					if ( !isNaN(add) )
						count += add;
				});
				$("span#cartItemsCount").html( count );
			}
			else if ( PublicTraining.mode == 'CONFIRMATION' ){
				$("span#cartItemsCount").html("0");
			}
			else if ( PublicTraining.mode == 'BILLING' ){
				$("select[name=CountryCode]").change(function(){
					if ( $(this).val() == 'US' ){
						$("select[name=State]").parent("div").show();
						$("input[name=StateText]").val("").parent("div").hide();
					}
					else{
						$("select[name=State]").val("").parent("div").hide();
						$("input[name=StateText]").parent("div").show();
					}
					$("input[name=Country]").val( $("select[name=CountryCode] option:selected").html() );
				}).trigger("change");
			}

			//set the validation handler
			$("#cartContainer input[type=image]").click(function(){
				return PublicTraining.validateForm();
			});
			$("#registrationForm").submit(function(){
				return PublicTraining.validateForm();
			});

        });
		
	},
	
	validateForm: function(){
		
		var valErr = $("#validationErrors").html("");
		
		var buttonPressed = $("input[name=ButtonPressed]").val();
		
		if ( PublicTraining.mode == 'CART' ){
			
			//validate qtys completed
			$("table.cartTable input.qtyInput").each(function(){
				if ( $.trim( $(this).val() ).length == 0 ){
					valErr.append("<p>You must complete all quantities<p>");
					return false;
				}
			});
			
			//check if the cart needs to be updated
			if ( valErr.html().length == 0 && buttonPressed != "UpdateCart" ){
				var count = 0;
				$("table#cartTable tbody tr input[name=QtysPost]").each(function(){
					var add = parseInt($(this).val());
					if ( !isNaN(add) )
						count += add;
				});
				if ( $("span#cartItemsCount").html() != count ){
					valErr.append("<p>You should update the cart first<p>");
				}
			}
			
		}
		else if ( PublicTraining.mode == 'BILLING' ){

			if ( buttonPressed == "Continue" ){
				
				//make sure they completed all fields --> .validationFieldFalied
				var incompleteFound = 0;				
				$("#registrationForm .formRow:visible input[type=text], #registrationForm .formRow:visible select").each(function(){
					if (  $(this).attr("name") != "Address2" && $(this).attr("name") != "PurchaseOrder" ){
						if ( $.trim( $(this).val() ).length == 0 ){
							$(this).addClass("validationFieldFalied");	
							incompleteFound += 1;
						}
						else
							$(this).removeClass("validationFieldFalied");	
					}
				});
				if ( incompleteFound ){
					valErr.append("<p>There are required fields incomplete<p>");
				}
				
				//make sure they piched a payment method
				if ( $("#registrationForm .formRow input[name=PaymentMethod]:checked ").length == 0 ){
					valErr.append("<p>You must choose a method of payment<p>");	
				}
				
				//check if PO needs to be completed
				var pofield = $("#registrationForm .formRow input[name=PurchaseOrder]");
				if ( $("#registrationForm input[name=PaymentMethod]:checked").val()=='PurchaseOrder' &&
					 $.trim( pofield.val() )==0  ){
					pofield.addClass("validationFieldFalied");		
					valErr.append("<p>You must complete the Purchase Order number<p>");	
				}
				else{
					pofield.removeClass("validationFieldFalied");						
				}
				
				//check if Ruffle code had been used before
				if ( $("#registrationForm input[name=PaymentMethod]:checked").val()=='PurchaseOrder' ){
					var codes = $.trim($("#ruffleCodesUsed").html()).split("|");
					var po = $.trim(pofield.val());
					for (var i=0; i<codes.length; i++){
						if ( codes[i] == po ){
							valErr.append("<p>You entered an already used ruffle number<p>");	
						}
					}
				}
				
			
			}
			
		}
		else if ( PublicTraining.mode == 'REVIEW' ){
			
		}
		else
			return false;
			
		return valErr.html().length == 0;
		
	},
	
	urlencode: function( str ) {
							 
		var histogram = {}, unicodeStr='', hexEscStr='';
		var ret = (str+'').toString();
		
		var replacer = function(search, replace, str) {
			var tmp_arr = [];
			tmp_arr = str.split(search);
			return tmp_arr.join(replace);
		};
		
		// The histogram is identical to the one in urldecode.
		histogram["'"]   = '%27';
		histogram['(']   = '%28';
		histogram[')']   = '%29';
		histogram['*']   = '%2A';
		histogram['~']   = '%7E';
		histogram['!']   = '%21';
		histogram['%20'] = '+';
		histogram['\u00DC'] = '%DC';
		histogram['\u00FC'] = '%FC';
		histogram['\u00C4'] = '%D4';
		histogram['\u00E4'] = '%E4';
		histogram['\u00D6'] = '%D6';
		histogram['\u00F6'] = '%F6';
		histogram['\u00DF'] = '%DF';
		histogram['\u20AC'] = '%80';
		histogram['\u0081'] = '%81';
		histogram['\u201A'] = '%82';
		histogram['\u0192'] = '%83';
		histogram['\u201E'] = '%84';
		histogram['\u2026'] = '%85';
		histogram['\u2020'] = '%86';
		histogram['\u2021'] = '%87';
		histogram['\u02C6'] = '%88';
		histogram['\u2030'] = '%89';
		histogram['\u0160'] = '%8A';
		histogram['\u2039'] = '%8B';
		histogram['\u0152'] = '%8C';
		histogram['\u008D'] = '%8D';
		histogram['\u017D'] = '%8E';
		histogram['\u008F'] = '%8F';
		histogram['\u0090'] = '%90';
		histogram['\u2018'] = '%91';
		histogram['\u2019'] = '%92';
		histogram['\u201C'] = '%93';
		histogram['\u201D'] = '%94';
		histogram['\u2022'] = '%95';
		histogram['\u2013'] = '%96';
		histogram['\u2014'] = '%97';
		histogram['\u02DC'] = '%98';
		histogram['\u2122'] = '%99';
		histogram['\u0161'] = '%9A';
		histogram['\u203A'] = '%9B';
		histogram['\u0153'] = '%9C';
		histogram['\u009D'] = '%9D';
		histogram['\u017E'] = '%9E';
		histogram['\u0178'] = '%9F';
		
		// Begin with encodeURIComponent, which most resembles PHP's encoding functions
		ret = encodeURIComponent(ret);
		
		for (unicodeStr in histogram) {
			hexEscStr = histogram[unicodeStr];
			ret = replacer(unicodeStr, hexEscStr, ret); // Custom replace. No regexing
		}
		
		// Uppercase for full PHP compatibility
		return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {
			return "%"+m2.toUpperCase();
		});
	},
	
	allowOnlyNumber: function(e){
		// 8:backspace - 0:delete 
		if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) )
			return false;
	}
	
} 

PublicTraining.initialize();

