var cat_select = 0;
var menuYloc = null;


function changeNavButton(button_name) {
	if (document.getElementById('welcome')) {
		document.getElementById('welcome').setAttribute("class", "button-off"); 
	}
	if (document.getElementById('feedback')) {
		document.getElementById('feedback').setAttribute("class", "button-off");
	}
	if (document.getElementById('about_us')) {
		document.getElementById('about_us').setAttribute("class", "button-off");
	}
	if (document.getElementById('signup')) {
		document.getElementById('signup').setAttribute("class", "button-off");
	}
		
	if (document.getElementById(button_name)) {document.getElementById(button_name).setAttribute("class", "button-on");}
		
}

function setMenuScrollDivs () { 
	if (document.getElementById('menu_cart')) {
	var cart_name = "#menu_cart"; 
	// if the height category menu is bigger then the viewpoint size then place the menu at the top of the viewpoint
	var cheight = ((document.getElementById('menu_cart').offsetHeight) > getClientHeight()) ? 0 : parseInt($(cart_name).css("top").substring(0,$(cart_name).css("top").indexOf("px")));
	
	// only if the height category menu + the header is smaller then the viewpoint size then make the div scrollable
	if ((document.getElementById('menu_cat').offsetHeight+100) < getClientHeight())	{
	$(document).ready(function(){  
		menuYloc_cart = cheight
		$(window).scroll(function () {  
			var offset = menuYloc_cart+$(document).scrollTop()+"px";  
			$(cart_name).animate({top:offset},{duration:500,queue:false});  
		});  
	}); 
	}
}

if (document.getElementById('menu_cat')) {
cat_name = "#menu_cat"; 

// if the height category menu is bigger then the viewpoint size then place the menu at the top of the viewpoint
var cheight = ((document.getElementById('menu_cat').offsetHeight) > getClientHeight()) ? 0 : parseInt($(cat_name).css("top").substring(0,$(cat_name).css("top").indexOf("px")));

// only if the height category menu + the header is smaller then the viewpoint size then make the div scrollable
if ((document.getElementById('menu_cat').offsetHeight+100) < getClientHeight())	{
$(document).ready(function(){  
	menuYloc_cat =  cheight
	$(window).scroll(function () {  
		var offset = menuYloc_cat+$(document).scrollTop()+"px";  
		$(cat_name).animate({top:offset},{duration:500,queue:false});  
	});  
});
}
}
}

function setBoxScrollDiv () {
popup_name = "#mainpage-box"; 
$(document).ready(function(){  
	menuYloc_popup = document.getElementById('mainpage-box').offsetTop;
	$(window).scroll(function () {  
		var offset = menuYloc_popup+$(document).scrollTop()+"px";  
		$(popup_name).animate({top:offset},{duration:500,queue:false});  
	});  
});

}

function remove_pre_text(el) {
	
	var re = new RegExp('pre-input-text');
	if(re.test(el.className)) {
		el.value = '';
		var re = new RegExp('pre-input-text', 'g');
		el.className = el.className.replace(re, '');
		el.style.color = '#000';
		if (el.id == 'password') {
			document.getElementById('ipassword').innerHTML = '<input type="password" id="password" onkeyup="if (KeyCheck(event) == 13) {signIn();}">';
			setTimeout("document.getElementById('password').focus();", 1);
		}
	}
}

function loadPage (page, param, form) {
	// if not in checkout then set postcode to the register postcode
	document.getElementById('postcode').value = (!param.postcode && document.getElementById('register_postcode')) 
									? document.getElementById('register_postcode').value 
									: param.postcode; 
	document.getElementById('w_id').value = param.wholesaler_id;
	form = (!form) ? document.shop_detail : form;
	
	pageid = 'home';
	if (form.name == 'register_form') pageid = 'page_reg';
	if (form.name == 'login_form') pageid = 'page_log';
	if (form.name == 'shop_detail') pageid = 'page';
	if (form.name == 'payment_delivery') pageid = 'page_check';
	if (form.name == 'checkout_form') pageid = 'page_checkout';
	
	document.getElementById(pageid).value = page;
	//alert(page);
	form.submit();
}

function getParams() {
	return param = {
		'postcode': document.getElementById('postcode').value,
		'wholesaler_id': document.getElementById('w_id').value
	};
}

function headShowHide() {
	if (document.getElementById('sub-header').style.display == '') {document.getElementById('sub-header').style.display = 'block';} 
	document.getElementById('sub-header').style.display = (document.getElementById('sub-header').style.display == 'block') ? 'none' : 'block';
	if (document.getElementById('header').style.display == '') {document.getElementById('header').style.display = 'block';} 
	document.getElementById('header').style.display = (document.getElementById('header').style.display == 'block') ? 'none' : 'block';
	
	if (document.getElementById('menu_cart')) {
		document.getElementById('menu_cart').style.marginTop = (document.getElementById('sub-header').style.display == 'block') ? '120px' : '0px';
		document.getElementById('menu_cat').style.marginTop = (document.getElementById('sub-header').style.display == 'block') ? '120px' : '0px';
	}
	
	document.getElementById('show_header').style.display = (document.getElementById('show_header').style.display == 'block') ? 'none' : 'block';
}

function footerShowHide() {
	if (document.getElementById('footer').style.display == '') {document.getElementById('footer').style.display = 'block';} 
	document.getElementById('hideshowfooter').innerHTML = (document.getElementById('footer').style.display == 'block') ? 'Show Footer' : 'Hide Footer';
	document.getElementById('footer').style.display = (document.getElementById('footer').style.display == 'block') ? 'none' : 'block';
}

function loadMenuContent (cat_id, w_id) {
	
	document.getElementById('cat_'+cat_select).setAttribute("class", "menu-category-select");
	document.getElementById('cat_'+cat_id).setAttribute("class", "menu-category-select-first");
	cat_select = cat_id;
	
	o = {'cat_id': cat_id, 'w_id': w_id}
	
	$('#menu-content').load('modules/ajax/menu_detail.php', o);
}

function addBasket(p_id) {
	// add cart info and create temp user if not logged in
	o = {'p_id': p_id};
	$('#basket-detail').load("modules/ajax/add_basket.php", o);
}

function loadBasket(crt_id) {
	//loadExtras(<?=$crt_id?>, 'extras', true, this);
	// if on load Extras then keep crt_id to keep the basket item on top of the background div
	o = {'crt_id': crt_id}
	
	// output basket lines
	$('#basket-detail').load('modules/ajax/load_basket.php', o);
	// output basket discount
	$('#basket-discount').load('modules/ajax/discount_basket.php');
	// output basket total
	$('#basket-total').load('modules/ajax/total_basket.php');
	// output mini basket by statusbar
	$('#mini-cart').load('modules/ajax/total_basket.php');
	
	cart_id = $('#cart_id_options').html();
	//alert(cart_id);
	//loadExtras(cart_id, 'extras', true, this);
}

function removeBasket(crt_id) {
	// remove item line from basket
	order_build_remove_product(crt_id);
}

function loadExtraDetail (id_val) {
	parentID = 'line_'+id_val;
	
	document.getElementById('anchor_'+id_val).style.display = 'none';
	document.getElementById('remove_'+id_val).style.display = 'none';	
	
	//createDiv('extra_detail', parentID, document.getElementById(parentID).innerHTML);
	//document.getElementById('extra_detail').style.top = document.getElementById(parentID).offsetTop+'px';
	//document.getElementById('extra_detail').style.left = document.getElementById(parentID).offsetLeft+'px';
	//document.getElementById('extra_detail').style.height = document.getElementById(parentID).offsetHeight+'px';
	//document.getElementById('extra_detail').style.width = document.getElementById(parentID).offsetWidth+'px';
}
function loadNewExtras(crt_id, opt, val, el) {
	
	id_val = el.id.substr(7);
	
	//loadExtraDetail(id_val);
	
	//backgroundBox();
	
	document.getElementById('mainpage-box').style.top = '100px';
	// get tge left position with left of container and left of menu-content
	extrabox = Math.round(document.getElementById('menu-content').offsetLeft+document.getElementById('container').offsetLeft)-87+'px';
	// set to the position next to the basket div
	document.getElementById('mainpage-box').style.left = extrabox
	//document.getElementById('mainpage-box').style.width = document.getElementById('menu-content').offsetWidth+'px';
	alert('hello');
	if (opt == 'options') {
		$.shadowbox.load('modules/customer_id/ajax/order-build.php',{'crt_id': crt_id, 'options': val},true, {'width': 960, 'height': 450, 'title': 'Choose Your Options'});
	} else {
		$.shadowbox.load('modules/customer_id/ajax/order-build.php',{'crt_id': crt_id, 'extras': val},true, {'width': 960, 'height': 450, 'title': 'Choose Your Extras'});
	}
	
	//loadBasket(crt_id);
	//setBoxScrollDiv();
	//addMainBoxTitle('none'); // wait for ajax to load before adding the close button
}
function loadExtras(crt_id, opt, val, el) {

	id_val = el.id.substr(7);
	
	//loadExtraDetail(id_val);
	
	//backgroundBox();
	
	document.getElementById('mainpage-box').style.top = '100px';
	// get tge left position with left of container and left of menu-content
	extrabox = Math.round(document.getElementById('menu-content').offsetLeft+document.getElementById('container').offsetLeft)-87+'px';
	// set to the position next to the basket div
	document.getElementById('mainpage-box').style.left = extrabox
	//document.getElementById('mainpage-box').style.width = document.getElementById('menu-content').offsetWidth+'px';
	
	if (opt == 'options') {
		$.shadowbox.load('modules/customer_id/ajax/order-build.php',{'crt_id': crt_id, 'options': val},true, {'width': 960, 'height': 450, 'title': 'Choose Your Options'});
	} else {
		$.shadowbox.load('modules/customer_id/ajax/order-build.php',{'crt_id': crt_id, 'extras': val},true, {'width': 960, 'height': 450, 'title': 'Choose Your Extras'});
	}
	//setBoxScrollDiv();
	//addMainBoxTitle('none'); // wait for ajax to load before adding the close button
}
function closeShadowbox(){
	//alert('close this');
	window.parent.$.shadowbox.hide();
}

function refreshShadowbox(crt_id,option){
	$.shadowbox.load('modules/customer_id/ajax/order-build.php',{'crt_id': crt_id, 'options': option},true, {'width': 940, 'height': 450, 'title': 'Choose Your Options'});
}

function signOut() {
	
	o = {'innerstatus': document.getElementById('inner-status').innerHTML}
	
	$('#inner-status').load('modules/ajax/logout.php', o);
	
	pg = document.getElementById('page').value;
	if (pg == 'delivery_details') {document.getElementById('page').value = 'menu';}
	if (pg == 'post_new_user') {document.getElementById('page').value = 'menu';}
	if (pg == 'checkout') {document.getElementById('page').value = 'home';}

}

function signIn() {
	o = {'email': document.getElementById('email').value, 'password': document.getElementById('password').value}
	$('#inner-status').load('modules/ajax/load_user.php', o);
}

function checkLogin(rootDir) {
    /*if (document.getElementById('email').value && document.getElementById('password').value) {
        o = {'email': document.getElementById('email').value, 'password': document.getElementById('password').value}
        $('#login-details').load('modules/ajax/login.php', o);
    } */
    //alert('heelo');
   // err = 0;   
   //action     = 'email';     
    email = document.getElementById('email').value;
    password = document.getElementById('password').value;
    ajax = document.getElementById('ajax').value;
    $.ajax({
     type: "POST",
     url: rootDir + '/user_login.php',
     data: {"login_email_address" : email, "login_password" : password, "ajax" : ajax },
     success: function(data){
     if (data == 1) {
        window.location.reload(true); 
     }
     else if(data == "2"){
        window.location = "http://www.feedmeonline.co.uk/modules/update_user.php";
     }
     else {
        $("#signInForm").html("Failure"); 
     }  
     
    }});   
    }

    // New Function for sign up Email field Validation
    function check_signup_email() {
    var signup_email = (document.getElementById('email')) ? document.getElementById('email').value : '';
 
    var email_check = (document.getElementById('email_check')) ? document.getElementById('email_check') : '';
    passImgTick = '&nbsp;<img src="inc/img/icon-general-tick.png" height=15>';
    passImgCross = '&nbsp;<img src="inc/img/icon-general-cross.png" height=15>';
       
    
    if (isValidEmail(signup_email) == true) {
        email_check.innerHTML = passImgTick;
    } else  {
        email_check.innerHTML = (signup_email == '') ? '' :  passImgCross;
    }   
}

    // New Function for forgot Email field Validation
    function check_forgot_email() {
    var forgot_email = (document.getElementById('emailpassword')) ? document.getElementById('emailpassword').value : '';
 
    var email_check = (document.getElementById('email_check_forgot')) ? document.getElementById('email_check_forgot') : '';
    passImgTick  = '&nbsp;<img src="inc/img/icon-general-tick.png" height=15>';
    passImgCross = '&nbsp;<img src="inc/img/icon-general-cross.png" height=15>';
       
    
    if (isValidEmail(forgot_email) == true) {
        email_check.innerHTML = passImgTick;
    } else  {
        email_check.innerHTML = (forgot_email == '') ? '' :  passImgCross;
    }   
}


    


function getPassword() {
	o = {'forgot': document.getElementById('email').value};
	$('#login-details').load('modules/forgot_password.php', o);
}

// Modified for new post login Program
function sendPasswordReset (rootDir) {
	o = {'send': (document.getElementById('emailpassword')) ? document.getElementById('emailpassword').value : ''}
    $('#signInForm').load(rootDir+'/post_login.php', o);
}

function isValidPostcode(p) {
	if (p != '') {
		var postcodeReg = /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/i;
		return postcodeReg.test(p);
	} else {
		return false;
	}
}

function isValidEmail(e) {
	if (e != '') {
		var emailReg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		return emailReg.test(e);
	} else {
		return false;
	}
}

function passwordChanged(el, evt, action) {
	var strength = document.getElementById('strength');
	var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\W).*$", "g");
	var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
	var enoughRegex = new RegExp("(?=.{6,}).*", "g");
	var pwd = document.getElementById("register_password");
	if (pwd.value.length==0) {
		document.getElementById('strength').style.background = "#ffffff";
		document.getElementById('strength').style.color = "#ff0000";
		strength.innerHTML = 'No Password';
	} else if (false == enoughRegex.test(pwd.value)) {
		document.getElementById('strength').style.background = "#ffffff";
		document.getElementById('strength').style.color = "#ff0000";
		strength.innerHTML = 'More Characters';
	} else if (strongRegex.test(pwd.value)) {
		document.getElementById('strength').style.background = "#009900";
		document.getElementById('strength').style.color = "#ffffff";
		strength.innerHTML = 'Strong';
	} else if (mediumRegex.test(pwd.value)) {
		document.getElementById('strength').style.background = "#999955";
		document.getElementById('strength').style.color = "#ffffff";
		strength.innerHTML = 'Medium';
	} else { 
		document.getElementById('strength').style.background = "#ff0000";
		document.getElementById('strength').style.color = "#ffffff";
		strength.innerHTML = 'Weak';
	}
	if (action == 'password') {
		if (KeyCheck(evt) == 13) {
			changePassword();
		}
	} else {
		check_Register(el, evt);
	} 
}

function check_Register(el, evt, action) {
	
	var submitform = 0;
	if (KeyCheck(evt) == 13 || el.innerHTML == 'Update' || el.innerHTML == 'Register' || el.innerHTML == 'Confirm'  || el.innerHTML == 'Card'  || el.innerHTML == 'Cash') {submitform = 1;}
	
	if (el.value != '') {el.style.background = '#fff'; el.style.color = '#000';}
	
	reg_name = (document.getElementById('register_name')) ? document.getElementById('register_name').value : '';
	reg_email = (document.getElementById('register_email')) ? document.getElementById('register_email').value : '';
	reg_pass = '';
	if (document.getElementById('register_password')) {
		reg_pass = (document.getElementById('register_password')) ? document.getElementById('register_password').value : '';
		reg_pass2 = (document.getElementById('register_password2')) ? document.getElementById('register_password2').value : '';
	}
	reg_house = (document.getElementById('register_house')) ? document.getElementById('register_house').value : '';
	reg_address = (document.getElementById('register_address')) ? document.getElementById('register_address').value : '';
	reg_postcode = (document.getElementById('register_postcode')) ? document.getElementById('register_postcode').value : '';
	reg_tel = (document.getElementById('register_tel')) ? document.getElementById('register_tel').value : '';
	newsletter = (document.getElementById('newsletter')) ? document.getElementById('newsletter').checked : '';
	comments = (document.getElementById('comments')) ? document.getElementById('comments').value : '';
	type = (document.getElementById('type')) ? document.getElementById('type').value : '';
	if(el.innerHTML == 'Card'  || el.innerHTML == 'Cash'){
		if(el.innerHTML=='Card'){payment_type='2'}
		if(el.innerHTML=='Cash'){payment_type='1'}
	} else {
		payment_type = '';	
	}
	delivery_time = (document.getElementById('delivery_time')) ? document.getElementById('delivery_time').value : '';
	
	// if on delivery screen then pass through div_id 
	div_id='';
	if (el.innerHTML == 'Confirm' || el.innerHTML == 'Card' || el.innerHTML == 'Cash') {div_id = 'delivery_details_content';}
	//if (el.innerHTML == 'Confirm') {div_id = 'delivery_details_content';}
	
	updateuser =(action == 'update') ? true : false;
	
	// pass through with a object if updating
	o = {'register_title': document.getElementById('register_title').value,
		'register_name': reg_name, 
		'register_password': reg_pass, 
		'register_email': reg_email, 
		'register_house': reg_house,
		'register_address': reg_address,
		'register_postcode': reg_postcode,
		'register_tel': reg_tel,
		'register_mobile': document.getElementById('register_mobile').value,
		'newsletter': newsletter,
		'comments': comments,
		'type': type,
		'payment_type': payment_type,
		'delivery_time': delivery_time,
		'update': updateuser,
		'div_id': div_id}
	
	var email_check = (document.getElementById('email_check')) ? document.getElementById('email_check') : '';
	var pass_check = (document.getElementById('pass_check')) ? document.getElementById('pass_check') : '';
	var postcode_check = (document.getElementById('postcode_check')) ? document.getElementById('postcode_check') : '';
	passImgTick = '&nbsp;<img src="inc/img/icon-general-tick.png" height=15>';
	passImgCross = '&nbsp;<img src="inc/img/icon-general-cross.png" height=15>';
		
	submitReg = true;
	updateUser = true;
	    
	if (reg_name == '') {submitReg=false; updateUser=false;}
	if (reg_address == '') {submitReg=false; updateUser=false;}
	if (reg_tel == '') {submitReg=false; updateUser=false;}
	if (reg_house == '') {submitReg=false; updateUser=false;}
	
	if (isValidPostcode(reg_postcode) == true) {
		postcode_check.innerHTML = passImgTick;
	} else {
		submitReg = false; 
		updateUser=false;
		postcode_check.innerHTML = (reg_postcode == '') ? '' : passImgCross;
	}
	
	if (isValidEmail(reg_email) == true) {
		email_check.innerHTML = passImgTick;
	} else  {
		submitReg = false; 
		updateUser=false;
		email_check.innerHTML = (reg_email == '') ? '' :  passImgCross;
	}
	
	if (document.getElementById('register_password')) {
		if ((reg_pass == reg_pass2) && reg_pass.length >= 6) {
			pass_check.innerHTML = passImgTick;
		} else {
			submitReg = false; 
			pass_check.innerHTML = (reg_pass == '') ? '' :  passImgCross;
		}
	}
	
	if (submitReg == true) {
		if (action == 'submit' && submitform == 1) {
			if (document.getElementById('prev_page').value = 'order_register') {
				if (document.getElementById('page') != 'order_register') { // set area to postcode that customer has entered when registering outside checkout
					document.getElementById('postcode').value = document.getElementById('register_postcode').value;
				}
				//alert('submitted');
				loadPage("post_new_user", getParams(), document.register_form);
			} else {
			}
		} else {
			document.getElementById('reg_msg').innerHTML = errorMsg(document.register_form);
		}
	}
	
	if (updateUser == true) {
		//alert(action +" , "+ submitform);
		//alert();
		if ((action == 'update' || action == 'news_signup') && submitform == 1) {
			if (el.innerHTML == 'Confirm' || el.innerHTML == 'Card' || el.innerHTML == 'Cash') {
				//alert('confirm');
				//alert('confirm');
			//if (el.innerHTML == 'Confirm') {
				
				$('#delivery_details_content').load('modules/post_new_user.php', o);
			} else {
				loadMainBox('modules/post_new_user.php', o, 'User update');
			}
		}
	} else {
		document.getElementById('reg_msg').innerHTML = errorMsg(document.register_form);
	}
	
}

function errorMsg(form) {
	//alert(form);
	for ( var i = 0; i < form.elements.length; ++i ) {
		var fld = form.elements[i];
		if (fld.type == 'password' || fld.type == 'text' || fld.type != "textarea") {
			if (fld.name != 'register_title' && fld.name != 'register_mobile') {
				if (fld.value == '') {fld.style.background = '#f99'; fld.style.color = '#fff';}
			}
		}
	}
	return '';//Remove error msg'<b class="warn-message">(Please Enter in all needed fields to continue)</b>';
}

function loadShops(term, search, postc) { 
	o = {'term': term, 'search': search, 'postcode': postc}
	$('#wholesaler-list-content').load('modules/ajax/load_shops.php', o); 
}

function finalPayment () {
	ptype = document.getElementById('payment_type').value;
	dhouse = document.getElementById('register_house').value;
	daddress = document.getElementById('register_address').value;
	dpostcode = document.getElementById('payment_type').value;
	
	process_order = 1;
	message = '';
		
	if (ptype == 0) {process_order=0; message += 'Payment type';}
	if (dhouse == '' || daddress == '' || dpostcode == '') {process_order=0; if (message != '') {message += ' and '} message += 'Address details';}
	if (message != '') {message += ' needed to process this order.<br />'}
	
	o = {'message': message, 'type': ptype}
	
	if (process_order == 1) {
		//alert('process order 1');
		// go to checkout page
		loadPage('checkout', getParams(), document.register_form);
	} else {
		//alert('go back');
		// return back to delivery details if the details entered are incorrect
		$('#payment-details').load('modules/ajax/payment_type.php', o);
	}
}

function card_payment(el, evt, action){
	var type = '2';
	$('input:hidden[name=payment_type]').val(type);
	check_Register(el, evt, action);
	//check_Register(el, evt, action);
}

function cash_payment(el, evt, action){
	var type = '1';
	$('input:hidden[name=payment_type]').val(type);
	check_Register(el, evt, action);
	//check_Register(el, evt, action);
}

function loadRegisterForm (evt) {  
	if (document.getElementById('news_email').disabled == false) {
		var email = (document.getElementById('news_email')) ? document.getElementById('news_email').value : '';
		pcode1 = (document.getElementById('news_pcode1')) ? document.getElementById('news_pcode1').value : '';
		pcode2 = (document.getElementById('news_pcode2')) ? document.getElementById('news_pcode2').value : '';
        
		if (document.getElementById('news_email').value == 'Your Email Address') {document.getElementById('news_email').value = '';}
		if (document.getElementById('news_pcode1').value == 'Eg: SK7') {document.getElementById('news_pcode1').value = '';}
		if (document.getElementById('news_pcode2').value == 'Eg: 5HQ') {document.getElementById('news_pcode2').value = '';}
	
		document.getElementById('mainpage-box').innerHTML = "";
	
		o = {'email': escape(email), 'pcode1': escape(pcode1), 'pcode2': escape(pcode2), 'newsletter': 'true'}
		pos = {'evt': evt, 'positionX': 'right', 'positionY': 'top'}
	
		if (document.getElementById('news_email').value == '' || document.getElementById('news_pcode1').value == '' || document.getElementById('news_pcode2').value == '') {
			alert('Please enter in all the fields.');
			if (document.getElementById('news_email').value == '') {document.getElementById('news_email').value = 'Your Email Address';}
			document.getElementById('news_email').className = document.getElementById('news_email').className = 'pre-input-text input-width-long';
			if (document.getElementById('news_pcode1').value == '') {document.getElementById('news_pcode1').value = 'Eg: SK7';}
			document.getElementById('news_pcode1').className = document.getElementById('news_pcode1').className = 'pre-input-text input-width-short';
			if (document.getElementById('news_pcode2').value == '') {document.getElementById('news_pcode2').value = 'Eg: 5HQ';}
			document.getElementById('news_pcode2').className = document.getElementById('news_pcode2').className = 'pre-input-text input-width-short';
		} else {  
			
            $("#subscribe").load('modules/ajax/add_user.php', o, 'Add User', pos);
           // loadMainBox('modules/ajax/add_user.php', o, 'Add User', pos);
		}
	} else {
		alert('Log out before you may apply for the newsletter.');  
	}
}


function viewUserOrders (uid) {
	loadMainBox('modules/orders_reports/list.php', {}, 'Orders');
}

function viewUserOrder (w_id, o_id, start) {
	o = {'w_id': w_id, 'id': o_id, 'ref': escape('list.php?start='+start)}
	loadMainBox('modules/orders_reports/vieworder.php', o, 'Order - '+o_id);
}

function getOrder (oid, wid) {
	o = {'oid': oid, 'wid': wid}
	loadMainBox('modules/common/ssi/convert_order_to_cart.php', o, 'Get order');
}

function updateUserDetails (div_id) {
	if (!div_id) {
		o = {'update': true, 'change_password': true};
		loadMainBox('modules/ajax/register_form.php', o, 'Update user');
	} else {
		o = {'update': true, 'div_id': div_id};
		$("#"+div_id).load("modules/ajax/register_form.php", o);
	}
}

function changePassword(AP_UID) {
	
	if (AP_UID) {
		o = {'uid': AP_UID,
			'new_password': document.getElementById('register_password') ? document.getElementById('register_password').value : '',
			'confirm_password': document.getElementById('register_password2') ? document.getElementById('register_password2').value : ''}
	
		$('#container').load('passwordReset_markup.php', o);
	} else {
		o = {'old_password': document.getElementById('register_old_password') ? document.getElementById('register_old_password').value : '',
			'new_password': document.getElementById('register_password') ? document.getElementById('register_password').value : '',
			'confirm_password': document.getElementById('register_password2') ? document.getElementById('register_password2').value : ''}
	
		loadMainBox('modules/ajax/change_password.php', o, 'Change password');
	}
}

function cancelCheckout(oid, status, payment_type, type, delivery_time, comments, register_house, register_address, register_postcode) {
	//o = {'oid': oid, 'page': 'checkout', 'status': status, 'payment_type': payment_type}
	//$('#finalPayment').load('modules/ajax/finalPayment.php', o);
	o = {'oid':oid }
	$('#order_status').load('modules/ajax/cancel_order.php', o, function(){
		status = $('#order_status').html();								
		reloadCheckout(oid,status,payment_type,type,delivery_time,comments,register_house,register_address,register_postcode);
	});
	
}

//function proceed_to_order_checkout(oid,sha_oid){
	//alert(oid + ',' +sha_oid);
//	$('#finalPayment').load('modules/ajax/finalPayment.php', {'oid' : oid, 'sha_oid' : sha_oid}); 	
//}

function checkOrderStatus(oid, status, payment_type, type, delivery_time, comments, register_house, register_address, register_postcode){
		o = {'oid':oid }
		$('#order_status').load('modules/ajax/check_order_status.php', o, function(){
			status = $('#order_status').html();								
			if(status=='accepted' || status=='declined'){
				//setTimeout("reloadCheckout('"+oid+"', '"+status+"',' "+payment_type+"',' "+type+"',' "+delivery_time+"',' "+comments+"',' "+register_house+"',' "+register_address+"',' "+register_postcode+"')",5000);
				reloadCheckout(oid,status,payment_type,type,delivery_time,comments,register_house,register_address,register_postcode);
			} else {
				setTimeout("checkOrderStatus('"+oid+"', '"+status+"',' "+payment_type+"',' "+type+"',' "+delivery_time+"',' "+comments+"',' "+register_house+"',' "+register_address+"',' "+register_postcode+"')",5000);	
			}
		});
}

function reloadCheckout(oid, status, payment_type, type, delivery_time, comments, register_house, register_address, register_postcode) {
	o = {'oid':oid,
		'page':'checkout',
		'status':status,
		'payment_type':payment_type,
		'type':type,
		'delivery_time':"'"+delivery_time+"'",
		'comments':comments,
		'register_house':register_house,
		'register_address':register_address,
		'register_postcode':register_postcode}
	$('#finalPayment').load('modules/ajax/finalPayment.php', o);
}

function lookupTakeaways(search) {
	// create the div within the container element
	createDiv('lookup_takeaway', 'container');
	o = {'search': search}
	
	if (search.length >= 2) {
		$('#lookup_takeaway').load('modules/ajax/lookup_takeaway.php', o);
	} else {
		if (document.getElementById('lookup_takeaway')) {removeDiv('lookup_takeaway');}
	}
}

function addFavorites(oid, status, name) {
	createDiv('favorites', 'mainpage-box');
	
	if (!name) {name='';}
	
	o = {'oid': oid, 'status': status, 'name': name}
	$('#favorites').load('modules/ajax/favorites.php', o);
}

function viewFavorites() {
	o = {'status': 'list'}
	loadMainBox('modules/ajax/favorites.php', o, 'Favorites');	
}

function loadGames() {
	loadMainBox('modules/games.php', {}, 'Spot the difference');
}

function saveFeedback(rootDir) {
	//alert('hello');
	//alert(isemail + " , " + name + " , " +email + " , " +message + " , " +action);
	err = 0;
	document.getElementById('main_error').style.display = 'none';
	document.getElementById('email2_error').style.display = 'none';	
	var email 	= document.feedback.email.value;
	isemail = isValidEmail(email);
	name 	= document.feedback.name.value;
	message = document.feedback.message.value;
	//isemail = isemail;
	action 	= 'email';
	if(name!=''){
		document.getElementById('name_error').style.display = 'none';	
	} else {
		document.getElementById('name_error').style.display = '';	
		err = 1;
	}
	//alert(isemail);
	if(email!=''){
		document.getElementById('email_error').style.display = 'none';	
	} else {
		document.getElementById('email_error').style.display = '';	
		err = 1;
	}
	if(isemail == false){
		document.getElementById('email2_error').style.display = '';	
		document.getElementById('email_error').style.display = '';	
		err = 1;
	} else {
		document.getElementById('email2_error').style.display = 'none';	
		document.getElementById('email_error').style.display = 'none';	
		
	}
	if(message!=''){
		document.getElementById('feedback_error').style.display = 'none';	
	} else {
		document.getElementById('feedback_error').style.display = '';	
		err = 1;
	}
	//alert(isemail + " , " + name + " , " +email + " , " +message + " , " +action);
	//alert(err);
	spam = 1;
	if(err == 0){
		//return true;	
		$('#centre-info-box').load(rootDir+'/ajax/send_feedback.php',{ 'name': name, 'email' : email, 'message' : message, 'spam' : spam });
		return false;
	} else {
		document.getElementById('main_error').style.display = '';
		return false;	
	}
	
	//alert('hello');
	//$('#mainpage-box').load('modules/feedback.php', o);
	//setTimeout('addMainBoxTitle("");', 300); // wait for ajax to load before adding the close button
	
	//$.shadowbox.load(rootDir+'/games.php', {shadowbox: true},true, {title: 'About Us', width: 580, height:430});
	
}

$(function () {
            var tabContainers = $('div.tabs > div');
            tabContainers.hide().filter(':first').show();
            
            $('div.tabs ul.tabNavigation a').click(function () {
                tabContainers.hide();
                tabContainers.filter(this.hash).show();
                $('div.tabs ul.tabNavigation a').removeClass('selected');
                $(this).addClass('selected');
                return false;
            }).filter(':first').click();
});
        
function map_toggle(){
    $('#searchMapLocation').show("slow");
    $('#locationSelect').show("slow");     
    $('#geoList').show("slow");
    $('#mapViewButton').addClass("selected");
    $('#listViewButton').removeClass('selected');    
    $('#searchListView').hide("slow");    
    $('#geoList').show("slow");
    $('#map').css("position" , "relative" );    
    $('#map').css("left" , "0px" );
}

function list_toggle(){
    $('#searchListView').show("slow");     
    $('#locationSelect').hide("slow");
    $('#geoList').hide("slow");
    $('#listViewButton').addClass("selected");
    $('#mapViewButton').removeClass('selected'); 
    $('#searchMapLocation').hide("slow");
    $('#map').css("position" , "absolute" );    
    $('#map').css("left" , "-10000px" );   
}


// JS FOR MAP LOCATOR
var map;
var markers = [];
var infoWindow;
var locationSelect;

function loadMap() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: new google.maps.LatLng(53.771297, -1.548742),
        zoom: 5,
        mapTypeId: 'roadmap',
        mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR}
      });
      infoWindow = new google.maps.InfoWindow();

      locationSelect = document.getElementById("locationSelect");
      locationSelect.onchange = function() {
      var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
      if (markerNum != "none"){
      google.maps.event.trigger(markers[markerNum], 'click');
        }
      };
   }

   function searchLocations() {
     var address = document.getElementById("sideBoxSearch").value;
     var geocoder = new google.maps.Geocoder();
     geocoder.geocode({address: address}, function(results, status) {
       if (status == google.maps.GeocoderStatus.OK) {

        searchLocationsNear(results[0].geometry.location);
       } else {
         //alert(address + ' not found');
       }
     });
   }

   function clearLocations() {
     infoWindow.close();
     var address = document.getElementById("sideBoxSearch").value; 
     for (var i = 0; i < markers.length; i++) {
       markers[i].setMap(null);
     }
     markers.length = 0;

     locationSelect.innerHTML = "";
     var option = document.createElement("option");
     option.value = "none";
     option.innerHTML = "Other Takeaways In Near " + address;
     locationSelect.appendChild(option);
   }

   function searchLocationsNear(center) {
     clearLocations(); 

     var radius = 3;
     var searchUrl = '/search/geo_locator.php?geo_lat=' + center.lat() + '&geo_lng=' + center.lng() + '&radius=' + radius;
     downloadUrl(searchUrl, function(data) { 
       var xml = parseXml(data);
       var markerNodes = xml.documentElement.getElementsByTagName("marker");
       var bounds = new google.maps.LatLngBounds();
       for (var i = 0; i < markerNodes.length; i++) {
       // Get Values For Popwindow 
         var name = markerNodes[i].getAttribute("name");
         var slug = markerNodes[i].getAttribute("slug");
         var address = markerNodes[i].getAttribute("address");          
         var postcode = markerNodes[i].getAttribute("geo_post_code");
         var distance = parseFloat(markerNodes[i].getAttribute("distance"));
         var latlng = new google.maps.LatLng(
              parseFloat(markerNodes[i].getAttribute("wholesaler_lat")),
              parseFloat(markerNodes[i].getAttribute("wholesaler_long"))); 
         createOption(name, distance, i);
         createMarker(latlng, name, address, postcode, slug, distance);
         bounds.extend(latlng);
       }
       map.fitBounds(bounds);
       locationSelect.style.visibility = "visible";
       locationSelect.onchange = function() {
         var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
         google.maps.event.trigger(markers[markerNum], 'click');
       };
      });
      var pcode = document.getElementById("sideBoxSearch").value; 
      $.ajax({
     type: "POST",
     url: "../search/ajax/shop_distance_list.php",
     data: {"geo_lat" : center.lat(), "geo_lng" :center.lng(), "pcode" : pcode},
     success: function(data){
     $("#geoList").html(data);      
     }
     });

    }

    function createMarker(latlng, name, address, postcode, slug, distance) { 
      var takeaway_region = document.getElementById("takeAwaySearchRegion").value;  
      var user_pcode = document.getElementById("sideBoxSearch").value;  
      // Build Pop up window of details
      var getDirections = document.getElementById('sideBoxSearch').value;
      var html = "<b><a href=/takeaways/index.php?route=" + takeaway_region + "/" + user_pcode + "/" + slug +">" + name + "</a></b> <br/>" + address + "<br/>" + postcode
      + "<br/><a target='_blank' href=http://maps.google.com/maps?saddr=" + getDirections.replace(' ','') + "&nbsp;united&nbsp;kingdom&daddr=" + postcode.replace(' ','&nbsp;')+ '&nbsp;united&nbsp;kingdom' + ">Get Directions</a>";  
      var image = "/inc/img/fmo_marker.png";
      var marker = new google.maps.Marker({
        map: map,
        position: latlng,
        icon: image
      });
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
      markers.push(marker);
    }

    function createOption(name, distance, num) {
      var option = document.createElement("option");
      option.value = num;
      option.innerHTML = name + " (" + distance.toFixed(1) + " Miles from your location)";
      locationSelect.appendChild(option);
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request.responseText, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function parseXml(str) {
      if (window.ActiveXObject) {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.loadXML(str);
        return doc;
      } else if (window.DOMParser) {
        return (new DOMParser).parseFromString(str, 'text/xml');
      }
    }

    function doNothing() {}  




