$(document).ready(function() {
	
	//  Imposes Maxlength Attributes on Textareas
	var txts = document.getElementsByTagName('TEXTAREA') 

	  for(var i = 0, l = txts.length; i < l; i++) {
	    if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) { 
	      var func = function() { 
	        var len = parseInt(this.getAttribute("maxlength"), 10); 

	        if(this.value.length > len) { 
	          this.value = this.value.substr(0, len); 
	          return false; 
	        } 
	      }

	      txts[i].onkeyup = func;
	      txts[i].onblur = func;
	    } 
	  }
	
	$('#area_id').autotab({ target: 'pre_id', format: 'numeric' });
	$('#pre_id').autotab({ target: 'num_id', format: 'numeric', previous: 'area_d' });
	$('#num_id').autotab({ target: 'company_id', previous: 'pre_id', format: 'numeric' });
	
	//  Switch between the addresses in the control panel
	$("#address_ul li").click( function() {
		
		$("#address_ul li").removeClass("active");
		
		var addr_type = $(this).attr('id') + '_fk';
		
		//  Disable the "Same as Company" button if we're on the Company Address
		if (addr_type == 'addr_primary_fk')
			$('#same_id').attr('disabled', true).attr('checked', false);
		else
			$('#same_id').attr('disabled', false);
		
		$(this).addClass("active");
		$("#addr_type_id").val(addr_type);
		xajax_loadAddress(addr_type, 'n/a');
	});
	
	//  Change address fields if the user clicks the "Same as Company" button
	$('#same_id').click( function() {
		xajax_loadAddress( $('#addr_type_id').val(), $(this).attr('checked') );
	});
	
	//  Remove the Item in the Shopping Cart
	$('.remove_cart_item').click( function() {
		var id = $(this).parent().parent().attr('id');
		id = id.split("_");
		xajax_removeCartItem(id[2], id[3]);
	});
	
	//  Takes the user so they can modify the Art Item
	$('.modify_art_item').click( function() {
		var id = $(this).parent().parent().attr('id');
		id = id.split("_");
		xajax_modifyArtItem(id[3], $(this).attr('type'));
	});
	
	//  Bind Tooltips
	$('.tooltip-trigger').tooltip({position:"top center", effect:"slide", relative:true, opacity:1});
	
	//  Binds the setRegenerate function to each field in the return address section
	$('#art_message_return .field').change(function() {setRegenerate('1');});
	
	//  Load the Overlay Elements
	$('#prompt').overlay({
		oneInstance:false,
		closeOnClick:true,
		mask: {
				color: '#000000',
				loadSpeed: 200,
				opacity: 0.3
			},
		top:'center',
		left:'center'
	});
	
	$('#modal-processing').overlay({
		oneInstance:false,
		mask: {
				color: '#000000',
				loadSpeed: 200,
				opacity: 0.3
			},
		top:'center',
		left:'center',
		closeOnClick:false
	});
	
	//  Initialize the Tabs
	$("ul.tabs").tabs("div.panes > div", {
			effect: 'fade',
			onBeforeClick : function(e, i) { 
				
				//  Don't Open Disabled Tabs
			    if ($("ul.tabs > li a").eq(i).hasClass("disabled")) { 
			    	return false; 
			    }
			
				//  Update the Pricing if we're clicking on Tab 5
				if (i==4){
					if ($('#art_type_id').val() == 2)
						xajax_updateQuantityPrice($('#qty').val(), $('#size_id').val(), $('#art_type_id').val());
				}
					
				//  Update the design fields if we're clicking on tab 3
				if (i==2){
					
					//  If the Gallery exists...
					if ($('.galleria-image').length > 0){
						
						//  If Selected Design is Different than Current Design then load the new fields
						var id = $('.galleria-image.active').attr('id');
						id = id.split("_");
						if (id[2] != $('#design_fk_id').val())
							xajax_loadDesign(id[2], true);
					}
				}
					
			},
			onClick : function(e, i) {
				$('.art_button').css('display', 'none').css('display', 'block');
			}
	});
	
	//  Change the Art item's appearance if the user selects it
	//bindArtClickEvent();
});

/*****  LEADS PLEASE / LEADS BOOSTER  *****/
//  Initialize the Leads Please Widget
function initializeLeadsPleaseWidget(type){
	
	switch (type){
		case "1":
			var config =	{	
								widgetid: 'widget',
		                    	affiliatecode: 'hogue',
		                     	conclusionurl: 'http://www.postcardmarketing.net',
								callback: onComplete,
		                    	sessionid: type,
								skin: {
									buylistbtn: 'Add to Cart'
								}
							};
			break;
		case "3":
			var config =	{	
								widgetid: 'widget',
		                    	affiliatecode: 'hogue2',
		                     	conclusionurl: 'http://www.postcardmarketing.net',
								callback: onComplete,
		                    	sessionid: type,
								skin: {
									buylistbtn: 'Next Step'
								}
							};
			break;
	}
	
    var w = new LeadsPlease.Widget(config);
}

//  Leads Please Callback Function
function onComplete(x) {
	
	/*  
		x.criteriaid - ID of the list request
		x.listtype - "consumer", "business", "newhomeowner", "newmover"
		x.price - Price of the purchase
		x.qtycount - Count of the records the user searched
		x.qtydesired - Desired number of records to purchase
		x.sessionid - Session ID for the current user
	*/
	
	//  Add the item to the shopping cart
	xajax_addToCart(x, x['sessionid']);
};

/*****  ART BOOSTER  *****/
//  Sets a variable telling the system the user has to regenerate the proof before checking out
function setRegenerate(val){
	$('#proof_required').val(val);
}

//  Bind the art pieces click event
function bindArtClickEvent(){
	
	/*
	$('.art_item').click( function() {
		$('.art_item').removeClass('active');
		$(this).addClass('active');
	});
	*/
	
}

//  Bind the scrollable art pieces
function bindScrollableArt(){
	
	/*
	$(".scrollable").scrollable({
		circular:false,
		speed:200
	});
	*/
	
	$('#galleria').galleria({
		transition:'fade',
		height:300,
		preload:1,
		show: Number($('#selected_design').val())
	});
	
}

//  Loads the Design that the user selected
function loadDesign(){
	var id = $('.galleria-image.active').attr('id');
	id = id.split("_");
	xajax_loadDesign(id[2]);
}

//  Display the Images for both the Front and Back of the Postcard
function displayArtPiece(front, back){
	$('#art_draft_img_front').attr('src', front);
	$('#art_draft_img_back').attr('src', back);
	
	//  Display the return address
	$('#art_draft_container_back .return').fadeIn('medium');
}

//  Populates the promotion box with the selected promotion text
function populatePromotion(text){
	
	var id = $('#discount_focus').val();
	
	if (id != '')
		$('#'+id).attr('value', text);
	else
		$('#discount_container .coupon_discount:first').attr('value', text);
}

//  Upload the user's image
function saveLogo(form){
	
	if ($('#logo_id').val().length > 0){
		
		//  Check the extension
		var ext = $('#logo_id').val().split('.').pop().toLowerCase();
		if (ext=='jpg' || ext=='jpeg' || ext=='png' || ext=='gif'){		
			openIndicator('Uploading Image...', 'Please be patient. High resolution<br/>images take a few moments to transfer');
			setRegenerate('1');
			fileUploadPublic(form, "saveLogo.htm");
		}
		else
			openModal('Error Uploading Logo', 'Please select an image of type JPG, GIF, PNG or EPS', true);
	}
	else 
		openModal('Error Uploading Logo', 'Please select an image to upload', true);
	
	return false;
}

//  Logo Upload Callback
function uploadCallback(div_id, iframeId){
	
	//  Process the Callback Response
	var response = processCallbackResponse(iframeId, uploadCallback);
	//alert(response);

	/*  Perform Response Actions here  */
	var response = response.split('@');
	$('#art_logo_container').attr('innerHTML', '<input type="file" name="logo" id="logo_id" size="30"/>');
	closeIndicator();
	
	//  Update the page's information if there's a new filename
	if (response[3] == '1'){		
		$('#art_logo_anchor').attr('href', response[1]+'p_'+response[2]).css('display', 'block');
		$('#art_logo_remove').css('display', 'block');
		$('#art_logo_thumb').attr('src', response[1]+'t_'+response[2]);
		$('#logo_filename_id').attr('value', response[2]);
	}
	else 
		openModal('Upload Error', response[0], true);
}

//  Remove the Uploaded Logo
function removeLogo(path){
	$('#art_logo_anchor, #art_logo_remove').fadeOut('medium');
	$('#art_logo_thumb').attr('src', path);
	$('#logo_filename_id').attr('value', '');
}

//  Load the designs when the user selects a category
function loadSubcategories(id){
	
	//  If there are art items then fade them out
	if ($('.art_item').length > 0){
		$('.scrollable .items').fadeOut(500, function() {
			$('.art_item').remove();
			xajax_loadSubcategories(id);
		});
	}
	else
		xajax_loadSubcategories(id);
}

//  Load the designs when the user selects a subcategory
function loadDesignsBySubcategory(id){
	
	//  If there are art items then fade them out
	if ($('.art_item').length > 0){
		$('.scrollable .items').fadeOut(250, function() {
			$('.art_item').remove();
			xajax_loadDesignsBySubcategory(id);
		});
	}
	else
		xajax_loadDesignsBySubcategory(id);
}

//  Initializes the Proof Generation
function generateProof(){
	$("#regenerate_id").fadeOut('medium');
	openIndicator('Generating Proof...', 'This should only take a moment<br/>We\'re creating a 100% customized proof just for you!<br/>Your custom generated proof can take up to one minute');
	$('#modal-processing').overlay().load();
	xajax_generateProof(	xajax.getFormValues('fieldsform'), 
							xajax.getFormValues('returnform'), 
							xajax.getFormValues('artparams'),
							$('.coupon_discount:first').val()
						);
}

//  Show the proof that was returned from the XMPie Server
function displayProof(side, path){
	$('#modal-processing').overlay().close();

	if (side == '1'){
		$('#art_draft_img_front_full').attr('href', path);
		$('#art_draft_img_front').attr('src', path);
	}
	else {
		$('#art_draft_img_back_full').attr('href', path);
		$('#art_draft_img_back').attr('src', path);
	}
	
	//  Enable the Final Tab	
	disableTabs([]);
}

//  Identify which pricing tier is currently active
function identifyPricingTier(id){
	$('.pricing_row').removeClass('active-price');
	if (id > 0)
		$('#pricing_'+id).addClass('active-price');
}

//  Validate the Promotions Tab
function validatePromotionsTab(){
	var valid = true;
	
	//  Check to make sure each coupon value is completed
	$('.coupon_discount').each( function() {
		if ($(this).val().length == 0)
			valid = false;
	});
	
	if (!valid){
		$('#prompt').addClass('modal-alert');
		$('#prompt-title').attr('innerHTML', 'Promotional Customization');
		$('#prompt-content').attr('innerHTML', 'Please Provide Discount Language<br/>for All Promotion Options');
		$('#prompt').overlay().load();
		return false;
	}
	
	disableTabs([3,4]);
	$("ul.tabs").tabs().next();
}

//  Move to the Select Quanitity Tab
function moveToStep5(){
	
	//  Only update the pricing if we're doing Art only
	if ($('#art_type').val() == 2)
		xajax_updateQuantityPrice($('#qty').val(), $('#size_id').val(), $('#art_type_id').val());
	
	disableTabs([]);
	$("ul.tabs").tabs().next();
}

//  Validate just the return address
function validateReturnAddress(){
	$('#returnform label').css('color', '#555');
	var address = new Array("return_first", "return_last", "return_company", "return_address", "return_city", "return_state", "return_zip");
	return globalValidate(address);
}

//  Validate just the message fields
function validateMessageFields(){
	$('#fieldsform label').css('color', '#555');
	
	//  Cycle Through the Required Fields
	address = new Array();
	$('.required-field').each( function() {
		address.push($(this).attr('name'));
	});
	
	return globalValidate(address);
}

//  Validate Mailer Options in the Art selection process:  Make Sure Return Address is filled
function validateMailerOptions(){
	if (validateReturnAddress() && validateMessageFields())
		generateProof();
	else
		openModal('Message Customization', 'Please Complete Required Fields', 'alert');
}

//  Validate the entire Art Selection process and adds the item to the shopping cart if it validates
function validateArtSelection(){
	
	var valid = true;
	var msg = '';
	var br = '';
	
	//  Confirm the user has selected an art piece
	if ($('#document_id_id').val() == ''){
		openModal('Error!','You must select a mailer design and options before adding to your shopping cart', 'alert');
		return false;
	}
	
	//  Confirm the user has entered their discount preferences
	var discounts = new Array();
	var valid_discounts = true;
	$('.coupon_discount').each( function() {
		var discount = new Array();
		discount['percent'] = $(this).next().val();
		discount['discount_fk'] = $(this).next().next().val();
		discount['discount'] = $(this).val().trim();
		discounts.push(discount);
		if (discount['discount'].length == 0)
			valid_discounts = false;
	});
	if (!valid_discounts){
		msg += br+'Step 2: Coupon Discount Values';
		br = "<br/>";
		valid = false;
	}
	
	//  Confirm the user has return address information entered
	if (!validateReturnAddress()){
		valid = false;
		msg += 'Step 3: Return Address Fields';
		br = "<br/>";
	}
	
	//  Confirm the user has completed the required message fields
	if (!validateMessageFields()){
		valid = false;
		msg += 'Step 3: Custom Message Fields';
		br = "<br/>";
	}
	
	//  Confirm the user has entered a quantity
	if ($('#qty').val().trim().length == 0){
		valid = false;
		msg += br+'Step 5: Mailer Quantity';
	}
	
	if (valid){
		
		//  Check to make sure that the user has regenerated the proof as necessary
		if ($('#proof_required').val() == '1'){
			$("ul.tabs").tabs().prev();
			$("#regenerate_id").fadeIn('medium');
			openModal('Proof Regeneration Required', 'You have made changes to your postcard since the last time you viewed your proof. Please click \'Regenerate Proof\' to see your most recent changes. <br/><br/>When you\'re satisfied with the design, update your shopping cart to check out!', 'alert');
			return false;
		}
		
		var art_item = new Array();
		art_item['mailer_options_fk'] = $('#mailer_options_id').val();
		art_item['quantity'] = $('#qty').val();
		art_item['price'] = $('#qty_price_hidden').val();
		art_item['discounts'] = discounts;
		art_item['order_item'] = $('#order_item_id').val();
		art_item['art_type'] = $('#art_type_id').val();
	
		//  Submit the art array and second variable indicates if we're adding just art or art to an full package
		xajax_addToCart(art_item, $('#art_type_id').val());
	}
	else 
		openModal('Missing Required Information', msg, 'alert');
	
	return false;
}

/*****  ACCOUNT FUNCTIONS  *****/
//  Validate the login form
function validateLogin(action){
	$("label.fields").css('color', '#555');
    var fields = new Array("email", "password");

	//  Make sure all the fields have information in them
    if(globalValidate(fields)){
		xajax_signin(xajax.getFormValues('signin'), action);
	}
	else
		openMsg('#login_msg', 'Please Complete Required Fields');
		
	return false;
}

//  Validate the password reset
function validateReset(){
	$("label.fields").css('color', '#555');
    var fields = new Array("email");

	//  Make sure all the fields have information in them
    if(globalValidate(fields))
		xajax_pwReset(xajax.getFormValues('signin'));
	else
		openMsg('#login_msg', 'Enter Email Address to Reset Password');

	return false;
}

//  Validate the new User signup form
function validateSignup(){
	
		//  Initialize Validation
		$("label.fields").css('color', '#555');
        var fields = new Array("fname", "lname", "email_new", "password_new", "password_confirm");

		//  Make sure all the fields have information in them
        if(globalValidate(fields)){
	
			//  Make sure the two passwords entered are the same
			if (validatePasswords('#password_new', '#password_confirm', '#signup_msg'))
				xajax_signup(xajax.getFormValues('signupform'));

        }
       	else{
			openMsg('#signup_msg', 'Missing Required Information');
			closeIndicator();
        }
        return false;
}

//  Remove the item from the shopping cart
function removeCartItem(type, id){
	
	//  If This is the last item of this group in the cart, remove the entire group container
	if ($('#cart_items_'+type+' .cart_item').size() == 1){
		$('#cart_items_'+type).fadeOut('medium', function() {
			$('#cart_items_'+type).remove();
		});
	}
	else {
		$('#cart_item_'+type+'_'+id).fadeOut('medium', function() {
			$('#cart_item_'+type+'_'+id).remove();
		});
	}
}

/*  Make Sure Everything is in line for the user to check out
		a.  User is logged in
		b.  There are no incomplete Campaigns in the cart
*/	
function validateCart(id){
	
	if ($('.incomplete_campaign').length > 0)
		openModal('Shopping Cart Incomplete', 'You have at least one incomplete<br/>Direct Mailer Campaign in your shopping cart.<br/>Please either remove the items or select your<br/>Mailer Design before checking out.', true);
	else if (id)
		window.location='Billing-Information';
	else
		window.location='Signup/Billing-Information';
}

/**********  CHECKOUT PROCESS  **********/
//  Validate the Billing Information Form
function validateBillingInfo(shipping){

	$("label.fields").css('color', '#555');
	if (shipping == 1)
    	var fields = new Array("fname", "lname", "email", "shipping_addr1", "shipping_city", "shipping_state_fk", "shipping_zip", "cc_type", "cc_number", "cc_ccv", "billing_addr1", "billing_city", "billing_state_fk", "billing_zip");
	else
		var fields = new Array("fname", "lname", "email", "cc_type", "cc_number", "cc_ccv", "billing_addr1", "billing_city", "billing_state_fk", "billing_zip");

	//  Make sure all the fields have information in them
    if(globalValidate(fields)){
	
		//  Validate the Credit Card Date
		var now = new Date();
		var cc_exp = new Date();
		cc_exp.setFullYear($('#cc_exp_year_id').val(), $('#cc_exp_month_id').val(), 1, 0, 0, 0, 0);
		if (cc_exp < now){
			openModal('Invalid Credit Card', 'Your Credit Card has Expired', true);
			$("#cc_exp_lbl").css("color", "#CD2626");
			return false;
		}
	
		xajax_saveBillingInfo(xajax.getFormValues('customerform'));
    }
    else{
		openModal('Missing Required Information', '', true);
		closeIndicator();
    }
    return false;
}

//  Apply the Discount to the Review Order Page
function applyDiscount(discount, subtotal, tax, total, percent, type){
	
	//  Change discount formatting depending on if it's a percent or dollar amount
	if (type == 0)
		$('#discount_amount').attr('innerHTML', '($'+discount+') - '+percent+'%');
	else
		$('#discount_amount').attr('innerHTML', '($'+discount+')');
	
	$('#subtotal_amount').attr('innerHTML', '$'+subtotal);
	$('#tax_amount').attr('innerHTML', '$'+tax);
	$('#total_amount').attr('innerHTML', '$'+total);
	
	//  Change Visual Display
	$('.discount_line').animate({'height':'25px'}).fadeIn('slow');
	$('#discount_code').val('');
	
}

//  Process the user's order after verifying that the art proof approval has been checked
function processOrder(approval){
	
	//  Do we need to check the approval box?
	if (approval == '1'){
		if (!$('#approve_art_id').attr('checked')){
			openModal('Art Proof Approval Required', 'Please approve of your art proofs by checking the<br/>"I Approve" checkbox in the Art Proof Approval section', 'alert');
			return false;
		}
	}
	//$('#button_process_order, #button_change').attr('disabled', true);
	$('#button_process_order').css('background-image', 'url(images/button-process-disabled.jpg)');
	$('#process_indicator').css('visibility', 'visible');
	xajax_processOrder();	
}

/**********  PERSONAL SETTINGS PAGE  **********/
//  Validate Saving Personal information on the Settings Page
function validateSavePersonal(){
	
		//  Initialize Validation
		$("label.fields").css('color', '#555');
        var fields = new Array("fname", "lname", "email");

		//  Make sure all the fields have information in them
        if(globalValidate(fields)){
			xajax_savePersonalInfo(xajax.getFormValues('settingsform'));
			closeMsg('#settings_msg');
		}
        else
			openMsg('#settings_msg', 'Missing Required Information');

        return false;
}

//  Validate Saving Company information on the Settings Page
function validateSaveCompany(){
	
		//  Initialize Validation
		/*
		$("label.fields").css('color', '#555');
        var fields = new Array();

		//  Make sure all the fields have information in them
        if(globalValidate(fields)){
			xajax_saveCompanyInfo(xajax.getFormValues('companyform'));
			closeMsg('#settings_msg');
		}
        else
			openMsg('#settings_msg', 'Missing Required Information');
		*/
		
		xajax_saveCompanyInfo(xajax.getFormValues('companyform'));
        return false;
}

//  Validate the Password Change Form
function validatePasswordChange(){
	
		//  Initialize Validation
		$("label.fields").css('color', '#555');
        var fields = new Array("password_current", "password", "password_confirm");

		//  Make sure all the fields have information in them
        if(globalValidate(fields)){
			
			//  Validate the Passwords
			if (validatePasswords('#password', '#password_confirm', '#password_msg')){			
				xajax_changePassword(xajax.getFormValues('passwordform'));
				closeMsg('#password_msg');
			}
		}
        else
			openMsg('#password_msg', 'Missing Required Information');

        return false;
}

//  Validate the Address Fields on the Settings Page
function validateAddress(){
	
		//  Initialize Validation
		$("label.fields").css('color', '#555');
        var fields = new Array("addr1", "city", "state_fk", "zip");

		//  Make sure all the fields have information in them
        if(globalValidate(fields)){
			xajax_saveAddress(xajax.getFormValues('addressform'));
			closeMsg('#address_msg');
		}
        else
			openMsg('#address_msg', 'Missing Required Information');

        return false;
}

//  Validate the Contact Form
function validateContactForm(){
	
		//  Initialize Validation
		$("label.fields").css('color', '#555');
        var fields = new Array("name", "email");

		//  Make sure all the fields have information in them
        if(globalValidate(fields)){
			$('#indicator').css('visibility', 'visible');
			xajax_submitContactForm(xajax.getFormValues('contactform'));
			closeMsg('#contact_msg');
		}
        else
			openMsg('#contact_msg', 'Missing Required Information');

        return false;
}

/**********  GENERAL FUNCTIONS  **********/
function disableTabs(indexes){
	$('ul.tabs > li a').removeClass('disabled');
	if (indexes.length != 0){
		$('ul.tabs > li a').removeClass('disabled');
		for (var i=0; i < indexes.length;i++)
			$('ul.tabs > li a:eq('+indexes[i]+')').addClass('disabled');
	}
}

function openModal(title, msg, type){
	
	switch (type){
		case 'alert':
			$('#prompt').addClass('modal-alert');
			break;
		default:
			$('#prompt').removeClass('modal-alert');
			break;
	}

	$('#prompt-title').attr('innerHTML', title);
	$('#prompt-content').attr('innerHTML', msg);
	$('#prompt').overlay().load();
	
}

function globalValidate(fields){
	
    var valid = true;
    var tmp = new String();
    for(var i=0; i<fields.length;i++){
		tmp = $('#'+fields[i]+'_id').val();
		tmp = tmp.trim();
		switch(fields[i]){
	        case "email":
                if(! validEmail(tmp)){
                    valid = false;
                    $("#"+fields[i]+"_lbl").css("color", "#CD2626");
                }
                break;
			case "area":
			case "pre":
				if(tmp.length < 3){
                    valid = false;
                    $("#phone_lbl").css("color", "#CD2626");
                }
				break;
			case "num":
				if(tmp.length < 4){
                    valid = false;
                    $("#phone_lbl").css("color", "#CD2626");
                }
	        default:
               	if(tmp.length < 1){
                    valid = false;
                   	$("#"+fields[i]+"_lbl").css("color", "#CD2626");
                }
		break;
        }
    }
	return valid;
}

function validatePasswords(pw1, pw2, msg){
	var message;
	if ($(pw1+'_id').val() == $(pw2+'_id').val()){
		if ($(pw1+'_id').val().length >= 6)
			return true;
		else
			message = 'Password must be 6-12 characters';
	}
	else
		message = 'Passwords do not match';
		
	$(pw1+'_lbl, '+pw2+'_lbl').css('color', '#CD2626');
	openMsg(msg, message);
	
	return false;
}

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)){
        if(charCode == 32 || (charCode >= 44 && charCode <= 46)){
            return true;
        }
        else{
            return false;
        }    
	}
    return true;
}

function validEmail(email){
    var tValid = true;
    if((email.length < 8) ||
        ((email.length>0) && (! email.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi)))){
        tValid = false;
    }
    return tValid;
}

function openMsg(id, msg){
	$(id).animate({height:25}, 500, function() {$(id).attr('innerHTML', msg)});
}

function closeMsg(id){
	$(id).animate({height:0}, 500, function() {$(id).attr('innerHTML', "&nbsp")});
}

function openModal(title, msg, error){
	
	if (error)
		$('#prompt').addClass('modal-alert');
	else
		$('#prompt').removeClass('modal-alert');
		
	$('#prompt-title').attr('innerHTML', title);
	$('#prompt-content').attr('innerHTML', msg);
	$('#modal-processing').overlay().close();
	setTimeout("$('#prompt').overlay().load();", 500);
}

function openIndicator(title, content){
	$('#processing-title').attr('innerHTML', title);
	$('#processing-content').attr('innerHTML', content);
	$('#modal-processing').overlay().load();
}

function closeIndicator(){
	$('#modal-processing').overlay().close();
}

/*  
	File Upload used on the public side of the site
		Params: Form to be processed, action php, message div
		Function: Differs in Message handling and actions
*/
function fileUploadPublic(form, action_url)  
{  	
	// Create the iframe...  
	var iframe = document.createElement("iframe");  
	iframe.setAttribute("id","upload_iframe");  
	iframe.setAttribute("name","upload_iframe");  
	iframe.setAttribute("width","0");  
	iframe.setAttribute("height","0");  
	iframe.setAttribute("border","0");  
	iframe.setAttribute("style","width: 0; height: 0; border: none;");  
  
	// Add to document...  
	form.parentNode.appendChild(iframe);  
	window.frames['upload_iframe'].name="upload_iframe";  
  
	iframeId = document.getElementById("upload_iframe");  
	
	/* TODO: Revise function to take callback function as a parameter  */
	var eventHandler = function() {
		uploadCallback(null, iframeId);
	}
  
	if (iframeId.addEventListener)  
		iframeId.addEventListener("load", eventHandler, true);  
	if (iframeId.attachEvent)  
		iframeId.attachEvent("onload", eventHandler);  
  
	// Set properties of form...  
	form.setAttribute("target","upload_iframe");  
	form.setAttribute("action", action_url);  
	form.setAttribute("method","post");  
	form.setAttribute("enctype","multipart/form-data");  
	form.setAttribute("encoding","multipart/form-data");   

	// Submit the form...  
	form.submit();	
}

//  Process the upload callback 
function processCallbackResponse(iframeId, uploadCallback){

	if (iframeId.detachEvent)  
		iframeId.detachEvent("onload", uploadCallback);  
	else  
		iframeId.removeEventListener("load", uploadCallback, false);

	// Message from server...  
	if (iframeId.contentDocument)
		response = iframeId.contentDocument.body.innerHTML;  
	else if (iframeId.contentWindow)
		response = iframeId.contentWindow.document.body.innerHTML;  
	else if (iframeId.document) 
		response = iframeId.document.body.innerHTML;  
	
	// Del the iframe...  
	setTimeout('iframeId.parentNode.removeChild(iframeId)', 1000);
	
	return response;
}

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
