/**
 * consumer frontend javascript
 */

var pageTracker,
	HPI = {};

HPI.marlin = {
	
	init: function()
	{
    // test for dubious input and attempt to repair
	$('input').change(function () {
	    var val = this.value;
	    val = val.replace(/&([^\s]+)|<([^\s]+)|\$([^\s]+)/g, '?$1');	       
	    val = val.replace(/[^\x00-\x7f]+|=/g, '?');	    
	    this.value = val;	        
	});	
    
        this.ga();
		HPI.marketing.init();
		
		if (this.getPageId() == 'contactus') {
			// handler for contact form
			this.handleContactForm();
		}
		
		if (this.getPageId() == 'affiliate') {
			// handler for contact form
			this.handleAffiliateForm();
		}
		
		if ($('html.mobile').length || this.isPossibleMobile()) {
			this.addMobileBanner();
			this.addMobileSiteLink();
		}
		
		/*if (this.getPageId() == 'home')
		{
			$('#flashAdvert').flash(
		        { src: 'flash/clone.swf', width: 423, height: 220 },
		        { version: 9, update: false }	  	
		    );
		}
		*/
	
	},
	
	/**
	 * Initilise the Google Anaylics code
	 */
	ga: function()
	{
		$.ajax({
			url: "http://" + document.location.host + "/consumer/hpiGoogleAnalytics.st",
			success: function(data) {
				try {
					pageTracker = _gat._getTracker(data);
					pageTracker._trackPageview();
					HPI.marketing.GA = data;
					}
				catch(err) {}
			}
		});
	},
	
	/**
	 * return the page BODY id
	 */
	getPageId: function ()
	{
		return document.getElementsByTagName('body')[0].id
	},	
	
	/**
	 * contact form validation and processing.
	 */
	handleContactForm: function ()
	{
		$('#contact_form').validate({
			rules: {
				email: {
					required: true,
					email: true
				},
				comments: {
					required: true
				}
			},
			messages: {
				email: {
					required: 'Please enter a valid email address'
				},
				comments: {
					required: 'Please enter a comment'
				}
			},
			errorElement: 'p',
			errorPlacement: function (err,el) {
				el[0].parentNode.appendChild(err[0]);
			},	
			submitHandler: function (form) {
				var box = $('#contact_form');
				box.height(box.height());
				
				$.ajax({
					type: "POST",
					url: "/marlin/contactus.st",
					data: $('#contact_form').serialize(),
					success: function() {
						box.html('<h2>Contact Form Submitted</h2>')
							.append('<p>We will be in touch soon.</p>');
						
					},
					error:function (xhr, ajaxOptions, thrownError) {
						var box = $('#contact_form');
						box.height(box.height());
						box.html('<h2>Contact Form Failed</h2>')
							.append("<p>Please try again later.</p>");
							
	             			//alert(xhr.status);
							//alert(ajaxOptions);
	             			//alert(thrownError);
					}
				});
			}

		});
	},
	
	/**
	 * affiliate signup form validation and processing.
	 */
	handleAffiliateForm: function ()
	{
		$('#affiliateForm').validate({
			rules: {
				name: {
					required: true
				},
				emailAddress: {
					required: true,
					email: true
				},
				website: {
					required: true
				},
				websiteDescription: {
					required: true
				},
				websiteCategory: {
					required: true
				},
				websiteStatus: {
					required: true
				},
				numberOfVisitorsPerMonth: {
					number: true
				}
			},
			errorElement: 'p',
			errorPlacement: function (err,el) {
				el[0].parentNode.appendChild(err[0]);
			},
			submitHandler: function (form) {
				var box = $('#affiliateForm');
				box.height(box.height());
				$.ajax({
					type: "POST",
					url: "/marlin/affiliatesignup.st",
					data: $(form).serialize(),
					success: function() {
						box.html("<h2>Sign Up Form Submitted</h2>").append("<p>We will be in touch soon.</p>");
						$('p.affiliateInfo').hide();
					},
					error:function (xhr, ajaxOptions, thrownError) {
						box.html("<h2>Sign Up Failed</h2>").append("<p>Please try again later.</p>");
						$('p.affiliateInfo').hide();
					}      
				});
			}
		});
	},
	
	/**
	 * Add a banner at the top of the page linking to the mobile version
	 */
	addMobileBanner: function ()
	{
		if (this.readCookie('MOBILE_BANNER_HIDDEN') == 'true') {
			return;
		}
		
		var that = this;
		
		this.banner = $('<div>').addClass('mobileBanner').prependTo('body'),
			
		
		this.banner.html('Would you like to browse the mobile version of our website?');
		
		$('<a>Yes please</a>').click(function () {
			var date = new Date(),
				expires;
		
				date.setTime(date.getTime() + (60*60*1000));
				document.cookie = 'CONS_SITE_VERSION=mobile; expires='+date.toGMTString()+'; path=/';
				location.reload(true);
				
		}).appendTo(this.banner);
		
		$('<a>No thanks</a>').click(function () {
			that.mobileBannerHide();
			
			var date = new Date(),
				expires;
		
			date.setTime(date.getTime() + (60*60*1000));
			document.cookie = 'MOBILE_BANNER_HIDDEN=true; expires='+date.toGMTString()+'; path=/';
			
		}).appendTo(this.banner);
		
	},
	
	/**
	 * show a final message and hide the banner
	 */
	mobileBannerHide: function ()
	{
		var that = this;
		
		this.banner.html('You can view the mobile site at any time by using the link at the bottom of the page.');
		$('<a>Hide</a>').click(function () {
			that.banner.hide();
		}).appendTo(this.banner);
		
	},
	
	/**
	 * read the value of a named cookie
	 */
	readCookie: function(name) 
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	},
	
	/**
	 * is the client device possibly a mobile?
	 */
	isPossibleMobile: function ()
	{
		return screen.width < 600 || screen.height < 600;
	},
	
	/**
	 * add the view mobile website link to the page footer
	 */
	addMobileSiteLink: function () {
		var mob = $('<a>View mobile website</a>').click(function () {
			var date = new Date(),
				expires;
		
				date.setTime(date.getTime() + (60*60*1000));
				document.cookie = 'CONS_SITE_VERSION=mobile; expires='+date.toGMTString()+'; path=/';
				location.reload(true);
		});
		
		$('<li>').append(mob).appendTo('ul.footnav');
	}
		
};


function submitForm(type) {
	var form = document.forms['hpicheck'];
	if (form != null) {
		var vrm = form.vrm.value.toUpperCase();
		form.vrm.value = vrm;
	} else {
		var vrm = '';
	}
	params = "?supplier=&vrm=" + vrm;
	if (type == 'buyOne' || typeof type == "undefined") {
		params = params + "&update=false";
	}
	if (type == 'buyBundle') {
		params = params
				+ "&source=HPIBN03&update=false&campaignCode=HPI3&productCode=HCP23";
	}
	if (type == 'update') {
		params = params + "&update=true";
	}
	if (type == 'redeem') {
		params = params
				+ "&source=HPIBN03&update=false&campaignCode=HPI3&productCode=HCP23&returningCustomer=true";
	}

	var urlstr = "/consumer/" + params;
	//window.open(urlstr);
	return false;
	
};

