$(document).ajaxStart(function() {
    $('#loading').fadeIn();
    $("#wrapper").fadeTo(0, 0.6);
});
$(document).ajaxComplete(function() {
    $('#loading').fadeOut('fast');
    $("#wrapper").fadeTo(0, 1);
});
//function loader

$(document).ready(function() {

	$("body").append('<div id="loading" ></div>');
	var baseUrl = $('#baseUrl').val();
	
  // Step by step instr	
	$("a.onlineorderlink").live('click', function() { 
		// ??? doesn't works
		// $("#onlineorderdiv").slideToggle("slow");
		if($("#onlineorderdiv").css('display')=='none')
			$("#onlineorderdiv").slideDown("slow");
		else {
			$("#onlineorderdiv").slideUp("slow");}
		return false; 
	});
	// @todo
	/*$("#clearcart").live('click',function(e) {
        e.preventDefault();
        $(this).nyroModal();
        return false;
    });*/
	
  // FAQ
	$(".accordian h3:first").addClass("active");
	$(".accordian h3:not(:first)").removeClass("active");
	$(".accordian p:not(:first)").hide();									
	$(".accordian h3").live('click', function(){
		$(this).next("p").slideToggle("slow")
		.siblings("p:visible").slideUp("slow");
		$(this).toggleClass("active");
		$(this).siblings("h3").removeClass("active");
	});
	
// --- SHOPPING CART --- //
	
  // ADD TO CART
	if($.cookie("dontShowWarnings") == null)
		$.cookie("dontShowWarnings", 0); // it's for user
	var noticed = false; // it's for us, to prevent warnings in opened popup
	$('form.addtocart').livequery('submit', function() {
		var form = $(this);
		// options for ajax submit
		var addOptions = {
	        dataType: 'json',
	        success : function(responseText) {
	            $('#cartcontent').html(responseText.content).highlightFade({speed:900});
	          // show postage box
	            if((responseText.cartitems == 1)) {
	            	showPostage();
	            }
	          // update postage box
	            else if(responseText.cartitems > 1) {
	            	if (responseText.postage != null) {
	            		updatePostage(responseText.postage, responseText.carttotal);
	            	}
	            }
	            noticed = false;
	        }
	    };
		//console.log('noticed:'+noticed+' dontShowWarnings:'+$.cookie("dontShowWarnings"));
	  // check if seal has multiple profiles
		if(($.cookie("dontShowWarnings") < 1) && (noticed != true)) {
			// callback for request
			var checkOpt = function(data) {
				// if has a multiple profile
				if(data.multiple == true) {
				  // "add to cart" button pressed in popup window
					$('#jqi input.addtocart').live('click', function(e) {
						noticed = true;
	                	  if($('#dontShow').attr('checked'))
	                		  $.cookie("dontShowWarnings", 1);
						$.prompt.close();
					});
					var states = {
						      state0: {
						            html:'<p><i>Notice:</i> selected seal has multiple profiles</p>'
						            	+'<p>If you are sure that selected seal is that what you need, just click <i>continue</i></p>'
						            	+'<p><input type="checkbox" name="dontShow" id="dontShow" /> '
						            	+'<label for="dontShow">Don\'t show me this warning again.</label></p>',
						            buttons: { More: true, Continue: false },
						            focus: 1,
						            submit:function(v,m,f){ 
						                  if(!v) { 
						                	  if($('#dontShow').attr('checked'))
						                		  $.cookie("dontShowWarnings", 1);
						                	  form.ajaxSubmit(addOptions);
							                  $.prompt.close();
						  				      return false;
						                  } else
						                      $.prompt.goToState('state1');
						                  return false; 
						            }
						      },
						      state1: {
						            html:data.html,
						            buttons: { Exit: 0 },
						            focus: 1,
						            submit:function(v,m,f){
					                	  if($('#dontShow').attr('checked'))
					                		  $.cookie("dontShowWarnings", 1);
						                  $.prompt.close();
						                  return false; 
						            }
						      }
						};
					$.prompt(states);
				} else {
					form.ajaxSubmit(addOptions);
				    return false;
				}
				return false;
			};
			// send request to know if it has multiple profiles
			$.post(baseUrl + "/cart/ismultipleprofile", {
				seal: $(this).attr('name')
			}, checkOpt, 'json');
		}
		// if user said "Don't show me this warning again."
		else {
			form.ajaxSubmit(addOptions);
		}
	    return false;
	});

  // DELETE FROM CART
	$('a.deleteitem').live('click', function() {
	    var id = $(this).attr('id');
	    var deleteOptions = {
	        dataType: 'json',
	        success : function(responseText) {
	    	  // html updates
	            if(responseText.cartitems > 0) {
	             // update item count
	                $('span#cartitems_val').html(responseText.cartitems);

	             // update postage box
	                if (responseText.postage != null) {
	                	updatePostage(responseText.postage, responseText.carttotal);
	            	}
	            } else {
	             // remove shopping cart bar
	                $('li#cartitems').html('You have no items in your shopping cart');
	                $('#postage').html('');
	                $('#shoppingoptions').html('');
	            }

	            if(responseText.carttotal > 0) {
	              // update "total" value
	                $('span#carttotal_val').html(responseText.carttotal);
	                $('li#carttotal').highlightFade({speed:900});
	            } else {
	              // remove "total" row
	                $('p#carttotal').remove();
	            }
	            
	          // remove element
	            var el = $('div#cart_'+id);
	            el.fadeOut(450, function () {
	                el.remove();
	            });
	        }
	    };
	    $('form#form_'+id).ajaxSubmit(deleteOptions);
	    $('form#form_'+id).livequery('submit', function() {
	    	return false;
	    });
		return false;
	});
	
  // CLEAR CART
	$('#clearcart').livequery('submit', function() {
		var clearOptions = {
	        dataType: 'json',
	        success : function(responseText) {
				$('#cartcontent').html(responseText.content).highlightFade({speed:900});
                $('#postage').html('');
                $('#shoppingoptions').html('');
	        }
	    };
		var form = $(this);
		// confirm
		var txt = 'Are you sure you would like to empty your cart?';

		function clearcallback(v,m,f){
			if(!v) return true;
        	else
	    	  form.ajaxSubmit(clearOptions);
		}

		$.prompt(txt,{
		      callback: clearcallback,
		      buttons: { Yes: true, Cancel: false }
		});
	    return false;
	});
	
  // POSTAGE
	var showPostage = function(callback)
	{
		$('#postage').load(baseUrl+'/cart/postage');
	};
	// overwrite total postage and totalprice only 
	var updatePostage = function(postage, carttotal)
	{
		$('span#totalpostage').html(postage);
		$('span#totalpostage').highlightFade({speed:900});
		$('span#totalprice').html(postage + carttotal);
		$('span#totalprice').highlightFade({speed:900});
	};
    // submit postcode form
	$('#postcodeform').livequery('submit', function() {
		var pcOptions = {
	        dataType: 'html',
	        success : function(responseText) {
				$('#postage').html(responseText);
				$('#postage').highlightFade({speed:900});
				setTimeout("$('span#invalid_postcode').slideUp()", 12000);
	        }
	    };
	    $(this).ajaxSubmit(pcOptions);
	    $('#reenterpostcode').slideUp();
	    return false;
	});
	// change post code
	$('a.changepostcode').live('click', function() {
		$('#reenterpostcode').slideToggle();
		return false;
	});
	
	// REGISTERED POST
	$('input#registered_post').livequery('change', function() {
		$.post(baseUrl + "/cart/registeredpost", {
			status: $(this).attr('checked')
		}, 
		function(result){
			updatePostage(result.postage, result.carttotal);
		}, 'json');
	});
	// disable for overseas
	$("#country").livequery('change', function() {
		if($this.val() == 'AU') {
			$("#regpost-label, #regpost-element").slideDown();
		} else {
			$("#regpost-label, #regpost-element").slideUp();
		}
	});
	
// --- CHECKOUT --- //
	
  // DELETE ITEM ON CHECKOUT
	$('a.deleteitemcheckout').live('click', function() {
		$("#loading").html("");
	    var id = $(this).attr('id');
	    var deleteOptions = {
	        dataType: 'json',
	        success : function(responseText) {
	    	  // html updates
	            if(responseText.cartitems > 0) {
            	// update "total" value
	                $('span#subtotalCheckout').html(responseText.carttotal);
	                $('span#shippingCheckout').html(responseText.postage);
	                $('span#grandtotalCheckout').html((responseText.carttotal + responseText.postage));
	                $('span#grandtotalCheckout').highlightFade({speed:900});
	            } else {
	             // redirect
	            	window.location = baseUrl+'/';
	            }
	            
	          // remove element
	            var el = $('tr#tr_'+id);
	            el.fadeOut(450, function () {
	                el.remove();
	            });
	        }
	    };
	    $('form#form_'+id).ajaxSubmit(deleteOptions);
	    $('form#form_'+id).livequery('submit', function() {
	    	return false;
	    });
		return false;
	});
	
  // payment method
	$('#ordersums_gateway').change(function(){
		if($(this).val() == 'Credit card') {
			$("#ccgroup-element, #cardsAccept").slideDown();
			$("#nocreditcard-hint").slideUp();
		} else {
			$("#ccgroup-element, #cardsAccept").slideUp();
			$("#nocreditcard-hint").slideDown();
		}
	});
	
  // loader on form submit
	var submitOptions = {
		url : '/checkout',
		dataType: 'json',
		success : function(data) {
			if(data.success == true) {
				window.location = '/checkout/complete';
			} else {
				if(data.error == "payment") {
					$("#fieldset-ccgroup dl").prepend("<ul class='errors'><li>"+data.msg+"</li></ul>");
				} else {
					$('#checkoutform').unbind('submit');
					$('#checkoutform').submit();
				}
			}
		}
	};
	$("#checkoutform").submit(function(){
		$("#loading").html("<span>Processing Order, Please Wait</span>");
		$("#checkoutform ul.errors").fadeOut();
		$(this).ajaxSubmit(submitOptions);
	    return false; 
	});
	
// --- SEARCH --- //
	
	var searchOptions = {
        dataType: 'html',
        success : function(responseText) {
			$('#maincontentarea').html(responseText);
		    $('#maincontentarea').fadeOut('fast',function(){
		    	$('#maincontentarea').fadeIn();
		    });
        }
    };
	$('#Searchbymodel').livequery('submit', function() {
	    $(this).ajaxSubmit(searchOptions);
	    return false;
	});
	$('#searchbysize').livequery('submit', function() {
	    $(this).ajaxSubmit(searchOptions);
	    return false;
	});
	// paginal navigation
	$('a.paginalnavlink').live('click', function() {
		$('#maincontentarea').load($(this).attr('href'));
		return false;
	});
	
	
// --- CUSTOM DOOR SEAL --- //
	
	var validateCommercial = function(){
		if (($('#product_width').val().length > 0) && ($('#product_height').val().length > 0) && ($('#product_profile').val() != 0)) {
			$("#add").removeAttr('disabled');
			$("#add").removeClass('disabledBtn');
			
		} else {
			$("#add").attr('disabled', true);
			$("#add").addClass('disabledBtn');
		}
	};
	$('#customseal').livequery('submit', function() {
		var calcOpt = {
	        dataType: 'json',
	        success : function(responseText) {
				if (responseText.success == true) {
					$('#productpreview').html(responseText.preview);
					$('#productpreview').highlightFade({speed:900});
					$('#productpreview').fadeIn();
					$('ul.errors').html('');
					$('ul.errors').fadeOut();
				} else {
					$('ul.errors').html('<li>' + $.makeArray(responseText.errors).join('</li><li>') + '</li>');
					$('ul.errors').highlightFade({speed:900});
					$('#productpreview').fadeOut();
				}
	        }
	    };
	    $(this).ajaxSubmit(calcOpt);
	    return false;
	});
	$('#product_width').keyup(function() {validateCommercial();});
	$('#product_height').keyup(function() {validateCommercial();});
	$('#product_profile').change(function() {
		validateCommercial();
		$("#profilepreview").load(baseUrl + "/profiles/async-preview", {profile_id: $(this).val()});
	});

	
// --- MATERIALS PER METRE --- //
	$('form.materialtocart').livequery('submit', function() {
		var form = $(this);
		var prodId = form.attr('id').replace('material_','');
		// options for ajax submit
		var addOptions = {
	        dataType: 'json',
	        success : function(responseText) {
	            $('#cartcontent').html(responseText.content).highlightFade({speed:900});
	          // show postage box
	            if((responseText.cartitems == 1)) {
	            	showPostage();
	            }
	          // update postage box
	            else if(responseText.cartitems > 1) {
	            	if (responseText.postage != null) {
	            		updatePostage(responseText.postage, responseText.carttotal);
	            	}
	            }
	            noticed = false;
	        }
	    };
	  // validate
		var qty = $("#product_qty_"+prodId).val();
		var min = $("#min_metre_"+prodId).val();
		if (qty <= 0) {
			$("#product_qty_"+prodId).css('background', '#f55');
			$("#error_hint_"+prodId).html('Qty is required field');
			$("#error_hint_"+prodId).slideDown();
		} else if((qty+0.01) < min) {
			$("#product_qty_"+prodId).css('background', '#f55');
			$("#error_hint_"+prodId).html('Minimum amount of metres is '+min);
			$("#error_hint_"+prodId).slideDown();
		}
		// passed validation
		else {
			$("#error_hint_"+prodId).slideUp();
			$("#product_qty_"+prodId).css('background', '#fff');
			form.ajaxSubmit(addOptions);
		}
	    return false;
	});
	
// CONTACT FORM - profiles preview
	$('#contactform #profile').livequery("change", function(e) {
		if (!$('#profile_preview').length) {
			$('#contactformdiv').append('<div id="profile_preview" style="display:none;border:1px solid black;background:#fff;width:280px;cursor:pointer;height:300px;position:absolute;"></div>');
			var pos = $(this).position();
			$("#profile_preview").css('top', pos.top-35+"px")
    							.css('left', pos.left+250+"px")
    							.livequery('click', function(){$(this).fadeOut();});
		} else
			$("#profile_preview").slideUp();
		$("#profile_preview").load(baseUrl + "/profiles/async-preview", {profile_name: $(this).val()}, function(){$(this).prepend('close<br class="clear"/>').slideDown();});
	});
// enquiry categories
	$('#contactform #category').livequery("change", function(e) {
		$("p.enquiryCategory").slideUp();
		$("p.enquiryCategory").load(baseUrl + "/contact/categorymessage-async", {category_id: $(this).val()}, function(data){
			if(data.length)
				$(this).slideDown();
		});
	});
	
});
