function showRequest(formData, jqForm, options) { 
    var queryString = $.param(formData); 
    return true; 
} 

// post-submit callback 
function showResponse(responseText, statusText)  { 
	init_contact();//after errors reset
}

function showError(responseText, statusText)  { 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\nThe output div should have already been updated with the responseText.'); 
}

function changeQuantity(obj, direction, show_error){
    // alert($(obj).attr('href'));
    
    number = $(obj).attr('href').substring($(obj).attr('href').indexOf("#")+1);
    frm = document.forms['form-'+number];
    target = frm.quantity;
    target.value = parseInt(target.value)+direction;

    if(show_error==true){
        $("#error"+number).show();
    }
    if(direction>0){
        if(target.value>parseInt($(obj).parent("form").children("input[name=total_in_stock]").val())){
            target.value = parseInt(target.value)-direction;
            $("#error"+number).show();
            return false;
        }
    }
	$(obj).parent("form").ajaxSubmit(
	    {
	        success:function(data){
		        basket_contents = data.substring(data.indexOf('<!--cartcontent!-->')+'<!--cartcontent!-->'.length, data.lastIndexOf('<!--cartcontent!-->'));
		        $("#ajaxwindow").html(basket_contents);
		        init_cart();
	        }, 
	        error:showError
	    });
	preLoad();
}


function preLoad(){
    $("#ajaxwindow").html('<img src="/static/custom/images/preloader_2.gif" width="32" height="32" alt="Ajax Loader" id="loader">').show()
}

function init_cart(){
	$(".remove_form").children("input").hide();
	$(".qtyform").children("input").hide();
	$(".delete").click(function(){
        preLoad();
	    $(this).parent("form").ajaxSubmit(
	        {
	            success:function(data){
                // alert("Success");
    		    basket_contents = data.substring(data.indexOf('<!--cartcontent!-->')+'<!--cartcontent!-->'.length, data.lastIndexOf('<!--cartcontent!-->'));
    		    $("#ajaxwindow").html(basket_contents);
    		    init_cart();
    	        },
    	        error:showError
    	    }
    	);
		return false;
	});
	$(".decrease").click(function(){
		changeQuantity($(this),-1);
		return false;
	});
	$(".increase").click(function(){
		changeQuantity($(this),1);
		return false;
	});
	$("#continue_shopping").click(function(){
	    preLoad();
		$("#ajaxwindow").html("").hide();
		return false;
	});
	$("#shipping_select").change(function(){
	    preLoad();
		pk = $(this).val();
		$.cookie('shipping_id', pk);
		$("li#cart a").click();
	});
	$(".error").hide();
    $("form input[name=total_in_stock]").each(function(){
        diff = $(this).val()-$(this).parents("form").children('input[name=quantity]').val();
        if(diff<0){
            //too many ordered
            changeQuantity($(this).parents("form").children(".decrease"),diff,true);
            $(this).parents("form").children(".error").show();
        }
    });
}

function b4s(){
    alert("B4");
}

function showError(XMLHttpRequest, textStatus, errorThrown){
    alert(XMLHttpRequest+"--"+textStatus+"--"+errorThrown);
}
// bind form using 'ajaxForm' 
function init_contact(){
	$("a.close-contact").click(function(){
		$("#ajaxwindow").html("").hide();//ready for next set of contents
	});
	$('#contact_form').ajaxForm(
	    { 
        target:        '#ajaxwindow',   // target element(s) to be updated with server response 
        success:       showResponse,  // post-submit callback 
        // beforeSend: b4s,
        error: showError
        }
    );
}



$(document).ready(function(){
	// hide children 
	p = document.location.href;
	if (p.indexOf('archive')!=-1){
	    $("a[href="+p.substring(p.indexOf('/archive'))+"]").addClass('active');
	}else{
	    $("ul#menu").children("li").children("ul").hide();
	}
	

	// toggle children if click on parent
	$("li.slide").children("a").click(function(event) {
			$(this).next("ul").slideToggle(200);
			return false;
	});
	//check for archive page
	$("li#cart a").click(function(){
		preLoad();
		$("#ajaxwindow").load("/cart/ #basketform", undefined, function(){init_cart()}).show();
		return false;
	});
	$("#mailinglist a").click(function(){
		preLoad();
		//$("#right").toggle();
		$("#ajaxwindow").load('/mailing_list_form/', undefined, function(){
			init_contact();
		}).show();	
		return false;
	});
	$("a.open-feedback").click(function(){
		preLoad();
		//$("#right").toggle();
		$("#ajaxwindow").load('/feedback_form/', undefined, function(){
			init_contact();
		}).show();	
		return false;
	});
	$("#contact a").click(function(){
		preLoad();
		//$("#right").toggle();
		$("#ajaxwindow").load('/contact_form/', undefined, function(){
			init_contact();
		}).show();	
		return false;
	});
	$("a:contains('Back one step')").click(function(){
	    history.back();
	    return false;
	})
	/*close cart*/
	l = document.location.href;
	if(l.substring(l.length-1)=="/"){
	    l = l.substring(0,l.length-1);
	}
	url = l.substring(l.lastIndexOf("/"));
	$('a[href='+url+']').addClass('active');
});


var SSS = {

    // handle a form submission
    // including updating the cart quantity
    updatestatus : function(json, result_tgt, count_tgt) {

        var result = json.results;
        if (result == "Success") {
            result = 'ITEM ADDED!';
        }
        $(result_tgt).html(result);
        errors = json.errors;
        if (errors > 0) {
            for (var i = 0; i<errors.length; i++) {
                which = errors[i][0];
                err = errors[i][1];
                if (which == 'quantity') {
                    $('#label-quantity span.error').html(err);
                }
                else if (which == 'product') {
                    var t = tgt.html();
                    tgt.html(t + '<br/>' + err);
                }
            }
        }
        else {
            var ct = '(' + json.cart_count + ' Item';
            if (json.cart_count != 1) {
                ct = ct + 's';
            }
            ct = ct + ')';
            $(count_tgt).text(ct);
			
        }
    },

    validate : function(formArray, jqForm, tgt) {

        var qty = 0;
        for (var i = 0; i<formArray.length; i++) {
            var elt = formArray[i];
            if (elt.name == 'quantity') {
                qty = elt.value;
            }
        }
        if (! parseInt(qty)>0) {
            $('#label-quantity span.error').html("Choose a quantity");
            return false;
        }
        return true;
    },
    error: showError

}


