// =m1_full_site
var host = window.location.host; //console.log(host);
var total = 0; //cart
var ship_cost = 1.5; //cart
var ship_desc = ' (Worldwide)';
var clicked_this = ""; //making the clicked element available outside the fun
var page_reload_count = 0;
// products_json[id] - [0=therapy_name,1=introductory_price,2=pp_row,3=desc,4=cat,5=subcat]
var pj = products_json;
var slide_speed = (document.domain == 'choicehealthmag.com')? 1000 : 0;
var window_width;
var window_height;
var pathname = window.location.pathname;
var jqxhr_data = {}; //login ajax data

// =full site ===================================================================================
$(function(){
	window_width = $(window).width();
	window_height = $(window).height();
	
	if_logged_in_do_these();
	if(window.location.search == '?paypal=sandbox'){cookie_write('paypal','sandbox');}
	
	$('a[rel="close"]').click(function(e){//close button
		e.preventDefault(); 
		$(this).parent().slideUp(slide_speed);
		var parent_id = $(this).parent().attr('id');
		if(parent_id == 'subscription_table') $('#index #gallery').slideDown(slide_speed);
	});
	
	$('div#header').click(function(){window.location.href = 'index.php'; /*window.location.replace('index.php');*/}); //make whole =header clickable
	
// auto click based on url -----------------------------------
	

// END auto click based on url -----------------------------------
	
// =menu clicking  -------------------------------
	function open_close_blocks(target,page_link){ //opening and closing blocks inside the #replace div. Making sure they are not downloaded again and again.
		$('#replace>div').slideUp(slide_speed,function(){
			if($(target).length == 0){
				$.get('_includes/page/'+page_link,function(d){
					$('#replace').css('display','none').append(d).slideDown(slide_speed);
				});
			}
			else {$(target).slideDown(slide_speed);}
		});
	}
	
	$('a[href*=logout]').click(function(e){// click menu logout
		e.preventDefault();
		cookie_write('logged_in','',-1);
		cookie_write('logged_in_c','',-1);
		cookie_write('email','',-1);
		cookie_write('free_copy_issue','',-1);
		$(this).parent().slideUp(1000);
	})
	
	$('#nav_main a[rev=link]').click(function(){// click menu link
		open_close_blocks('#link','link.php');
	});
	if(pathname.search(/\/link/i) >= 0) {
		open_close_blocks('#link','link.php');
	}
	
	$('#nav_main a[rev=workshops]').click(function(){// click menu workshops
		open_close_blocks('#workshops','workshops.php');
	});
	if(pathname.search(/\/workshops/i) >= 0) {
		open_close_blocks('#workshops','workshops.php');
	}
	
	$('#nav_main a[rev=media_information]').click(function(){// click menu workshops
		open_close_blocks('#media_information','media_information.html');
	});
	if(pathname.search(/\/media_information/i) >= 0) {
		open_close_blocks('#media_information','media_information.html');
	}
	
	$('#nav_main a[href*="index.php"]').click(function(e){// click menu index.php
		if($('#index').length == 0){}//reloads to index.php
		else {//#index exists
			e.preventDefault(); 
			if($('#index').is(':visible')){//visible
				if($('#index iframe').length > 0){//youtube videos are showing
					$('#index #gallery').slideUp(1000,function(){
						$("div#makeMeScrollable").smoothDivScroll("replaceContent","z_scrollableArea_content.php");
						$('#index #gallery').slideDown(1000,function(){});
					});
				}
			}
			if($('#index').is(':hidden')){
				$('#replace>div').slideUp(slide_speed);
				$('#replace #index').slideDown(slide_speed);
			}
		}
	});
	
	$('#nav_main a[href*="audio_seminars"]').click(function(e){// click menu audio_seminars
		e.preventDefault();
		clicked_this = '#nav_main a[href*="audio_seminars"]';
		if(cookie_read('logged_in')){
			open_close_blocks('#audio_seminars','audio_seminars.html');
		}
		else {$('#login').dialog('open');}
	});
	
	$('#nav_main a[href*="videos"]').click(function(e){// click menu videos
		e.preventDefault(); 
		clicked_this = '#nav_main a[href*="videos"]';
		if(cookie_read('logged_in')){
			if((window.location.pathname == '/index.php') || (window.location.pathname == '/')){
				if($('#index').is(':hidden')){
					$('#replace>div').slideUp(500);
					$('#replace #index').slideDown(500);	
				}
				$('#index #gallery').slideUp(1000,function(){
					$("div#makeMeScrollable").smoothDivScroll("replaceContent","z_videos.html");
					$('#index #gallery').slideDown(1000,function(){});
				});
			}
			else {
				window.location.href = 'index.php?c=videos';	
			}
		}
		else { // logging a user in ---
			$('#login').dialog('open');
		}// END logging a user in ---
	});
	
	$("a[href*='order_a_free_copy']").click(function(e){// click menu order a free mag
		e.preventDefault();
		clicked_this = "a[href*='order_a_free_copy']";
		if(!cookie_read('free_copy_issue')) {
			$('#login div.i_need_hard_copy').slideDown();
			$('#login').dialog('open');
		}
		else $('#download_links').html("<a href='download/mag/choicehealthmag.com_issue_"+cookie_read('free_copy_issue')+".pdf'>Download Free Copy</a>").dialog('open');
	});
	
	$('a[rel=partner_login]').click(function(e) {
		clicked_this = 'a[rel=partner_login]';
		free_hard_copy_section_hide();
        partner_login_register();
    });
	
	$('a[rel=partner_register]').click(function(e) {
		clicked_this = 'a[rel=partner_register]';
		free_hard_copy_section_show();
        partner_login_register();
    });
	
	function partner_login_register(){
		$('#login .i_need_hard_copy').hide();
		$('#login').dialog('open');
	}
	
	function free_hard_copy_section_show(){
		if($('#login #free_hard_copy_section') >= 1){}
		else {$('#login .main').append($('#free_hard_copy_section'));}
		$('#free_hard_copy_section').show();
	}
	
	function free_hard_copy_section_hide(){
		$('#free_hard_copy_section').hide();
		if($('#login #free_hard_copy_section') <= 0){}
		else {$('#page').append($('#free_hard_copy_section'));}
	}
	
	var form_free_hard_copy_section = $('form #free_hard_copy_section');
	$('select#country_free_copies',form_free_hard_copy_section).change(function(){//login/order a free mag/register - if uk is unselected then remove uk county option
		if($(this).val() == 'UK') {
			$('.county_free_copies',form_free_hard_copy_section).show().find('select').removeClass().addClass('required');
			$('.state_free_copies',form_free_hard_copy_section).hide().find('input').removeClass();	
		}
		else {
			$('.county_free_copies',form_free_hard_copy_section).hide().find('select').removeClass();
			$('.state_free_copies',form_free_hard_copy_section).show().find('input').removeClass().addClass('required');
		}
	});
	
  // END =menu clicking -------------------------------
// END =login ******************************************************************************
	
	// =menu ****************************************************************************************
		var menu_height = $('#nav_main').outerHeight(); // position menu on center of screen
		var top_position_of_menu = (window_height - menu_height) / 2;
		$('#nav_main').css('opacity',0).animate({'top':top_position_of_menu + 'px','opacity':1},slide_speed);
	// END =menu ****************************************************************************************
	
	function if_logged_in_do_these(){// do on each refresh
		if(cookie_read('logged_in')) {
			var email = cookie_read('email');
			email = email.replace('@',' @');
			$('#nav_main #logged_in span').text(email);
			$('#nav_main #logged_in').show();
		}
	}

// =contact =validate ****************************************************************************
	$("#form_contact,#login").validate({
		rules:{
			email: {email:true}
		}	
	});
// END =contact ****************************************************************************

$( "#tabs" ).tabs();
// window.location
//console.log('hash:',window.location.hash,' host:',window.location.host,' hostname:',window.location.hostname,' href:',window.location.href,' pathname:',window.location.pathname,' port:',window.location.port,' protocol:',window.location.protocol,' search:',window.location.search);

// offset scroll
//console.log("offset.left: ", offset.left, ",offset.top: ", offset.top, ",menu_scrolltop: ", menu_scrolltop, ",toscroll: ", toscroll, ",menu_height: ",menu_height);

/* 	// =del -------------------------
	if(!cookie_read('cookie_reset')){
		cookie_write('cookie_reset',1,364);
		cookie_write('cart','',-1);
	}
	// END =del ------------------------- */// =m2_cart
  // =cart ****************************************************************************************
	$("a.add_to_cart").live("click", function(e) { //.on() is not working here - Adding to cart on clicking add to cart button.
		var id = $(this).attr('rel');
		var ship = ($(this).attr('rev') != undefined)? $(this).attr('rev') : 0;
		cart_create(id,'',false,1,ship);//id_sel,qty_sel,paypal,page_loading,ship//page_loading = 0 means no popup when clicking add to cart
	});
	
	function add_to_cart_button(id){return "<a rel='" + id + "' class='button add_to_cart'>Add to Cart</a>";}
	
	// =dialogs -------------
  	$('#added_to_cart,#download_links').dialog({
		autoOpen   : false,
		position   : ['center',200],
		dialogClass: 'added_to_cart',
		resizable  : false,
		minWidth   : 500,
		minHeight  : 20
	});
	
	$('#download_links').dialog({
		dialogClass: 'download_links'
	});
	// END =dialogs -------------
	
	// cart box user interaction-----------
	$('#cart #cart_full h3 a').click(function(){//empty the cart
		cookie_write('cart','',-1);
		$('#cart').slideUp(700);
	});
	
	$('#cart #cart_small p:last-child a').click(function(e){//cart expand
		$('#cart #cart_small').slideUp(500,function(){
			$('#cart').css('width','700px');
			$('#cart #cart_full').slideDown(700);
		});
	});
	
	$('#cart #cart_full p:last-child a').click(function(e){//cart collapse
		$('#cart #cart_full').slideUp(700,function(){
			$('#cart').css('width','90px');
			$('#cart #cart_small').slideDown(500);
		});
	});
	// END cart box user interaction-----------
	
	if(!cookie_read('cart')){$('#cart').css('display','none');}//if no items in cart, then don't display cart
	else cart_create('','','',0); //0 means page being reloaded, so don't display the dialog saying 'added to cart'
			
	$('#cart #cart_full table tbody').delegate('a','click',function(e){//Cart updating to desired quantity
		e.preventDefault();
		var id = $(this).attr('rel');
		var qty = $(this).parent().parent().find('input').attr('value');
		var ship = $(this).attr('rev');
		cart_create(id,qty,false,0,ship)//id,qty,paypal,page_loading,ship
	});
	
	$('#cart #cart_full p.total').delegate('a','click',function(e){//Sending cart to paypal
		e.preventDefault();
		var cart_full_paypal = cart_create('undefined','undefined',true,0,'');//id_sel,qty_sel,paypal,page_loading,ship
		$('form#paypal_cart .items').html(cart_full_paypal);
		//console.log($('form#paypal_cart .items').html());
		$(this).fadeOut(500,function(){
			$(this).removeClass('button');
			$(this).text('Thank You. Verifying and Sending you to Paypal. Please Wait...').css({'text-decoration':'none','color':'#666'}).fadeIn(500);
		});
		$('#paypal_cart').submit();
	});
			
	function cart_create(id_sel,qty_sel,paypal,page_loading,ship_sel){
		total = 0;
		var cart = cookie_read('cart');
		var cart_new = '';
		var cart_full = '';
		var cart_full_paypal = '';
		ship_sel = (ship_sel == 'ship')? 'ship' : 'no';
		
		if(cart){//cart exists
			var already_in_cart = false;
			cart_a = cart.split(':::');
			
			for(var i=0; i<cart_a.length; i++){//looping thorough all items in cookie
				var cart_a_a = cart_a[i].split('::');
				
				if(cart_a_a[0].charAt(0) == ' ') cart_a_a[0] = cart_a_a[0].substring(1);
				cart_a_a[1] = parseInt(cart_a_a[1]);
				
				if(cart_a_a[0] == id_sel && !paypal) {//updating cookie for an item already in cart
					if(qty_sel == ''){
						cart_a_a[1]++; //incrementing qty by one when the 'add to cart' button is clicked repeatedly
						cart_a_a[2] = ship_sel;	
					}
					else cart_a_a[1] = qty_sel; //adding the exact quantity according to the 'update' link from #cart_full
					already_in_cart = true;	
				}
				
				if(cart_a_a[1] > 0 && cart_a_a[0] != 'undefined'){ //create (cookie and cart) OR (paypal form) for existing items in cookie
					var id = cart_a_a[0];
					var qty = cart_a_a[1];
					var ship = cart_a_a[2];
					if(paypal) cart_full_paypal += cart_full_paypal_html(id,qty,i + 1,ship);//i+1 because paypal starts from 1
					else{
						if(i != 0) cart_new += ':::';
						cart_new += cart_a_a.join('::');
						cart_full += cart_full_html(id,qty,ship);
					}
				}
			} //END looping through items already in the cookie
			
			if(paypal) return cart_full_paypal;
			
			if(!already_in_cart && id_sel && !paypal){ //create cookie and cart for newly added item
				cart_new += ':::' + id_sel + '::1::' + ship_sel;
				cart_full += cart_full_html(id_sel,1,ship_sel);
			}
		}//END if(cart)
		else if(id_sel && !paypal){ //create cookie and cart for a brand new cart
			cart_new = id_sel + "::1::" + ship_sel;
			cart_full += cart_full_html(id_sel,1,ship_sel);
		}
		
		if(cart_new == '' || cart_full == '') $('#cart').slideUp(700); //if cart is empty close it
		else {//only if there is something, show the cart, and add the values
			cookie_write('cart',cart_new,364);
			$('#cart #cart_full tbody').html(cart_full);
			$('#cart #cart_full p.total span,#cart #cart_small p span').text(total.toFixed(2));
			$('#cart').css('display','block');
			
			if(page_loading != 0) $('#added_to_cart').dialog('open'); //0 means - page reload/qty update/go to paypal
			setTimeout("$('#added_to_cart').dialog('close')",2000);
		}
	}/* END function cart_create(id_sel,qty_sel,paypal) */
			
	function cart_full_html(id,qty,ship){
		var price = parseFloat(products_json[id][1]);
		if(ship == 'ship'){
			price +=  parseFloat(ship_cost);
			var ship_this = ship_desc;	
		}
		else{var ship_this = '';}
		if(price == 'NaN') return '';
		qty = parseInt(qty);
		
		var cart_html = "<tr>\n";
		cart_html += "<td>"+products_json[id][0]+ship_this+"</td>\n";//title
		cart_html += "<td>"+price.toFixed(2)+"</td>\n";//price
		cart_html += "<td><input type='text' value='" + qty + "'></td>\n";//qty
		cart_html += "<td>"+(price * qty).toFixed(2)+"</td>\n";//subtotal
		cart_html += "<td><a rel='"+id+"' rev='"+ship+"'>Update</a></td>\n";//update
		cart_html += "</tr>\n\n";
	
		total += qty * price;
		return cart_html;
	}
	
	function cart_full_paypal_html(id,qty,i,ship){
		if(ship == 'ship'){
			var price = parseFloat(ship_cost);
			ship = ship_desc;	
		}
		else{ 
			var price = 0;
			ship = '';
		}
		var cart_html = "<input type='hidden' name='item_name_"+i+"' value='" + products_json[id][0] + ship + "'>\n";//title
		cart_html    += "<input type='hidden' name='item_number_"+i+"' value='" + id + "'>\n";//id
		cart_html    += "<input type='hidden' name='amount_"+i+"' value='" + (parseFloat(products_json[id][1]) + price) + "'>\n";//price
		cart_html    += "<input type='hidden' name='quantity_"+i+"' value='" + qty + "'>\n";//qty
		
		return cart_html;
	}
  // END =cart ************************************************************************************

// END =full site ===================================================================================
// END =m2_cart
// =m3_index
// =index page ******************************************************************************
	// =subscription table ---------------------------------------------------
	$('a[rel="show_subscription_details"]').click(function(e){
		$('#index #gallery').slideUp(1000);
		$('#subscription_table').slideDown(1000)
	;});//show the subscription options table
	if($(window).width() < 1200){$('#index table.price').css({'font-size':'.6em'});} //sub table reduce font size for small windows
	$('#index table.price td:nth-child(2), #index table.price td:nth-child(12)').prepend('&pound;'); // add £ sign
	
	$('#index table.price tbody td:last-child').click(function(e){ //submit to paypal on clicking buy ----
		e.preventDefault();
		var cost = $(this).parent().find('td:nth-child(2)').html();
		cost = parseInt(cost.substr(1,2));
		var issues = parseInt($(this).parent().find('td:nth-child(3)').html());
		var years = $(this).parent().find('td:nth-child(4)').html();
		var msg = 'Subscription to Choice Health Mag - No of Years:' + years + ', Issues:' + issues + '.';
		var therapy_id = $(this).find('a').attr('rel');
		$('#paypal_cart input[name=amount_1]').attr('value',cost);
		$('#paypal_cart input[name=item_name_1]').attr('value',msg);
		$('#paypal_cart input[name=item_number_1]').attr('value',therapy_id);
		$(this).fadeOut(500,function(){$(this).text('Thank You. Verifying and Sending you to Paypal. Please Wait...').css({'text-decoration':'none','color':'#666'}).fadeIn(500);});
		$('#paypal_cart').submit();
	});
	// END =subscription table ---------------------------------------------------
	
	// index - click buy - show backcopies buy options ===========================================
	function frm_buy_process(id){
		var frm_buy = $('#frm_buy');
		
		$('p.soft input',frm_buy).prop('checked',true); //check/select the soft copy option
		id = parseInt(id);
		var id_soft = id + 1;
		$('p.soft input',frm_buy).attr('value',id_soft); //soft copy price
		$('p.soft label span',frm_buy).text(products_json[id_soft][1]);//soft copy price
		if(products_json[id][1] <= 0){//if hard copy is not available (price is -1)
			$('p.hard_uk label, p.hard_row label',frm_buy).text('(Hard Copy not available)').parent().find('input').addClass('display_none');
		}
		else {
			$('p.hard_uk input, p.hard_row input',frm_buy).attr('value',id).removeClass('display_none'); //hard copy price
			$('p.hard_uk label',frm_buy).html("&pound;<span>"+products_json[id][1]+"</span> : Hard Copy (UK only)");//hard copy label
			$('p.hard_row label',frm_buy).html("&pound;<span>"+(parseFloat(products_json[id][1])+ship_cost)+"</span> : Hard Copy (Worldwide)");//hard copy label
		}
		$('a.add_to_cart',frm_buy).attr('rel',id_soft);
	}
	
	$('#gallery a.back_copies_buy_options').click(function(e){
		e.preventDefault();
		var id = $(this).attr('rel');
		
		frm_buy_process(id);
		
		var product = products_json[id][0];
		product = product.replace(' Hard Copy','');
		$('#frm_buy h3').text(product);
		
		$('#frm_buy').slideDown(1000);
	});// END index - click buy - show backcopies buy options =====================================
	
	$('#frm_buy input').live('click',function(){
		$(this).prop('checked',true);
		var id = $(this).attr('value');
		var ship = ($(this).attr('rev') != undefined)? 'ship' : '';
		$('#frm_buy a.add_to_cart').attr({rel:id,rev:ship});
	});
	
	// index slideshow -----------------------------------------------------------------------------
		$("div#makeMeScrollable").smoothDivScroll({
			scrollStep          :10,
			scrollInterval      :1,
			autoScroll          :'onstart',/*always/onstart*/
			autoScrollDirection :'backandforth',/*backandforth/endlessloopleft/endlessloopright*/
			autoScrollStep      :1,
			autoScrollInterval  :50,
			visibleHotSpots     :'always'
		});
		$("div#makeMeScrollable").mouseover(function(){$("#makeMeScrollable").smoothDivScroll("stopAutoScroll");});
		$("div#makeMeScrollable").mouseleave(function(){$("#makeMeScrollable").smoothDivScroll("startAutoScroll");});
		
		var makeMeScrollable_width = $('#gallery').width() - $('#current_issue').width() - 30; //width of scrolling images
		$('#makeMeScrollable').width(makeMeScrollable_width);
	// END index slideshow -----------------------------------------------------------------------------
	
	$('#gallery .issue .visible').hover( // index on hover show buy/subscribe
		function(){$(this).find('p:nth-child(2),p:nth-child(3)').css('visibility','visible');},
		function(){$(this).find('p:nth-child(2),p:nth-child(3)').css('visibility','hidden');}
	);
	
	$("#gallery a:not(.link)").fancybox({
		'opacity'           : true,
		'margin'            : 15,
		'padding'           : 1,
		'overlayColor'      : '#000',
		'overlayOpacity'    : .8,
		'transitionIn'      : 'elastic',
		'transitionOut'     : 'elastic',
		'titlePosition' 	: 'over',
		'cyclic'            : true,
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
						return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' - ' + title : '') + ' (click on left/right of image to see more)</span>';
							  }
	});
// END index **************************************************************************************
//END =m3_index
// =m4_login
// =login ******************************************************************************
	$("input#i_need_hard_copy").change(function(){
		if($(this).prop('checked')){
			free_hard_copy_section_show();
		}
		else{
			free_hard_copy_section_hide();
		}
	});

	function login_processing(){
		jqxhr_data.email = $('#login_email').val();
		jqxhr_data.pass = $('#login_pass').val();
		
		if(clicked_this == "a[href*='order_a_free_copy']" || (clicked_this.search(/rel=partner_/i) >= 0)){// order free copy OR client login/register -------------
			if($('#login #i_need_hard_copy').is(':checked')){// send hard copy
				jqxhr_data.fc = 'h';
				jqxhr_data.name = $('input#name_free_copies').val();
				jqxhr_data.address = $('input#address_free_copies').val();
				jqxhr_data.country = $('select#country_free_copies option:selected').val();
				if(jqxhr_data.country == 'UK'){jqxhr_data.county = $('select#county_free_copies option:selected').val();}
				else {jqxhr_data.county = $('input#state_free_copies').val();}
				jqxhr_data.postcode = $('input#postcode_free_copies').val();
				//jqxhr_data = {email:email,pass:pass,fc:'h',name:name,address:address,country:country,county:county,postcode:postcode};
			}
			else if(clicked_this.search(/rel=partner_login/i) >= 0){jqxhr_data.fc = 'cl';}//client login
			else if(clicked_this.search(/rel=partner_register/i) >= 0){jqxhr_data.fc = 'cr';}//client register
			else {//soft copy
				jqxhr_data.fc = 's';
			}// END soft copy
		}// END order free copy --------------------------------------------------------------
		
		else { // only log in --------------------------------------------------------------------
			//jqxhr_data = {email:email,pass:pass};
		} // END only log in------------------------------
		
		$.getJSON("_includes/ajax/login.php",jqxhr_data, function(d){ //server login ----------
		  if(d.valid == 'free_copy'){
			  valid_login_process(jqxhr_data);
			  if(clicked_this == "a[href*='order_a_free_copy']"){
				  cookie_write('free_copy_issue',d.free_copy_issue,364);
				  $('#download_links').html("<a href='download/mag/choicehealthmag.com_issue_"+cookie_read('free_copy_issue')+".pdf'>Download Free Copy</a>").dialog('open');
			  }
			  else{$(clicked_this).click();}
			  $('#login').dialog("close");
		  }
		  else if(d.valid == 'client'){
			valid_login_process(jqxhr_data);
		  	cookie_write('logged_in_c',1,364);
			window.location = 'partnership.php'
		  }
		  else if(d.valid == 'wrong_pass'){
			  $('#login .error1').slideUp(500).html("Wrong password, please try again.<br>OR <a rel='password_reset'>reset the pass and send a new pass to " + jqxhr_data.email + "</a>").slideDown(500);
			  //$('#login').dialog("close");
		  }
		  else if(d.valid == 1){
			  valid_login_process(jqxhr_data);
			  $('#login').dialog("close");
			  $(clicked_this).click();
		  }
		  else{
			  if(d.error){
				$('#login .error1').slideUp(500).text(d.error).slideDown(500);
			  }
		  }
	  });// END $.getJSON server login -------------
	} // END login_processing()
	
	$('#login').dialog({
		autoOpen : false,
		position : ['center',100],
		modal    : true,
		minWidth   : 700,
		buttons  : {"Login/Signup" : function(){
						if($("#login").validate().form() == true){
							login_processing();
						} // END if($("#login").validate().form() == true)
					} // END "Login/Signup"
				},// END buttons
		beforeClose: function(event, ui){
						$("input#i_need_hard_copy").prop('checked',false);
						free_hard_copy_section_hide();
						$('#login .i_need_hard_copy').hide();
					}
	});// END $('#login').dialog
	
	function valid_login_process(jqxhr_data){
		cookie_write('logged_in',1,364);
		cookie_write('email',jqxhr_data.email,364);
		if_logged_in_do_these();
	}
	
	$("a[rel=password_reset]").live('click',function(e){// password reset -----------------------------------
		e.preventDefault();
		$.getJSON("_includes/ajax/password_reset.php",null,function(d_password_reset){
			if(d_password_reset.valid == 1){$('#login .error1').html("Password has been reset successfully. Please check " + jqxhr_data.email + " to get your new pass.");}
			else {$('#login .error1').html("There has been a problem with resetting your password, the admin has been notified. You will be getting a response in 3 business days. We are sorry for this inconvenience.");}	
		});
	});// END password reset -----------------------------------
// END =m5_estore -------------------------------------------------------------------------------------------------
// =m5_estore
// =estore.php **********************************************************************************
	if(window.location.pathname == '/estore.php' || window.location.pathname == '/estore_c.php'){
		// =estore menu positioning -------------------
		var estore_width = $("#estore #main").outerWidth(true);
		var estore_menu = $("#estore .menu").outerWidth(true);
		var nav_main_width = $("#nav_main").outerWidth(true);
		var estore_width_calculated = window_width - (nav_main_width + estore_menu + 120);
		$("#estore #main").width(estore_width_calculated);
		$('#estore .menu').height(window_height);
		$('#page').css({'margin-left':'350px'});
		$('header#header_main #header').css({'margin-right':'200px'});
		// END =estore menu positioning ------------------------------------------------------------
	
		// estore user functionality ----------------------------------------------------------------
		$('#estore .menu>ul>li>div').click(function(e){
			var offset = $(this).offset();
			var menu_scrolltop = $('#estore .menu').scrollTop();
			var toscroll = parseInt(offset.top + menu_scrolltop);
			$('#estore .menu').scrollTop(toscroll);
			$(this).parent().find('ul').slideToggle(1000,'swing',function(){});	
		});
		
		$('#estore .menu ul>li>ul>p').click(function(){
			$(this).parent().find('ul').slideToggle(1000,'swing');	
		});
		
		// pj[id] - [0=therapy_name,1=introductory_price,2=pp_row,3=desc,4=cat,5=subcat]
		$('#estore .menu a').hover(
			function(){
				var id = this.rel;
				var img = 'images/store/' + pj[id][4] + '/';
				img += (pj[id][5] == '' || pj[id][5] == 'null' || pj[id][5] == null)? '' : (pj[id][5] + '/');
				img += id + '.jpg';
				if(pj[id][4] == 'back_issue'){
					var buy_options = "<form id='frm_buy'>"+
										  "<p class='soft'><input type='radio' name='cost'><label>&pound;<span></span> : e-mag/pdf (Worldwide)</label></p>"+
										  "<p class='hard_uk'><input type='radio' name='cost'><label>&pound;<span></span> : Hard Copy (UK only)</label></p>"+
										  "<p class='hard_row'><input type='radio' name='cost' rev='ship'><label>&pound;<span></span> : Hard Copy (Worldwide)</label></p>"+
										  "<p><a class='button add_to_cart link'>Add to Cart</a></p>"+
										"</form>";
				}
				else {var buy_options = add_to_cart_button(id);}
				var store_main = "<div><h3>"+pj[id][0]+"</h3>"+
								"<img src='" + img + "' alt='" + pj[id][0] + "'>"+
								buy_options +
								"<div>" + pj[id][3] + "</div>"+
								"<p class='price'>Price: &pound;" + parseFloat(pj[id][1]).toFixed(2) + "</p>"+
								//add_to_cart_button(id) +
								"</div>";
				$('#estore #main').html(store_main);
				if(pj[id][4] == 'back_issue'){frm_buy_process(id);}
			},
			function(){
				var id = $(this).val('rel');
			}
		);
		// END estore user functionality --------------------------------------------------------------
			
		// estore slideshow ------------------
		// END estore slideshow ------------------	
	}//END if(window.location.pathname == '/estore.php')
// END =estore.php **********************************************************************************	

//END =m5_estore
// =m6_admin
$('#admin a[rel=download_user_emails]').click(function(e) {
	
    //console.log('yes');
});

});//END =$(document).ready(function() 
//END =m6_admin
// =m7
// =cookie -----------------------------------------------------------------------------------------------
function cookie_write(name,value,days){
	if(days){
		var d = new Date();
		d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = ";expires=" + d.toUTCString();	
	}
	else var expires = '';
	document.cookie = name + '=' + value + expires + ';path=/';
}

function cookie_read(name){
	var c_a = document.cookie.split(';');
	for(var i = 0; i<c_a.length; i++){
		var c_a_a = c_a[i].split('=');
		if(c_a_a[0].charAt(0) == ' ') c_a_a[0] = c_a_a[0].substring(1);
		if(c_a_a[0] == name) return c_a_a[1];
	}
	return false;
}
// END cookie -------------------------------------------

// =therapists =============================================================================
// therapists.php ---------------
$(function(){
	//$('div.edit_your_listing').hide();
	$('a.edit_listing').click(function(){
		$('form.edit_your_listing').toggle("explode","slow");
	});
});
function display_details(email,site) {
	var win_url = site + "/therapist_details.php?email=" + email;
	new_window = window.open(win_url,"","height=800,width=500,scrollbars=1");
	new_window.moveTo(0,0);
}

// therapists_form.php -------------------------------
function therapists_form_check(){
	var message = "";
	var therapists_form_backgroundcolor = "#FFFABF";
	var therapists_form_regular_color = "#fff";
	var therapists_form_reset_color = "#EBF4FB";
	var focus_first = "";
	var form_elements = ["therapy_id", "name_first", "name_middle", "name_last", "sex", "email", "password", "password1", "therapy_style", "address_address", "address_county_uk", "address_county", "address_country", "tel_mobile", "tel_land", "qualification", "experience", "company_description", "accrediting_organizations"];
	
	for (i = 0; i < form_elements.length; i++) {
		document.getElementById(form_elements[i]).style.backgroundColor = therapists_form_reset_color;
	}
	
	// radio button Package Selection
	var radio_selected = -1;
	var radio_options = document.therapists_form.therapy_id.length;
	for (var i = 0; i < radio_options; i++) {
		if (document.therapists_form.therapy_id[i].checked) {
			radio_selected = i;
		}
	}
	if (radio_selected == -1) {
		document.getElementById("therapy_id").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Choose Package\n";
	}
	if (document.therapists_form.therapy_id[0].checked) {
		if (document.therapists_form.free_listing_code.value != "CHW") {
			document.getElementById("therapy_id").style.backgroundColor = therapists_form_backgroundcolor;
			message += "The code entered is not correct!\n";
		}
	}
	return therapists_common_elements_2(message,form_elements,therapists_form_backgroundcolor,therapists_form_regular_color,therapists_form_reset_color,focus_first);
}

// therapists_edit.php ----------------------------------------------
function therapists_edit_check(){
	var message = "";
	var therapists_form_backgroundcolor = "#FFFABF";
	var therapists_form_regular_color = "#fff";
	var therapists_form_reset_color = "#EBF4FB";
	var focus_first = "";
	var form_elements = ["name_first", "name_middle", "name_last", "sex", "email", "password", "password1", "therapy_style", "address_address", "address_county_uk", "address_county", "address_country", "tel_mobile", "tel_land", "qualification", "experience", "company_description", "accrediting_organizations"];
	
	for (i = 0; i < form_elements.length; i++) {
		document.getElementById(form_elements[i]).style.backgroundColor = therapists_form_reset_color;
	}
	return therapists_common_elements_2(message,form_elements,therapists_form_backgroundcolor,therapists_form_regular_color,therapists_form_reset_color,focus_first);
}
//----------------
function therapists_common_elements_2(message,form_elements,therapists_form_backgroundcolor,therapists_form_regular_color,therapists_form_reset_color,focus_first){
	if (document.therapists_form.name_first.value == ""){
		document.getElementById("name_first").style.backgroundColor = therapists_form_backgroundcolor;
		message += "First Name\n";
	}
	if (document.therapists_form.name_last.value == ""){
		document.getElementById("name_last").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Last Name\n";
	}
	
	// radio button Sex
	var radio_selected = -1;
	var radio_options = document.therapists_form.sex.length;
	for (var i=0; i<radio_options; i++){
		if (document.therapists_form.sex[i].checked){
			radio_selected = i;
		}
	}
	if (radio_selected == -1) {
		document.getElementById("sex").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Sex\n";
	}
	
	if (document.therapists_form.email.value == ""){
		document.getElementById("email").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Email\n";
	}
	
	//Passwords
	if (document.therapists_form.password.value == ""){
		document.getElementById("password").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Password\n";
	}
	else if (document.therapists_form.password.value != document.therapists_form.password1.value){
		document.getElementById("password").style.backgroundColor = therapists_form_backgroundcolor;
		document.getElementById("password1").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Passwords do not match. Please enter same password in both fields!\n";
	}
	
	if (document.therapists_form.therapy_style.value == ""){
		document.getElementById("therapy_style").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Therapy Style\n";
	}
	if (document.therapists_form.address_address.value == ""){
		document.getElementById("address_address").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Address\n";
	}
	
	// COUNTRY/COUNTY
	if (document.therapists_form.address_country.value == "UK"){
		if (document.therapists_form.address_county_uk.value == "") {
			document.getElementById("address_county_uk").style.backgroundColor = therapists_form_backgroundcolor;
			document.getElementById("address_county").style.backgroundColor = therapists_form_regular_color;
			message += "UK County(from the drop down list)\n";
		}
	}
	else if (document.therapists_form.address_county.value == "") {
		document.getElementById("address_county").style.backgroundColor = therapists_form_backgroundcolor;
		document.getElementById("address_county_uk").style.backgroundColor = therapists_form_regular_color;
		message += "County/State\n";
	}
	
	// telephone
	if (document.therapists_form.tel_mobile.value == "" && document.therapists_form.tel_land.value == ""){
		document.getElementById("tel_mobile").style.backgroundColor = therapists_form_backgroundcolor;
		document.getElementById("tel_land").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Telephone Mobile/Telephone Land Line\n";
	}
	
	if (document.therapists_form.qualification.value == ""){
		document.getElementById("qualification").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Qualification\n";
	}
	if (document.therapists_form.experience.value == ""){
		document.getElementById("experience").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Experience\n";
	}
	if (document.therapists_form.company_description.value == ""){
		document.getElementById("company_description").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Company Descripton\n";
	}
	if (document.therapists_form.accrediting_organizations.value == ""){
		document.getElementById("accrediting_organizations").style.backgroundColor = therapists_form_backgroundcolor;
		message += "Member of which Accrediting Organisations\n";
	}
	if (document.therapists_form.specialization.value == ""){
		document.getElementById("specialization").style.backgroundColor = therapists_form_backgroundcolor;
		message += "\n";
	}
	if (message != "") {
		alert("Please fill up the following compulsory values:\n" + message);
		return false;
		//return true; // USE FOR TESTING ONLY
	}
	else return true;
}
// END therapists =====================================================================

// =piwik ------------------------------------------------------------------------------
function piwik(){
	var pkBaseURL = (("https:" == document.location.protocol) ? "https://www.choicehealthmag.com/tool/piwik/" : "http://www.choicehealthmag.com/tool/piwik/");
	document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));
	try {
		var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 1);
		piwikTracker.trackPageView();
		piwikTracker.enableLinkTracking();
	} catch( err ) {}
}
// END =piwik ------------------------------------------------------------------
//END =m7

