var tools = {

	iefix : function() {
		if($.browser.msie)	$('.flash').each(	function() { var html = $(this).html();	$(this).html(html);	})
	},

	startup : function() {  
		$('#header label').show();
		$('#username').val(''); $('#password').val('');
		$("label.overlabel").overlabel();
		$('.rounded').nifty('top large');
		$('.nifty').nifty();
		$('#managedServices a').animate({opacity: 1.0}, 500).hide().animate({opacity: 1.0}, 500).slideDown('slow').animate({opacity: 1.0}, 2000).fadeOut('slow').fadeIn('slow').animate({opacity: 1.0}, 2000).fadeOut('slow').fadeIn('slow');
		$('#spec h3').nifty('top large');
		$('#_date').datePicker().trigger('change');
	},

	popup : function(url, large, scrollb) {
		string = (large)?', width=800,height=800':', width=520,height=570';
		window.open(url, "", "menubar=1,resizable=1, scrollbars=1,status=1 "+ string);		
	},
	
	openwindow : function(url) {
		window.open(url, "", "menubar=0,resizable=1, scrollbars=1, "+ 'width='+(screen.availWidth-10)+',height='+screen.availHeight);
	},
	
	deleteConfiguration : function (serial, name) {
		if(confirm('Are you sure you want to permanently Delete the following Configuration?\n\n  -  '+name)) {
			
			$.getJSON('/configurations/delete/'+serial, '', 
				function(data) {
					if(data.result) {
						$('#'+serial).html('<a><strong>Deleting your Configuration....</strong></a>').animate({opacity: 1.0}, 1000).fadeOut('slow');
					}
					else {
						alert('There seems to be something out of the ordinary about your system configuration.\n Please try again');
					}
				}
			);			
		}
		else
			return false;
	},

	
	authenticate : function() {
		$('#login').hide();
		$.post('/home/authenticate/', $('#authenticate').serialize(), 
			function(data) { 
				$('#login').fadeIn('fast').empty().append(data); 
				if($('#header').length  > 0) {
					$('#username').val(''); $('#password').val('');				
					$("label.overlabel").overlabel();
				}	
			} 
		);
	},
	
	calculateRewards : function() { 
		var total = 0;
		$('#rewards_list input.qty').each( 
			function(i)  { 
				total = total + (parseInt($(this).val()) * parseInt($(this).attr('title')));
			}
		);
		if(total) {
			$('#total').html(total);
			$('#reward_totals').fadeIn();
		}
		else {
			$('#reward_totals').fadeOut();
		}
	},
	
	loadPostal : function() { 
		$('#postalAdd1').val($('#tradingAdd1').val());
		$('#postalAdd2').val($('#tradingAdd2').val());
		$('#postalAdd3').val($('#tradingAdd3').val());
		$('#stateP').val($('#stateT').val());
		$('#postP').val($('#postT').val());	
	},


	addRewardItem : function(input, id) { 
		$.getJSON('', '',
			function(data) {


			}
		);
	},
	
	appSubmit : function() {
		
		if(this.verify('app')) {
			if(confirm('By submitting your dealer application, you agree to our terms and conditions')) { 
				var url = '/home/register/process/';
				$.post( url, $('#app').serialize(),
					function(data) { 
						$('#appResults').fadeOut().empty().append(data).fadeIn();						
					}
				);
			}
			else {
				
				
			
			}
		}
	},
	
	deleteQuotation : function (rowId, serial) {
		if(confirm('Are you sure you wish to delete this Quotation?')) {
			$.post('/orders/delete_quote/', { id: serial },
				function(data) {		
					if(data.done == 'true') {
						$('#'+rowId).fadeOut('slow').remove();
					}
					else { 
						if(confirm('Quotation could not be deleted. Would you like to refresh your page to try again?')) {
							 window.location.href = unescape(window.location.pathname);
						}
					}
				} , "json"
			);
		}
	},
	
	updateCompanyInfo : function() {
		$('#detailsForm').hide();
		$.post('/marketing/updateCompanyDetails/', $('#detailsf').serialize(), 
			function(data) { 
				$('#detailsForm').empty().append(data).fadeIn();
			}
		)
	},
	
	submitEditCart  : function() {
		
		$('#save_cart').val('Saving Cart...').attr('disabled', 'disabled');
		
		$.post( '/orders/updateCart/ajax' , $('#cart_contents_form').serialize(),
			function(data) { 
				$('#editCart').empty().append(data);
			}
		);
		
	},
	
	verify : function(form) {
		
		$('#xhtml').val($('#editor').val());
		
		var intact = true;
		$('#'+form+' .verify').each( 
			function(i) { 
				$(this).removeClass('red');
				if($(this).val() == '' || 
					($(this).attr('checked') == false && $(this).attr('type') == 'checkbox'))  { 
					$(this).addClass('red');
					intact = false;
				}				
			} 
		);
		if(!intact) alert('Please check that you have entered all information correctly');
		
		return intact;
	},
	
	showProductList : function(obj) {
		
		if($(obj).hasClass('minus')) { 
			$(obj).removeClass('minus').addClass('plus');
			$(obj).parent().children('.results').hide();
		}
		else {
			// expand
			
			$(obj).removeClass('plus').addClass('wait');
			
			$(obj).children('strong').show();
			var address = '/products/product_list/'+$(obj).parent().children('.range').val();
			
			$(obj).parent().children('.results').load(address, 
				function() {
					$(obj).children('strong').hide();	
					$(obj).parent().children('.results').show();
					$(obj).removeClass('plus').removeClass('wait').addClass('minus');
				}
			);
			
		
		}
		
		
		return false;
	},
	
	showFile : function (id, filename) {
	
		$('#'+id).show().attr('src', '/resources/img/'+filename);
		
	},
	
	addCart : function(obj) {
		//$(obj).children('input').attr('disabled', 'disabled');
		$(obj).children('.loading').fadeIn();		
		$('#'+$(obj).attr('id')+' .ct').hide();
		$.post('/products/add_cart', $(obj).serialize(),
			function(data) {
				$(obj).children('.loading').hide();		
				if(data.result == 'done') {
					$(obj).children('.done').show().animate({opacity: 1.0}, 1000).fadeOut(
						function() {
							$('#'+$(obj).attr('id')+' .ct').show();										
						}
					
					);	
					tools.updateCart();
				}
				else {
					$(obj).children('.error').show().animate({opacity: 1.0}, 4000).fadeOut(
						function() {
							$('#'+$(obj).attr('id')+' .ct').show();										
						}
					);	
					alert(data.result);
				}				
				$(obj).children('input').removeAttr('disabled');
			}, 'json'
		);
	},
	
	updateCart : function() {
		$('#basket').load('/products/refresh_cart/');	
	},
	
	showSubCat : function(obj) { 
	
		if($(obj).hasClass('minus')) {
			$('#'+$(obj).removeClass('minus').addClass('plus').parent().attr('id')+' ul').hide();
		} else {
			$('#'+$(obj).addClass('minus').removeClass('plus').parent().attr('id')+' ul').show();
		}
		
		return false;
	},
	
	
	selectShipping : function(radio) {

		var id = $(radio).attr('id');
		if(id == 'freight') {
			$('#ship_address').show();
		}
		else {
			$('#ship_address').hide();
		}
	},

	checkPostcode : function(obj){ 
		
		var value = $(obj).val();
		$('#check span').hide();
		if(value.length != 4) {
			$('#check span.error').show();
		}
		else {
			$('#check span.checking').show();
			$.getJSON('/orders/postcodecheck/'+value, '', 
				function(data){ 
					$('#check span.checking').hide();
					if(data.confirm == 'yes') {
						$('#checkout #state').val(data.state);
						$('#check span.done').show();			
					}
					else {
						$('#check span.error').show();			
					}
					
				}
			);
		}
	},
	
	emailChecker : function(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1) {
			return false
		}
		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr) {
			return false
		}
		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr) {
			return false
		}
		if (str.indexOf(at,(lat+1))!=-1) {
			return false
		}
		if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot) {
			return false
		}
		if (str.indexOf(dot,(lat+2))==-1) {
			return false
		}	
		if (str.indexOf(" ")!=-1) {
			return false
		}
		return true					
	}
};

var appForm = {

	focusApplicationField : function (obj) { this.resetApplicationField(); $(obj).parent().parent().addClass('overlay'); },	
	resetApplicationField : function() { $('#itemList tr.overlay').each( function() { $(this).removeClass('overlay') } ); },	
	addRow : function() { $('#itemList .end').removeClass('end').clone().addClass('end').insertBefore('#marker'); $('#itemList .end input').each(function() { $(this).val('') }); $('#itemList .end textarea').val(''); },
	submitForm : function(form) {

		var error = false; 
		//$('.verify').each(function() { if(($(this).val() == '')) { $(this).addClass('error'); error = true; } else { $(this).removeClass('error'); } });
		$('.verify input').each(function() { if($(this).val() == '') { $(this).addClass('shade'); error = true; } else { $(this).removeClass('shade'); }  });
		$('.verify textarea').each(function() { if($(this).val() == '') { $(this).addClass('shade'); error = true; } else { $(this).removeClass('shade'); }  });
		$('.email input').each(function() { if(!tools.emailChecker($(this).val())) { $(this).addClass('shade'); error = true; } else { $(this).removeClass('shade'); } } );

		if(error) alert('Please check the Form and fill out the required Fields');
		else { 
			var params = $('#RaApplication').serialize();
			$('#RaApplication input').attr('disabled', 'disabled');
			$('#RaApplication textarea').attr('disabled', 'disabled');
			$('#RaApplication select').attr('disabled', 'disabled');
			$('#RaApplication button').attr('disabled', 'disabled');
			$('#RaApplication').fadeOut();
			switch(form) {
				case('mon'): var url = '/support/monitors/ajax'; var send = true;	break;
				case('ra'):	var url = '';	var send = true; break;
				default: var send = false; break;
			}
			if(send) $.post(url, params, function(data) { $('#support').empty().append(data); }) 
		} 
		return false;
	}
}
var support = { 
	submitRequest : function() {
		var error = false;
		$('.verify').each(function() { if($(this).val() == '') { $(this).addClass('error'); error = true; } else { $(this).removeClass('error'); }  });		
		var url = '/request/supportEnquiry.php';
		var params = $('#supportEnquiry').formSerialize();
		$('#enquiry').append(completeAHAH.loading);
		if(error == false) 
			$.post(url, params, function(data) { $('#enquiry').empty().append(data); }) 
	},
	showPreview : function(jobject, ev) {
		var id = jobject.attr('id');
		$('#support').append('<div id="_'+id+'" class="fs"><div><img src="'+jobject.attr('href')+'" /></div></div>');
		var x = (parseInt(ev.pageX)-20);
		var y = (parseInt(ev.pageY)+26);
		$('#_'+id).attr('style', 'left:'+x+'px; top:'+y+'px;');
		$('#_'+id).fadeIn('fast');
	},
	hidePreview : function(jobject, ev) {
		var id = jobject.attr('id');
		$('#_'+id).fadeOut('fast');
	}
}
