////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///// ALL PAGE HANDLERS ////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Initialise required variables
var helpup;
var timeout;
var submit = 0;

$(document).ready(function(){
	
	$('.addaddress').css('display', 'none');
	
	$('.address_radio').change(function(){
		
		if ($(this).attr('id') == 'new_billing_address' || $(this).attr('id') == 'new_delivery_address'){
			$(this).parents('.js_wrap').find('.addaddress').slideDown();	
			$('.js_toggle').each(function(){
				addClass('js_form_val');
			});
		} else {
			$(this).parents('.js_wrap').find('.addaddress').slideUp();
			$('.js_toggle').each(function(){
				removeClass('js_form_val');
			});
		}
	
	});
	
	// Automatically select sign in radio if email selected
	$('.user_login #form_email_address, .user_login #form_password').click( function() {
		$('#form_returning').attr('checked', true);
	});
	
	// Changing add to added for collections and normal buttons
	$('#testsubmit, #addcollection').click( function() {
		$(this).attr('value', 'Added').delay(2000).queue(function(next) { $(this).attr('value', 'Add to Basket'); next(); });
	});
	
	// Highlighting for A-Z
	$( function() {     
    	var pathName = window.location.href.split(/=/)[1];
		$('.fll.w100.text-center.mb20.mt20.darkpurp').find('a').each(function() {
			var html = $(this).html();
			if ( html == pathName ) {
				$(this).css({
					'font-weight': 'bold',
					'text-decoration': 'underline'
				});
			}
		});
	});  
	
	// Highlighting for collections
	$( function() {      
    	var colName = window.location.href.split(/=/)[1];
		$('.collections').find('a').each(function() {
			var coll = $(this).attr('href').split(/=/)[1];
			if ( coll == colName ) {
				$(this).css({
					'text-decoration': 'underline'
				});
			}
		});
	});  
	
	// Add the open attribute to the cart and define as false
	$('#openBasket').attr('open', 'false');
	
	// Add on click handler to both IDs
	$('#smbasket_close, #openBasket').click(toggleBasket);
	
	// Add click handler to update cart links using LIVE
	$('.updateBasket').live('click', updateCart);
	
	// Add onclick handlers to any helper links
	$('.js_help, .iqmark').live('click', helpup);
	
	// Add onclick to add to cart product page
	$("#testsubmit").live('click', addToCartMain);
	
	// Add onsubmit to search page
	$('form[name=searchresultspage]').live('submit', addToCartSearch);

	// Add onclick to move to cart links
	$('.js_mtc').bind('click', moveToCart);

	// Bind on click to clear all filters button
	$('#clearall').bind('click', clearAllFilters);
	
	$('.js_form_val').each(function(){
		addValidation(this);
	});
	
	// Show delivery address if different_to clicked
	$('#different_to').click(function () {
		$('.deliveryadd').slideDown();
	});
	$('#same_as').click(function () {
		$('.deliveryadd').slideUp();
	});
	
	//Show sub list if selected
	$('#checkout_substitutes').change( function() {
	    if ( $(this).val() == 1 ) {
	    	$('.sub_list').slideDown();
	    } else {
	    	slideUp();
	    }
	});
	
	$('#addcollection').bind('click', addCollection);
	
	// Bind on click to the copy addresses checkbox
	$('#same_as').bind('click', copyAddresses);
	
	$('#addcollection').bind('click', addCollection);
	
	// Bind on click to address form submit	
	$('.js_carryon').bind('click', validateAll);
	
	$('#sid').bind('change', alterPrice);
	
	$('.js_sel_chg').live('change', alterPrices);
	
	$('.js_add_book').bind('click', addBook);
	
	// Bind on click to extra features
	$('.js_fscb').live('click', extraFilters);
	
	$("#extrasearch").hide();
	
	$("#faceted").click(function(){
		$("#extrasearch").slideToggle(500);
	});
	
	$(".faceted").change(filterResults); 
	
	$(".js_imageswap").bind('click', imgSwap);
	
	$('.js_splitter').bind('click', updShip);
	
	$('select#view').change(function(){
		var numberPerPage = $(this).val();
		$('.display').each(function(){
			$(this).val(numberPerPage);
		});
		$.ajax({
			url: '/ajax/set_number_of_results_per_page.php',
			data: 'value=' + numberPerPage,
			success: function(){
				filterResults();
			}
		});
	});
	
	$('form .resultform').bind('submit', addToCartSearch);
	
});

////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///// AJAX OBJECT //////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Initialize the object:
var ajax = false;

// Choose object type based upon what's supported:
if (window.XMLHttpRequest) {

	// IE 7, Mozilla, Safari, Firefox, Opera, most browsers:
	ajax = new XMLHttpRequest();
	
} else if (window.ActiveXObject) { // Older IE browsers

	// Create type Msxml2.XMLHTTP, if possible:
	try {
		ajax = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e1) { // Create the older type instead:
		try {
			ajax = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e2) { }
	}
	
}

// Send an alert if the object wasn't created.
if (!ajax) {
	alert ('Some page functionality is unavailable.');
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///// CART RELATED FUNCTIONS ///////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function toggleBasket(){
	
	if(timeout){
		clearTimeout(timeout);
	}
	
	if($("#openBasket").attr('open') == 'false'){
		
		$("#openBasket").attr('open', 'true');
		$("#smbasket_open").fadeIn(500);
		$("#js_sb_ar").rotateLeft(90);
	
	} else {
		
		$("#openBasket").attr('open', 'false');
		$("#smbasket_open").fadeOut(500);
		$("#js_sb_ar").rotateRight(90);
		// Change add to basket class temporarily
	  $("input[name='addtobasketlink']").attr('class', 'addtobasketsm button flr');
	}
	
	return false;

}

function moveToCart(){

	// Test for the ajax object
	if(ajax){
		
		// Snatch the destination of the link
		var sid = $(this).attr('id').substring(7);
		
		// Attach a variable to the window to delete the DIV
		window.fadeout = 'js_mtc_container_' + sid;
		window.specific = sid;
		
		// Call the PHP script using the GET method
		ajax.open('get', 'ajax_movetocart.php?sid=' + encodeURIComponent(sid));
	
		// Assign the function that handles the response
		ajax.onreadystatechange = handleCart;
		
		// Send the request
		ajax.send(null);
	
		return false;
		
	} else {
		
		return true;
		
	}
	
}

function addToCartMain(){
	
	// Test for the ajax object
	if (ajax){
			
		// Grab the value of the select
		var sid = $("#sid").val();
		
		// Grab the order ID
		var oid = $("#oid").val();
		
		// Attach variables to the window
    	window.specific = sid;
		
		// Grab the value of the quantity input
		var qty = $("#quantity").val();

		// Call the PHP script using the GET method
		ajax.open('get', 'add-plant-to-cart.php?sid=' + encodeURIComponent(sid) + '&qty=' + encodeURIComponent(qty) + '&oid=' + encodeURIComponent(oid) + '&ajax=true');

		// Assign the function that handles the response
		ajax.onreadystatechange = handleCart;
		
		// Send the request
		ajax.send(null);

		return false;
		
	} else {
		
		return true;
		
	}
	
}

function addToCartSearch(){

	// Check the AJAX object is available
	if (ajax){
		
		// Assign the SELECT variables	
		var fid = $(this).attr('id');
		var eid = fid.substring(5);
		var sid = $("#select_" + eid).val();
		var oid = $("#oid_" + eid).val();
		var aid = "addbtn_" + eid;
		
		// Attach variables to the window
		window.specific = sid;
		window.btnadded = aid;

		// Call the PHP script using the GET method
		ajax.open('get', 'add-plant-to-cart.php?sid=' + encodeURIComponent(sid) + '&oid=' + encodeURIComponent(oid) + '&ajax=true');
		
		// Assign the function that handles the response
		ajax.onreadystatechange = handleCart;
		
		// Send the request
		ajax.send(null);
		
		return false;
		
	} else {
		
		return true;
		
	}
	
}

function addCollection(){
	
	// Test for the ajax object
	if(ajax){
			
		// Grab the value of the select
		var sid = $("#collection_id").val();
		
		// Grab the value of the quantity input
		var qty = $("input:radio[name=add_amount]:checked").val();
		
		var oid = $('#oid').val();
		
		// Call the PHP script using the GET method
		ajax.open('get', 'add-collection-to-cart.php?sid=' + encodeURIComponent(sid) + '&qty=' + encodeURIComponent(qty) + '&oid=' + encodeURIComponent(oid) + '&ajax=true');

		// Assign the function that handles the response
		ajax.onreadystatechange = handleCart;
		
		// Send the request
		ajax.send(null);

		return false;
		
	} else {
		
		return true;
		
	}
	
}

function addBook(){
	
	// Test for the ajax object
	if (ajax){
			
		// Grab the value of the select
		var string = $(this).attr('href');
		
		// Call the PHP script using the GET method
		ajax.open('get', string + '&ajax=true');

		// Assign the function that handles the response
		ajax.onreadystatechange = handleCart;
		
		// Send the request
		ajax.send(null);

		return false;
		
	} else {
		
		return true;
		
	}
	
}


function handleCart(){
	
	// Check the status of the ajax call
	if ((ajax.readyState == 4) && (ajax.status == 200)){
		
		// Check for a positive response
		if (ajax.responseText.length > 5){
			
			showCart(eval('(' + ajax.responseText + ')'));
			
		}
		
	}
	
}

function showCart(results){
	
	// Tend to the window variables??
	if(window.specific){
		var specific = window.specific;
	} else {
		var specific = '0';
	}
	
	if(timeout){
		clearTimeout(timeout);
	}
	
	// Initialise a variable to hold the HTML
	var minicart = '';
	
	// Check the cart is not empty prior to looping
	if (results[0].length > 0) {
		
		// Loop through all the products in results
		for (i = 0; i < results[0].length; i++) {
		
			minicart += '<fieldset class="smbasket_item" ';
			if (results[0][i].specific == specific) {
				minicart += 'id="newitem"';
			}
			minicart += ' >';
			minicart += '<img src="images/sbp_' + results[0][i].image + '" alt="' + results[0][i].latin + '" class="smbasket_img" />';
			minicart += '<fieldset class="smbasket_details">';
			minicart += '<p class="smbasket_name"><a href="">' + results[0][i].latin + '</a><span class="italics">&nbsp;' + results[0][i].size + '</span></p>';
			minicart += '<fieldset class="smbasket_wrapper">';
			minicart += '<fieldset class="smbasket_qty">';
			minicart += '<p>Qty:</p>';
			minicart += '<fieldset>';
			minicart += '<input type="hidden" name="sid[]" value="' + results[0][i].specific + '" />';
			minicart += '<input class="smbasket_qty_input" type="text" name="amount[]" class="fll" value="' + results[0][i].qty + '" />';
			minicart += '<input type="hidden" name="oid[]" value="' + results[0][i].oid + '" />';
			minicart += '</fieldset>';
			minicart += '</fieldset>';
			minicart += '<fieldset class="smbasket_update anone">';
			minicart += '<a href="" class="updateBasket"><fieldset class="iupdate"></fieldset>update</a> ';
			minicart += '</fieldset>';
			minicart += '<fieldset class="smbasket_itemprice">';
			minicart += '<p>' + results[0][i].price + '</p>';
			minicart += '</fieldset>';
			minicart += '</fieldset>';
			minicart += '</fieldset>';
			minicart += '</fieldset>';
			
		}
		
	}
	
	// Replace the inner HTML of the minicart
	$("#smbasket_form").html(minicart);
	
	// Update the estimated delivery cost
	$("#estdelivery").html(results[1]);
	
	// Update the basket total
	$("#basketotal").html(results[2]);
	
	// Update the number of items in the basket
	$("#itemsinbasket").html(results[3]);
	
	// Is theis an update or an add?
	if (typeof window.updatecart == 'undefined'){
		
		// Change add to basket class tempotarily
		$("#" + window.btnadded).attr('class', 'addtobasketsm_added button flr');
		
		// Is basket already open?
		if($("#openBasket").attr('open') == 'false'){
			
			// Open the basket using fade
			$("#smbasket_open").fadeIn(750, function(){
				
				// Set the open attritube to true
				$("#openBasket").attr('open', 'true');
				
				// Rotate the arrow 90 degrees left
				$("#js_sb_ar").rotateLeft(90);
				
			});
			
		}
		
		if(window.fadeout){
			
			$('#' + window.fadeout).fadeOut(500);
			delete window.fadeout;
		}
		
		// Animate the background colour of the new item
		$("#newitem").animate({
			backgroundColor: '#b0b2c1'
		}, 500).delay(800).animate({
			backgroundColor: '#fafde0'
		}, 2000);
		
		// Set a timeout and grab the instance
		timeout = setTimeout(toggleBasket, 4000);
	
	}
}

function updateCart(){
	
	// Test for the ajax object
	if(ajax){
		
		// Assign variables to the window for global use
		window.updatecart = true;
		if(window.specific){
			delete window.specific;
		}
		
		// Extract all the specific IDs and quantities
		var sids = document.getElementsByName('sid[]');
		var qtys = document.getElementsByName('amount[]');
		var oids = document.getElementsByName('oid[]');
		
		// Initialise an array to hold values
		var fields = [];
		
		// Loop through all the SIDs
		for(i = 0; i < sids.length; i++){
			
			// Add the values to array ensuring all are encoded
			fields[i] = {
				"sid": encodeURIComponent(sids[i].value),
				"qty": encodeURIComponent(qtys[i].value),
				"oid": encodeURIComponent(oids[i].value)
			};
			
		}
		
		// Transform the array into a string
		var string = $.toJSON(fields);

		// Call the PHP script using the GET method
		ajax.open('get', 'ajax_updatecart.php?json=' + string);
		
		// Assign the function that handles the response
		ajax.onreadystatechange = handleCart;
			
		// Send the request
		ajax.send(null);
			
		return false;
			
	} else {
		
		return true;
		
	}
	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///// PRICE RELATED FUNCTIONS //////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function alterPrices(){
	
	var sid = $(this).val();
	
	var gid = $(this).attr('id').substring(7);
	window.gid = gid;
	
	// Call the PHP script using the GET method
	ajax.open('get', 'ajax_update.php?sid=' + encodeURIComponent(sid));

	// Assign the function that handles the response
	ajax.onreadystatechange = handlePrice;
	
	// Send the request
	ajax.send(null);
	
	// Prevent default action
	return false;
	
}

function alterPrice(){
	
	// Snatch the value to pass to the script
	var sid = $("#sid").val();
	
	// Call the PHP script using the GET method
	ajax.open('get', 'ajax_update.php?sid=' + encodeURIComponent(sid) + '&s=1');

	// Assign the function that handles the response
	ajax.onreadystatechange = handlePrice;
	
	// Send the request
	ajax.send(null);
	
	// Prevent default action
	return false;
	
}

function handlePrice(){
	
	// Check if the ajax call is complete
	if((ajax.readyState == 4) && (ajax.status == 200)){
		
		// Check for a positive response
		if(ajax.responseText.length > 5){
			
			// Call the update price function passing the response text
			updatePrice(eval('(' + ajax.responseText + ')'));
			
		}
		
	}
	
}

function updatePrice(response){
	
	if(window.gid){

		$('#deliveryest_' + window.gid).html(response.upperbox);
		$('#priceadd_' + window.gid).html(response.lowerbox);
		$('#oid_' + window.gid).val(response.oid);
		delete window.gid;
		
	} else {
	  
		// Update the price
		$('#price').html(response.price);	
		// Update the delivery time estimate
		$('#deliveryest').html(response.delivery);
    $('#rightcontain').html(response.cyb);
    
	}
		
	// Update the stock level
	$('#stock').html(response.html);
		
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///// CHECKOUT RELATED FUNCTIONS ///////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Add on change handler to radio buttons
jQuery('.delivery_radio_button').change(function(){
    
    var parentFieldset = jQuery(this).val() == 1 ? 'billing' : 'delivery';
    addDeliveryChargeEventHandlers(parentFieldset);
    
});

function addDeliveryChargeEventHandlers(parentFieldset){
    
    if (parentFieldset == 'billing'){

        jQuery('#delivery').find('.country').unbind('change');
        jQuery('#delivery').find('.postcode').unbind('blur');
        
    } else {
        
        jQuery('#billing').find('.country').unbind('change');
        jQuery('#billing').find('.postcode').unbind('blur');
        
    }
    
    jQuery('#' + parentFieldset).find('.country').change(updateShipping);
    jQuery('#' + parentFieldset).find('.postcode').blur(updateShipping);
    jQuery('#' + parentFieldset).find('.postcode').blur();
    jQuery('#' + parentFieldset).find('.country').change();
    
    
}

function updateShipping(){
    
    var type;
    var overseas = false;
        
    if (jQuery(this).hasClass('country')){
            
        type = 'cid';
            
    } else {
        
        type = 'pcd';
        
        if (jQuery(this).parent().parent().find('.country').val() != 35){
            
            overseas = true;
            
        }
        
    }
    
    if (type == 'cid' || (type == 'pcd' && !overseas)){
        
        jQuery.ajax({
            url: "ajax_update_shipping.php",
            data: ({
                type: type,
                value: jQuery(this).val()
            }),
            success: function(data){

                if (data.length > 0){
                    jQuery('#shipping_feedback').html(data);
                    jQuery('#shipping_feedback').slideDown(1000);
                } else {
                    jQuery('#shipping_feedback').slideUp(1000);
                    jQuery('#shipping_feedback').html('');
                }

            }
        });
        
    }
    
}


function copyAddresses(){

	if (this.checked == 1) {
	
		$('.js_form_copy').each(function(){
		
			var source = $(this).attr('id');
			var text = $(this).val();
			var destination = 'd' + source.substring(1);
			$('#' + destination).val(text);
			
		});
		
		if ($('#d_checkout_country').val() == 999) {
		
			$('#d_checkout_postcode').trigger('blur');
			
		}
		else {
		
			$('#d_checkout_country').trigger('change');
			
		}
		
	} else {
	
		$('.js_form_remov').each(function(){
		
			$(this).val('');
			
		});
		
	}
	
	$('.js_form_val').not('#checkout_b_contactno, #checkout_email').each(validation);

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///// VALIDATION RELATED FUNCTIONS /////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function addValidation(object){
	
	if ($(object).hasClass('js_form_mand')) {
	
		$(object).bind('blur', validation);
		
	} else if ($(object).hasClass('js_form_num')) {
		
		$(object).bind('change', validation);
			
	} else if ($(object).hasClass('js_form_email')) {
			
		$(object).bind('blur', validation);
			
	}
	
}

function validation(){

	// Snatch the validation type and store in a variable
	var value = $(this).val();
	var validate = 0;
	
	// Run this through a switch 
	if ($(this).hasClass('js_form_mand')) {
	
		if (value.length > 0) {
			validate = 1;
		}
		
	} else if ($(this).hasClass('js_form_email')) {
		
		var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		if (emailPattern.test(value)) {
			validate = 1;
		}
			
	} else if ($(this).hasClass('js_form_num')) {
			
		if (parseInt(value) > 0) {
			validate = 1;
		}
				
	} else if($(this).hasClass('js_form_check')) {
		
		if(this.checked == 1){
			validate = 1;
		}
			
	}
	
	if(validate == 1){
		
		$(this).css({'background-color' : '#d8f0b4', 'border' : '2px solid #a4d858'});
		
	} else {
		
		$(this).css({'background-color' : '#f3d4ce', 'border' : '2px solid #df5e5e'});
		submit++;
		
	}

}

function validateAll(){
  
  submit = 0;
  
	$.each($('.js_form_val'), validation);
	
	if(submit > 0){
		submit = 0;
		$('#js_val_fb').html('You must fill out the form elements highlighted in red and agree to our terms and conditions');
		return false;		
	} else {
		return true;
	}
	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///// ROTATION FUNCTIONS ///////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

jQuery.fn.rotate = function(angle,whence) {
	var p = this.get(0);

	// we store the angle inside the image tag for persistence
	if (!whence) {
		p.angle = ((p.angle==undefined?0:p.angle) + angle) % 360;
	} else {
		p.angle = angle;
	}

	if (p.angle >= 0) {
		var rotation = Math.PI * p.angle / 180;
	} else {
		var rotation = Math.PI * (360+p.angle) / 180;
	}
	var costheta = Math.cos(rotation);
	var sintheta = Math.sin(rotation);

	if (document.all && !window.opera) {
		var canvas = document.createElement('img');

		canvas.src = p.src;
		canvas.height = p.height;
		canvas.width = p.width;

		canvas.style.filter = "progid:DXImageTransform.Microsoft.Matrix(M11="+costheta+",M12="+(-sintheta)+",M21="+sintheta+",M22="+costheta+",SizingMethod='auto expand')";
	} else {
		var canvas = document.createElement('canvas');
		if (!p.oImage) {
			canvas.oImage = new Image();
			canvas.oImage.src = p.src;
		} else {
			canvas.oImage = p.oImage;
		}

		canvas.style.width = canvas.width = Math.abs(costheta*canvas.oImage.width) + Math.abs(sintheta*canvas.oImage.height);
		canvas.style.height = canvas.height = Math.abs(costheta*canvas.oImage.height) + Math.abs(sintheta*canvas.oImage.width);

		var context = canvas.getContext('2d');
		context.save();
		if (rotation <= Math.PI/2) {
			context.translate(sintheta*canvas.oImage.height,0);
		} else if (rotation <= Math.PI) {
			context.translate(canvas.width,-costheta*canvas.oImage.height);
		} else if (rotation <= 1.5*Math.PI) {
			context.translate(-costheta*canvas.oImage.width,canvas.height);
		} else {
			context.translate(0,-sintheta*canvas.oImage.width);
		}
		context.rotate(rotation);
		context.drawImage(canvas.oImage, 0, 0, canvas.oImage.width, canvas.oImage.height);
		context.restore();
	}
	canvas.id = p.id;
	canvas.angle = p.angle;
	p.parentNode.replaceChild(canvas, p);
}

jQuery.fn.rotateRight = function(angle) {
	this.rotate(angle==undefined?90:angle);
}

jQuery.fn.rotateLeft = function(angle) {
	this.rotate(angle==undefined?-90:-angle);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///// GENERAL FUNCTIONS ////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function clearMe(formfield){
	
	if (formfield.defaultValue == formfield.value) {
		formfield.value = "";
	}
	
}

function returnMe(formfield){
	
	if (formfield.value == "") {
		formfield.value = formfield.defaultValue;
	}
	
}

function helpup(){

	helpup = window.open(dest, "helper", "width=540, height=600");
	helpup.close();
	
	var dest = $(this).attr("href");
	
	helpup = window.open(dest, "helper", "width=540, height=600");
	
	return false;
	
}

function clearAllFilters(){
	
	// Check the AJAX object is available
	if(ajax){
		
		// Call the PHP script using the GET method
		ajax.open('get', 'updateresults.php');
		
		// Assign the function that handles the response
		ajax.onreadystatechange = handleUpdate;
		
		// Send the request
		ajax.send(null);
		
		return false;
		
	} else {
		
		return true;
		
	}
	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
///// JSON FUNCTIONS ///////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////

(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);

function filterResults(){
	
	// Check the AJAX object is available
	if (ajax){
		
		// Assign the SELECT variables	
		var select = $(this).attr("name");
		var option = $(this).val();
		
		// Call the PHP script using the GET method
		ajax.open('get', 'updateresults.php?select=' + encodeURIComponent(select) + '&option=' + encodeURIComponent(option));
		
		// Assign the function that handles the response
		ajax.onreadystatechange = handleUpdate;
		
		// Send the request
		ajax.send(null);
		
		return false;
		
	} else {
		
		return true;
		
	}
	
}

function extraFilters(){
	
	// Check the AJAX object is available
	if(ajax){
		
		if(this.checked == 1){
			
			var option = '1';
			
		} else {
			
			var option = '0';
			
		}
		
		// Assign the SELECT variables	
		var select = $(this).attr("name");
		
		// Call the PHP script using the GET method
		ajax.open('get', 'updateresults.php?select=' + encodeURIComponent(select) + '&option=' + encodeURIComponent(option));
		
		// Assign the function that handles the response
		ajax.onreadystatechange = handleUpdate;
		
		// Send the request
		ajax.send(null);
		
	}
	
}

function handleUpdate(){

	if((ajax.readyState == 4) && (ajax.status == 200)){
		
		if(ajax.responseText.length > 10){
			
			showResults(eval('(' + ajax.responseText + ')'));
			
		} else {
			
			// Update main DIV to show no results?
			
		}
		
	}
	
}

function showResults(results){

	var html = '';
	var p = 1;
	for (i = 0; i < results[0].length; i++) {
		
		var gen = results[0][i].generic_id;
		
		if (p < 2) {
		
			html += '<div class="resultholder mr20">';
			
		} else {
		
			html += '<div class="resultholder">';
			
			p = 0;
			
		}
		
		// Echo out the product image
        html += '<div class="resultimg">';
            	
		// Print the start of the link to the product page
		html += '<a href="product.php?id=' + results[0][i].generic_id + '"><img src="images/spp_';
		
		// Check if an image has been supplied
		if(results[0][i].image_url != null){
			
			// Add the image from the database
			html += results[0][i].image_url;	

		} else {
			
			// Print out the generic blank image
			html += 'blank.jpg';
			
		}
		
		// Complete the image by adding the plant name as ALT text	
		html += '" alt="' + results[0][i].latin_name + '" /></a>';
		html += '</div>';
            
		html += '<div class="resultdetails">';
		html += '<a href="product.php?id=' + results[0][i].generic_id + '" class="fll">';
        html += '<span class="resultname">';
        html += '<span class="r_latin fll">' + results[0][i].latin_name + '</span>';
		if (results[0][i].common_name.length > 0){
			html += '<span class="r_common fll">(' + results[0][i].common_name + ')</span>';
		}
       	html += '</span>';
        html += '</a>';
		
        html += '<form class="resultform darkpurp" method="post" action="addtocart.php" id="form_' + results[0][i].generic_id + '" name="searchresultspage">';
        html += '<fieldset class="size_delivery">';
        html += '<fieldset class="resultsize">';
		html += '<input type="hidden" name="oid" id="oid_' + results[0][i].generic_id + '" value="' + results[0][i].oid + '" />';
		html += results[0][i].options;

		//html += $dropdown;
        html += '</select>';
        html += '</fieldset>';
		
		// IS THE PRODUCT IN OR OUT OF STOCK?

		if(results[0][i].stock > 0){
			
			html += '<fieldset class="resultdelivery">';
		    html += '<p class="fll" id="deliveryest_' + results[0][i].generic_id + '">' + results[0][i].delivery_est.substring(13) + '</p>';
			html += '</fieldset>';
			html += '</fieldset>';
			html += '<fieldset class="price_add" id="priceadd_' + results[0][i].generic_id + '">';
			html += '<fieldset class="resultprice flr">';
			html += '<p class="bold fll" id="price_' + results[0][i].generic_id + '">' + results[0][i].price_1 + '</p>';
			html += '</fieldset>';
			html += '<input type="hidden" name="typ" value="1">';
			html += '<input type="submit" value="Add to basket" name="addtobasketlink" class="addtobasketsm button flr" id="addbtn_' + results[0][i].generic_id + '" />';	
			
		} else {
			
			html += '<fieldset class="resultdelivery">';
        //html += '<p class="fll" id="deliveryest_' + results[0][i].generic_id + '">' + results[0][i].delivery_est.substring(13) + '</p>';
      		html += '</fieldset>';
			html += '</fieldset>';
			html += '<fieldset class="price_add" id="priceadd_' + results[0][i].generic_id + '">';
		    html += '<fieldset class="red bold flr w100 text-center mt5">';
			html += 'Out of stock';
			html += '</fieldset>';
			
		}
		
        html += '</fieldset>';
        html += '</form>';
        html += '</div>';
        
		// Close panel div
		html += '</div>';
		p++;
	}

	document.getElementById('resultsstage').innerHTML = html;
	document.getElementById('resultsnumber').innerHTML = results[1];
	$('.js_pagination').html(results[3]);
	$('#checkbox_facet').html(results[4]);
	
	$("#resultsnumberholder").animate({backgroundColor: '#8a90bb'}, 300).delay(800).animate({backgroundColor: '#d0d3c2'}, 1000);
	
	for (i = 0; i < results[2].length; i++) {
	  
	  if(results[2][i].select == 'flowering_month'){
	    $("#flowering_season").html(results[2][i].options);
	    $("#flowering_season").attr('disabled', results[2][i].state);
	  } else {
	    $("#" + results[2][i].select).html(results[2][i].options);
	    $("#" + results[2][i].select).attr('disabled', results[2][i].state);
	  }
	
	}
	
	$('.faceted').each(function(){

		if($(this).val() != 0){
			$(this).css({'font-weight' : 'bold'});
		} else {
			$(this).css({'font-weight' : 'normal'});
		}
	})
	
	var order_price = results[3]['order_price'];
	$('#order_price').attr('order', order_price);
	
	$('#order_price').click(function(){
	
		var order = $(this).attr('order');
		
		// Call the PHP script using the GET method
		ajax.open('get', 'updateresults.php?o=' + encodeURIComponent(order));
	
		// Assign the function that handles the response
		ajax.onreadystatechange = handleUpdate;
		
		// Send the request
		ajax.send(null);
	
		return false;
					
	});
		
}

function updShip(){
  
  // Check the AJAX object is available
  if(ajax){
   
     var split = $(this).val();
     
     // Call the PHP script using the GET method
     ajax.open('get', 'order_splitter.php?split=' + encodeURIComponent(split));
    
    // Assign the function that handles the response
    ajax.onreadystatechange = handleSplit;
    
    // Send the request
    ajax.send(null);
    
    return true;

  }
  
}

function handleSplit(){
	
	// Check the status of the ajax call
	if((ajax.readyState == 4) && (ajax.status == 200)){
		
		// Check for a positive response
		if(ajax.responseText.length > 5){
			
			updateShip(eval('(' + ajax.responseText + ')'));
			
		}
		
	}
	
}

function updateShip(shipping){
  
  $('#devpri1').html(shipping[0]);
  $('#totdev').html(shipping[1]);
  $('#pay_tot').html(shipping[2]);
    
}

function imgSwap(){

	var a = $(this).attr('src').substring(10);
	var b = $("#js_imagecanvas").attr('src').substring(10);
	
	$("#js_imagecanvas").attr('src', 'images/mpp' + a);
	$(this).attr('src', 'images/sbp' + b);
	
}
