// simple jQuery code for Nobrow pages, just to handle menu buttons
// nobrow02js.js		from contact10js.js 29oct09 of metal box project28 Oct 09 
//						30 jan 10  use jQuery to position footerdiv
//						 7 Feb 10  converted to WP (nb in /scripts/nobrow02js.js)
//                      14 feb 10  change BuyButton to <input type image... (remove .children()
//						20 Feb 10  position footerdiv for Blog layout too
//						 7 Mar 10  minimum page ht (600px for now)
//						20 Apr 10  add sign up button etc
//						22 Apr 10  (Nobrow) absolute address for call to mlist_insert.php
//                       6 May 10  add trigger to submit shop cart form if anything changes on shop cart page
//						27 Jul 10  add validateCart (to ensure user has set shipzone)


// global variables


// *************** to handle menu buttons **********************************

$(document).ready(function() {
		
		// Preload all rollovers
		$("#menudiv img").each(function() {
			// Set the original src
			rollsrc = $(this).attr("src");
			rollON = rollsrc.replace('_black', '_blue');
			newImg = new Image(); // create new image obj
			$(newImg).attr("src", rollON); // set new obj's src, ie cache it
			//rollDown = rollsrc.replace('_up', '_down');
			//downImg = new Image(); // create new image obj
			//$(downImg).attr("src", rollDown); // set new obj's src, ie cache it
		});

		
		// Navigation rollovers
		$("#menudiv a").mouseover(function(){
			imgsrc = $(this).children("img").attr("src");
			if (typeof(imgsrc) != 'undefined') {
				imgsrcOVER = imgsrc.replace('_black', '_blue');
				$(this).children("img").attr("src", imgsrcOVER);
			}
		});
		
		// on mouse down
		/*$("#menudiv a").mousedown(function(){
			if (typeof(imgsrc) != 'undefined') {
				imgsrcDOWN = imgsrc.replace('_up', '_down');
				$(this).children("img").attr("src", imgsrcDOWN);
			}
		});
		*/
		
		// Handle mouseout
		$("#menudiv a").mouseout(function(){
			if (typeof(imgsrc) != 'undefined') {
				$(this).children("img").attr("src", imgsrc);
			}
		});
		
});

// *************** to handle Buy Buttons **********************************

$(document).ready(function() {
		
		// Preload all rollovers
		$(".buyImg").each(function() {
			// Set the original src
			rollsrc = $(this).attr("src");
			rollON = rollsrc.replace('buy_up', 'buy_over');
			newImg = new Image(); // create new image obj
			$(newImg).attr("src", rollON); // set new obj's src, ie cache it
			rollDown = rollsrc.replace('buy_up', 'in_cart');
			downImg = new Image(); // create new image obj
			$(downImg).attr("src", rollDown); // set new obj's src, ie cache it
		});

		
		// Navigation rollovers
		// mouse over
		$(".buyImg").mouseover(function(){
			imgsrc = $(this).attr("src");
			if (typeof(imgsrc) != 'undefined') {
				imgsrcOVER = imgsrc.replace('buy_up', 'buy_over');
				$(this).attr("src", imgsrcOVER);
			}
		});
		
		// on mouse down change to 'in cart'
		// but it may be better to drive this from analysis of cart (not mouse-down?)
		$(".buyImg").mousedown(function(){
			if (typeof(imgsrc) != 'undefined') {
				imgsrcDOWN = imgsrc.replace('buy_up', 'in_cart');
				$(this).attr("src", imgsrcDOWN);
			}
		});
		
		
		// Handle mouseout
		$(".buyImg").mouseout(function(){
			if (typeof(imgsrc) != 'undefined') {
				// if product in cart then leave as 'in-cart' (this code only v simple for now)
				// will need to check cart etc etc ?
				// ie revert to buy_up only if not clicked ?
				if ($(this).attr("src") == imgsrcOVER) {
					$(this).attr("src", imgsrc);
				}
			}
		});
		
});


// ******************** to handle Sign up (mailinglist) button

$(document).ready(function() {
		
		
		// if user clicks SignUp button
		$('.footersignup a').click( function () {
											  
					postAddress();
					return false; 
	 	});
		
		
		// or if user presses CR while in text box (ie signifying submit)	
		$('#email').keyup( function(event) {
			if ( (event.which && event.which == 13) || (event.keyCode && event.keyCode == 13) ) {
				event.preventDefault();
				postAddress()
				return false;
			}
    	});
		
		// and prevent submission of form (if user presses CR)
		$('#mailinglist').submit( function() {
			   return false;
		});

						   
						   
});

// get email address from input box and check if it is a valid email format
// if so, post it to mlist_insert.php and put response (OK or you're already there!) in input field 
function postAddress() {
	var emailaddress =  $('#email').val();	
	
	// check if it looks like email format 
	reg = /^\s*\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+\s*$/

	if (reg.test(emailaddress)) {	// valid format ?
	
		// pass to mlist_insert.php file (ajax / post)
		$.post('http://www.nobrow.net/wordpress/wp-content/plugins/mlist/mlist_insert.php', {'email': emailaddress}, function( response) {
						// return result to email box
						$('#email').val(response);
		});			
		
	} else {
		$('#email').val("Invalid email address ?");
		$('#email').focus();
		$('#email').select();
	}
	
}



// *********************** end of SignUp ***************************************


// *************** to position footer below homediv on home page    ************************
// or greater of blogdiv and rightsidebardiv on blog page 
// or greater of contentdiv and leftsidebardiv on others 
// but min page ht of 600 px. So content etc minht = 600 - 151(hdr) - c 140 (footer) = 310
// also set contentdiv.height to max of sidebar and contentdiv, so that grey keyline extends to bottom

$(document).ready(function() {
		var innerht;
		var minht = 310;
		 
		if ($('#homediv').height()) {			// is this test robust enough (ie when homediv not in use) ?
			footertop = parseInt($('#homediv').css('top')) +  $('#homediv').height();
			$('#footerdiv').css("top", footertop + 12);
		} else if ($('#blogdiv').height()) {
			innerht = $('#blogdiv').height();
			if (innerht < minht) {
				innerht = minht;
				$('#blogdiv').height(minht);   // extend blogdiv so that grey vert keyline extends down
			}
			footertop = parseInt($('#blogdiv').css('top')) +  innerht;
			footertop2 = 0;
			if ($('#rightsidebardiv').height()) {
				sidebarht = $('#rightsidebardiv').height();
				footertop2 = parseInt($('#rightsidebardiv').css('top')) + sidebarht;
				if (  sidebarht > innerht ) {
					$('#blogdiv').height(sidebarht);   // extend blogdiv to match sidebar ht
				}
			}
			if (footertop2 > footertop) {
				footertop = footertop2;
			}
			$('#footerdiv').css("top", footertop + 12);
		} else if ($('#contentdiv').height()) {
			innerht = $('#contentdiv').height();
			if (innerht < minht) {
				innerht = minht;
				$('#contentdiv').height(minht);   // extend contentdiv so that grey vert keyline extends down
			}
			footertop = parseInt($('#contentdiv').css('top')) +  innerht;
			footertop2 = 0;
			if ($('#leftsidebardiv').height()) {
				sidebarht = $('#leftsidebardiv').height();
				footertop2 = parseInt($('#leftsidebardiv').css('top')) + sidebarht;
				if (  sidebarht > innerht ) {
					$('#contentdiv').height(sidebarht);   // extend contentdiv to match sidebar ht
				}
			}
			
			// and position footer
			if (footertop2 > footertop) {
				footertop = footertop2;
			}
			$('#footerdiv').css("top", footertop + 12);
		} 
});


// ********** resubmit shop cart form (for recalc & redisplay) if ship zone (or method) radio buttons changed ********
// **********  or qty field changed (trickier) ***************

var myTimer = null;	// timer to allow delay in typing qty

// func called if delay exceeded when typing qty (ie finished (?) typing)
function clearValues() {
	if (myTimer) {
		window.clearTimeout(myTimer);
		myTimer = null;
	}
	$("#shopcartform td.amts").text(" ");
	$("#shopcartform").trigger("submit");
};

$(document).ready(function() {
	// nb have to use click (not change) because IE doesn't trigger change until buttongroup loses focus					    // if a shipzone radiobutton clicked, clear linetotals and totals, and submit form for recalc & redisplay
	$("#shopcartform input[name='shipzonebutton']").click( function() {
		$("#shopcartform td.linetotalclass").text(" ");
		$("#shopcartform td.amts").text(" ");
		$("#shopcartform").trigger("submit");
	});
	// if a shipmethod radiobutton clicked, just clear shipcahrge and grand total, and submit form for recalc & redisplay
	$("input[name='shipmethodbutton']").click( function() {
		$("#shopcartform td[headers='cartItem scharge']").text(" ");  // have to change if hdrs get changed
		$("#shopcartform td[headers='cTotal cartTotal']").text(" ");
		$("#shopcartform").trigger("submit");
	});
	
	// update if user exits Qty field (tab,  mouse), bit of a catch all
	$('#shopcartform .carttext:text').blur( function() {
		//if timer running, stop it
		if (myTimer) {
			window.clearTimeout(myTimer);
			myTimer = null;
		}
		$(this).parent().parent().next().text(" ");  // linetotal for this line
		$("#shopcartform td.amts").text(" ");
		$("#shopcartform").trigger("submit");
	});

	// update if user is typing into qty field but pauses (no keypress for 3 secs)
	// this is for when he has finished typing but doesn't tab out (ie blur)
	// is this too quick ? too slow ?
	$('#shopcartform .carttext:text').keyup(function(event) {
		$(this).parent().parent().next().text(" ");				// linetotal for this line
		// if key is CR then don't delay (and allow normal default submit process)
		if (event.keyCode == 13 ) {
			if (myTimer) {
				window.clearTimeout(myTimer);
				myTimer = null;
			}
			$("#shopcartform td.amts").text(" ");
		} else {
			if (myTimer) {
				window.clearTimeout(myTimer);
			}
			myTimer = window.setTimeout( 'clearValues()', 3000 );
		}
	});

	

});

// **************** end of automatically submit shop cart form ***************

// 9aug10. System doesn't set shipzone radio button anymore
//          (in order to force user to set it, and hopefully reduce discrepancies)
// so now need to check if user has set the shipZone 
function validateCart() {
	//alert("validateCart");
	// has shipzonebutton been set by user ? check to see if a button is selected
	zoneButton = $('input:radio[name=shipzonebutton]:checked').val();
	
	if (zoneButton == undefined) {
		// if not, tell user he must select one
		$('#shipzoneplease').hide().show('slow', function() {
			$('#shipzoneplease').parent().addClass('redBorder');
		});
	} else {
		// if one is set then proceed to paypal express as normal
		$('#shipzoneplease').hide();
		window.location.href = "wordpress/wp-content/plugins/eshop/ppx_setexpress.php";
		
	}
	
}

// ******************* email functions for contact page (not used yet) ********************
// email functions


function selectName() {
	fld = document.emailForm.Name;
	fld.focus();
	fld.select();
}

// reg exp from Javascript Visual Quickstart manual (modified so that leading/trailing spaces allowed)

reg = /^\s*\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+\s*$/

function validEmail(myform) {
	if (reg.test(myform.Email.value)) {
		return true
	}
	alert("Invalid email address");
	myform.Email.focus();
	myform.Email.select();
	return false;
}


// new Ajax sendMail function  4sep09
// ombsendmail.php returns 'Success ' if OK, otherwise the ErrorInfo from php mail
function sendEmail (myform) {
	if (validEmail(myform)) {
		var myURL = "ombsendmail.php"; // absolute while testing local
		var myFormData = $("#emailForm").serialize();
		var myHTML = "";
      	// send form using jQuery Ajax POST
		$.post(myURL, myFormData, function(data) {
				if (data.substr(0,7) == "Success") {
					myHTML += "<p>Thank you for your enquiry. We will reply to you shortly</p>";
				} else {
					myHTML += "<p>We are sorry but there has been a problem and your message has not been sent.<br>Please try again later, or contact us by phone or letter.</p>"
				}
				$("#resultdiv").html(myHTML);					   
		});
		
	}
}

// not used, but might be if revert to button for Send
function emailOver (imgName) {   
	document.images[imgName].src = "img/emailup.gif";
	document.images[imgName].parentNode.hideFocus = true;
	return true;
}
function emailOut (imgName) {    // normal when mouse out,
	document.images[imgName].src = "img/emaildown.gif";
	return true;
}
