// Elegant.com
// AJAX Basket & Overlay Engine
// Uses 2 slightly different techniques
// 1 For Grid View
// 1 For product view to allow configurable products to be added to basket

// Release Version 1.0
// 8th November 2009


// prepare the form when the DOM is ready 
var basket_in_action = false;
var overlayTimeoutId = 0;
// Useful javascript routines

// Simple StrPos function for Javascript
	function strpos (haystack, needle, offset) {
	var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
	return i === -1 ? false : i;
	}
	
// Simple Left function for Javascript	
	function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
	
}

// Simple Right function for Javascript
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str; 
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}



$j(document).ready(function() { 
$j('#ajax_basket').hide();
	  var options = { 
        target:        '#ajax_basket',   // target element(s) to be updated with server response 
        beforeSubmit:  showRequest,  // pre-submit callback 
        success:       showResponse  // post-submit callback 
 
        // other available options: 
        //url:       url         // override for form's 'action' attribute 
        //type:      type        // 'get' or 'post', override for form's 'method' attribute 
        //dataType:  null        // 'xml', 'script', or 'json' (expected server response type) 
        //clearForm: true        // clear all form fields after successful submit 
        //resetForm: true        // reset the form after successful submit 
        // $.ajax options can be used here too, for example: 
        // timeout:   000 
    } ;
 	 $j('#buy_button_form').ajaxForm(options);
}); 
 
// pre-submit callback 
// Main Handler for Adding item to basket on Product Page
function showRequest(formData, jqForm, options) { 
    //loop form data and make sure we can add to cart
	var can_add = true;
	if (validateForm()) {
		for ( var i=0, len=formData.length; i<len; ++i ){
			var current_key = formData[i].name;
			if(current_key.indexOf("super_attribute") >= 0){
				var current_value = formData[i].value;
				if(current_value){
					if( basket_in_action == true ){
						alert("Please wait...An item is being added to your basket.");
						can_add = false;
						return false;
					}
				}else{
					can_add = false;
					alert("Please choose a product option");
					return false;
				}
			}
		}
	}else{
		can_add = false;
	}
	
	if(can_add){
		basket_action_main("product",0,"");
		return true;
	}else{
	 return false;
	}
} 
 
// post-submit callback 
function showResponse(responseText, statusText)  { 
basket_action_process_product();
	
	//restore qty field after submit clears it
	if($j('#qty')){
		if(!$j('#qty').val()){
			$j('#qty').val('1');
		}
	}
	//grayOut(false);
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxSubmit method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
	// $('#ajax_loader').fadeOut('fast');
    // $j('#basket_wrapper').fadeOut('slow');	
//	handle_BasketResponse("product","");	

 }
 

 // Basket Action Invoke

function basket_action_main(pageType,butId,locString)
	{
		if( check_basket_action_state() == false )
			{
			return false;
			}
			else
			{
			basket_in_action = true;
			
			if(pageType == "product")
				{
				locString = "";
				}
			toggle_buy_buttons(pageType,butId,"on");
			if( pageType == "grid")
				{
				basket_action_process_grid(butId,locString);
				}
			}
	}
	
// Process Grid Call
function basket_action_process_grid(butId,locString)
	{
	$j.post(locString,function(data) { 
		verify_post_data = check_post_data_message(data);
		build_screen_messages(verify_post_data,data);
		toggle_buy_buttons("grid",butId,"off");	
		});
	}
// Process Product Page Call
function basket_action_process_product()
	{
	pp_data = $j('#ajax_basket').html();
	verify_post_data = check_post_data_message(pp_data);
	build_screen_messages(verify_post_data,pp_data);
	toggle_buy_buttons("product",0,"off");	
	}
	
	
	// Entry point for Grid Buy Button Call
	
	function action_grid_button(butId,locString)
		{
		basket_action_main("grid",butId,locString)
	//	basket_action_process_grid("grid",butId,locString)
		}
		
	
  // If we are already performing a basket action then alert the customer and do nothing

 function check_basket_action_state()
		{
		if( basket_in_action == true )
			{
			alert("Please wait...An item is being added to your basket.");
			return false;	
			}		
		}
		
//  Fade Out Buttons
 function toggle_buy_buttons(pageType,butId,switchType)
	{
	if( switchType == "on" )
		{
	
				
			if( pageType == "product" )
				{
				//$j('#buy_submit_button').removeClass('buy_btn');
				$j('#buy_button_grid_ajax').show();
				}
			if( pageType == "grid" )
				{
				$j('#bbg_'+butId).removeClass('buy_btn');
				$j('#bbg_'+butId).addClass('buy_button_grid_ajax');
				}
			
		}
		
	if( switchType == "off")
		{
		if( pageType == "product" )
			{
			//$j('#buy_submit_button').removeClass('buy_button_grid_ajax');
			$j('#buy_button_grid_ajax').hide();

			}
		if( pageType == "grid" )
			{
			$j('#bbg_'+butId).removeClass('buy_button_grid_ajax');
			$j('#bbg_'+butId).addClass('buy_btn');
			}
			basket_in_action = false;
		}
	}
	

function check_post_data_message(data_message)
	{
	data_message = data_message.toLowerCase();
		// Correct basket message should contain a double || in it.
		pipe_point = data_message.indexOf("||");
		cookies_disabled = data_message.indexOf("what are cookies");
		if(cookies_disabled > 1 )
			{
			return "cookies";
			}	
		if(!data_message || data_message == "" || data_message.length < 5 )
			{
			return "empty";
			}
		if(!pipe_point || pipe_point == 0 || pipe_point == -1 )
			{
			return "nopipes";
			}	
	 // Basket message should never be longer than 2500 bytes, if it is then error.	
	// If the basket message can genuinely be longer than this then raise this threshold.
		if( data_message.length > 2500 )
			{
			return "longstring";
			}
			return "passed";
		}
		
	function build_screen_messages(verify_post_data,post_data)
		{
		if( verify_post_data == "cookies" )
				{
				basket_overlay_message = "You seem to have cookies disabled. Please enable to continue shopping. Refresh and try again";
				render_overlay(basket_overlay_message,"cookies");
				}
			if( verify_post_data == "pipes" || 	verify_post_data == "empty" || verify_post_data == "longstring" )
				{
				basket_overlay_message = "Error encountered. Please try again";
				render_overlay(basket_overlay_message,"error");
				}
			if( verify_post_data == "passed" )
				{
				basket_overlay_message = split_basket_message_dialogue_box(post_data);
				basket_box_html = split_basket_message_basket_controller(post_data);
				render_overlay(basket_overlay_message,"passed");
				update_basket_box(basket_box_html);
				}
		}
		
	// Get message for dialogue box overlay	
	function split_basket_message_dialogue_box(basket_message)
		{
		pipe_point = strpos(basket_message,'|',0);
		dialogue_box_message = Left(basket_message,pipe_point);
		return dialogue_box_message;
		}
		
	// Get message for basket controller at top of the page	
	function split_basket_message_basket_controller(basket_message)
		{
		pipe_point = strpos(basket_message,'|',0);
		basket_controller_message = Right(basket_message,(basket_message.length-pipe_point)-2);
		return basket_controller_message;
		}	
		
	function update_basket_box(basket_box_html)
		{
		$j('#basket_content').empty(); // Empty the basket box
		$j('#basket_content').hide();
		$j('#basket_content').append(basket_box_html);
		$j('#basket_content').fadeIn('slow');
		}
		
	function render_overlay(basket_overlay_message,action_outcome)
		{
		clearTimeout(overlayTimeoutId);
		$j('#basket_dialogue_box').empty();
		$j('#basket_dialogue_overlay').show();
		$j('#basket_dialogue_box').fadeIn("800");
		$j('#basket_dialogue_box').append(render_message(basket_overlay_message,action_outcome));
		
		$j(document).ready(function() {
		$j('#overlay_close').click(function() {
		clearTimeout(overlayTimeoutId); clear_overlay(); 
		}); 
		$j('#close_topCorner').click(function() {
		clearTimeout(overlayTimeoutId); clear_overlay(); 
		}); 
		
		});
		overlayTimeoutId = setTimeout( function() { clear_overlay(); },10000 );
		}
		
	function render_message(basket_overlay_message,action_outcome)
		{
		lowercase_basket_overlay_message = basket_overlay_message.toLowerCase();
		bdo_msg_class = "";
		bdo_title_class = "";
		bdo_title_string = "";
		
		if(action_outcome == "passed")
			{
			outcome_success = lowercase_basket_overlay_message.indexOf("successfully added to your shopping");
			outcome_nostock = lowercase_basket_overlay_message.indexOf("not available");
			//alert(outcome_success+' '+outcome_nostock);
			
			if( outcome_success > 1 )
				{
				bdo_title_class = "basket_dialogue_overlay_title_success";
				bdo_title_string = "Thank You";
				bdo_msg_class = "basket_dialogue_overlay_msg_success";
				tmp_success_msg = basket_overlay_message;
				tmp_success_msg = tmp_success_msg.replace("success:","");
				tmp_success_msg = tmp_success_msg.replace("was successfully added to your shopping cart.","");
				tmp_success_msg = tmp_success_msg.replace("was successfully added to your shopping basket.","");
				tmp_success_msg = tmp_success_msg.replace("was successfully added to your basket.","");
				basket_overlay_product = tmp_success_msg;
				basket_overlay_message = '<div id="basket_dialogue_overlay_product">' + basket_overlay_product + '</div>';
				basket_overlay_message += '<div id="basket_dialogue_overlay_msg_success">has been added to your shopping basket.</div>';
				}
				
			if( outcome_nostock > 1 )
				{
				bdo_title_class = "basket_dialogue_overlay_title_stock";
				bdo_title_string = "Sorry...";
				bdo_msg_class = "basket_dialogue_overlay_msg_error";
				basket_overlay_message = '<div id="basket_dialogue_msg_error">We have just gone out of stock of that item</div>';
				}
			}
		if( action_outcome == "cookies" )
			{
			bdo_title_class = "basket_dialogue_overlay_title_error";
			bdo_title_string = "Ooops...";
			basket_overlay_message = '<div id="basket_dialogue_msg_error">' + basket_overlay_product + '</div>';
			}
		if( bdo_title_string == "" )
			{
			action_outcome = "error";
			}
			
		if( action_outcome == "error" )
			{
			bdo_title_class = "basket_dialogue_overlay_title_error";
			bdo_title_string = "Sorry...";
			basket_overlay_message = '<div id="basket_dialogue_msg_error">' + basket_overlay_product + '</div>';
			}
		
		m_html = '<div id="basket_dialogue_overlay_wrapper"><div class="cart_title"><p>Product Added to Cart</p><a id="close_topCorner" href="#">Close</a></div><div id="basket_dialogue_overlay_main_area">';
		m_html += '<div id="'+bdo_title_class+'">' + bdo_title_string + '</div>';
		m_html += basket_overlay_message;
		m_html += '</div>';
		m_html += '<div id="overlay_buttons"><button class="black_button right" onclick="setLocation(\'../../../../../../../../../../checkout/onepage \')" id="overlay_view"><span>Checkout</span></button><a class="continue-button left" id="overlay_close">Continue Shopping</a></div>';
		m_html += '</div>';
		return m_html;
		}
	
	$j(document).ready(function() {
		$j('#basket_dialogue_overlay').click(function() {clear_overlay();});
	});	
	
	function clear_overlay() {
		$j('#basket_dialogue_overlay').hide(); 
		$j('#basket_dialogue_box').fadeOut(1500); 
	}
	
	
	
	
