(function($) {

	$.extend({
		add2cart: function(source_id, target_id, callback) {
    
      var source = $('#' + source_id );
      var target = $('#' + target_id );
      
      var shadow = $('#' + source_id + '_shadow');
      if( !shadow.attr('id') ) {
          $('body').prepend('<div id="'+source.attr('id')+'_shadow" style="display: none; background-color: #ddd; border: solid 1px darkgray; position: static; top: 0px; z-index: 100000;">&nbsp;</div>');
          var shadow = $('#'+source.attr('id')+'_shadow');
      }
      
      if( !shadow ) {
        //alert('Cannot create the shadow div');
      }
      
      shadow.width(source.css('width')).height(source.css('height')).css('top', source.offset().top).css('left', source.offset().left).css('opacity', 0.5).show();
      shadow.css('position', 'absolute');
      
      shadow.animate( { width: target.innerWidth(), height: target.innerHeight(), top: target.offset().top, left: target.offset().left }, { duration: 300 } )
        .animate( { opacity: 0 }, { duration: 100, complete: callback } );
        
		}
	});
})(jQuery);

var $hhCheckoutCurrentStep;

function setupCheckoutAjax(el) {
	
	if($.browser.msie) {
		if ($.browser.version < 7) {
			return;
		}
	}

	$.historyInit(hashLoader);
	setupAjaxButtons(el);
	$.historyLoad(getCurrentStepNo());
	//$('#checkout-form-content').accordion({header: 'h3', autoHeight: false, clearStyle: true});
	//setCheckoutStep();
}

function hashLoader(hash, old) {
	if(hash) {
		// restore ajax loaded state
		if($.browser.msie) {
			// jquery's $.load() function does't work when hash include special characters like aao.
			hash = encodeURIComponent(hash);
		}
		old = old || $hhCheckoutCurrentStep || getCurrentStepNo();
		if (old && (old != hash)) {
			var direction = (old > hash ? 'back' : 'next');
			
			$("#checkout-form-holder").addClass("ajaxLoading");
			href = window.location.href.replace(/(#|\?).*$/, '') + "?cfs=" + hash;
			
			$.get(href, function(data) {
				showScrollStep(data, direction);
			});
		}
	}
}

function setupAjaxButtons(el) {
	
	if($.browser.msie) {
		if ($.browser.version < 7) {
			return;
		}
	}
	
	el = el || "#checkout-form-holder";
	
	var $holder = $(el);
	
	if (!$holder || !$holder.length) {
		top.location.reload();
	}
	
	/*$(".checkoutStepBlock.canAjax .checkoutStepData", $holder).each(function() {
		if (!$(this).find(".checkoutStepAjaxSubmit").lenth) {
			$(this).append('<button class="checkoutStepAjaxSubmit" onclick="return submitCheckoutStep(this);">continue</button>');
		}
	});*/
	
	var $back = $("#order_back_button a", $holder);
	$back.click(loadBackStep);
	
	$("#order_next_button input", $holder).click(submitCheckoutStep);
	
	/*
	$(".expose", $holder).bind("click keydown", function() { 
 
        $(this).expose({ 
 
            // custom mask settings with CSS 
            maskId: 'exposeMask', 
 
            // when exposing is done, change form's background color 
            onLoad: function() { 
                this.getExposed().css({backgroundColor: '#eeeeee'}); 
            }, 
 
            // when "unexposed", return to original background color 
            onClose: function() { 
                this.getExposed().css({backgroundColor: null}); 
            }, 
 
            api: true 
 
        }).load(); 
    });*/
	
	// select all desired input fields and attach tooltips to them 
	$(":input", $holder).tooltip({ 
	
	    // place tooltip on the right edge 
	    position: ['bottom', 'left'], 
	 
	    // a little tweaking of the position 
	    //offset: [45, 255], 
	 
	    // use a simple show/hide effect 
	    effect: 'toggle', 
	     
	    // custom opacity setting 
	    opacity: 0.8,
		
		tip: ".tooltip"
	});
	
	$(".tooltip", $holder).hide();
	
	$(".infoBoxPopup", $holder).each(function() {
		
		$(this).attr("title", "");
		
		$(this).after($(this).find("span").clone().addClass("tooltipPopup"));
		
		$(this).tooltip({
		    position: ['top', 'center'], 
		 
		    // a little tweaking of the position 
		    offset: [5, 0], 
		 
		    // use a simple show/hide effect 
		    effect: 'slideup', 
		     
		    // custom opacity setting 
		    opacity: 0.8,
			
			tip: "span"
		});
	});
	
	fixJSElements($holder);
	
	/*$(".viewCart a", $holder).click(function() {
		var api = $(this).overlay({oneInstance: false, api: true});
		api.load();
	});*/
	
	$(".viewCart a", $holder).fancyZoom({directory: "images/design/fancyzoom"});
	
	$(window).trigger('load');
	
	/*var baseHref = window.location.href.replace(/(#|\?).*$/, '');
	window.location = (baseHref + '#' + getCurrentStepNo());
	
	$.historyLoad(getCurrentStepNo());*/
	
	$(".steps a", $holder).click(function(e) {
		var href = window.location.href;
		
		if (href.match(/checkout(?:\?cfs=\d+)?/)) {
			e.preventDefault();
			e.stopPropagation();
			
			var h = $(this).attr("href").replace(/^.*?cfs=/, "");
			$.historyLoad(h);
		} else {
			window.location.replace($(this).attr("href"));
			e.preventDefault();
			e.stopPropagation();
		}
	});
	
	$(".checkEmptyNFocusIfNot", $holder).each(function() {
		if ($(this).val()) {
			$(this).focus().click();
			$(this).attr("autoset", $(this).val());
		}
	});
	
}

function getCurrentStepNo() {
	var stepNo, $holder = $("#checkout-form-holder");
	var stepBlock = $("div.layout", $holder);
	stepNo = stepBlock.attr("id").replace(/[^\d]+/g, '');
	return stepNo;
}

function loadBackStep(e) {

	e.preventDefault();
	e.stopPropagation();
	
	$("#checkout-form-holder").addClass("ajaxLoading");
	
	$.get(this.href, showScrollStep);
}

function showScrollStep(data, direction) {
	
	if (!data) {
		top.location.reload();
	}
	
	direction = (direction == 'next') ? direction : 'back';
	
	var $old = $("#checkout-form-holder"), $h = $old.height(), $w = $old.width();
	$old.wrap('<div id="scrollWrapper" class="innerBody"><div class="items"></div><div class="scrollWrapperBottom"></div></div>');
	var $scroller = $("#scrollWrapper");
	var $data = $(data);
	$scroller.height($h);
	
	$scroller.prepend($old.find(".top"));
	
	var api = $scroller.scrollable({
		api: true,
		size: 1,
		speed: 0,
		keyboard: false,
		clickable: false
	});
	
	var doPage = 1;
	var conf = api.getConf();
	
	if (direction == 'back') {
		//$data.hide();
		api.getItemWrap().prepend(data);
		$data = api.getItemWrap().children(":first");
		conf.speed = 0;
		
		doPage = 0;
		api.reload();
		api.setPage(1);
		//$data.show();
	} else {
		api.getItemWrap().append(data); 
		$data = api.getItemWrap().children(":last");
		api.reload();
	}
	
	fixJSElements($data);
	
	conf.speed = 800;
	conf.easing = "backout";
	
	var $h2 = $data.height();
	
	if ($h2 > $h) {
		$scroller.animate({height: $h2}, function() {doSetPage(api, $scroller, doPage, data, $h2);});
	} else {
		doSetPage(api, $scroller, doPage, data, $h2);
	}
}

function fixJSElements($holder) {
	$("select:not(.addressSelector)", $holder).uniform();
	
	if($.browser.msie && $.browser.version < 7){
		// can do something for IE6 users
	} else {
		$(":radio", $holder).uniform();
	}
	
	$(":checkbox", $holder).uniform();
}

function doSetPage(api, $scroller, doPage, data, $h2) {
	api.setPage(doPage, function() { 
		$scroller.animate({height: $h2}, function() {
			$scroller.replaceWith(data); 
			setupAjaxButtons();
			var cs = getCurrentStepNo();
			if ($.historyCurrentHash != cs) {
				$.historyLoad(getCurrentStepNo());
			}
		});
	});
}

function showNextStep(data) {
	showScrollStep(data, 'next');
}


function updateFormContent(data) {
}

function submitCheckoutStep(e) {
	var $form = this.form;
	
	var $data = $(":input", $form).serializeArray();
	//$dataBlock
	$("#checkout-form-holder").addClass("ajaxLoading");
	try {
		$.post($form.action, $data, processCheckoutResponse, 'html');
	} catch (ex) {
		return true;
	}
	e.preventDefault();
	e.stopPropagation();
	
	return false;
}


function doAjaxOfferStatusUpdate(e, stepNo, refresh_id, ns) {
	var $data = $("#"+refresh_id+" :input").serializeArray();
	$data.push({name: ns + "["+stepNo+"]" + "[ajaxUpdate]", value: true});
	
	$("#checkout-form-holder").addClass("ajaxLoading");
	$.post(e.form.action + "?cfs=" + stepNo, $data, processCheckoutResponse, "html");
	
	return false;
}


function processCheckoutResponse($data) {
	
	if (!$data) {
		top.location.reload();
		return;
	} else {
		/*if ($data[0]=='{') {*/
		if ($data.match(/^\{/)) {
			$data = eval("("+$data+")");
		} else {
			top.location.href = this.url;
			return;
		}
	}
	
	if ($data.stay) {
		$("#checkout-form-holder").replaceWith($data.content);
		setupAjaxButtons();
	} else if ($data.redirect) {
		window.location.replace($data.redirect);
	} else {
		showNextStep($data.content);
	}
}



/** steps code **/
function checkAddressChange(el) {
	var val = $(el).val();
	
	if (val == 'n/a') {
		$("#checkout-additional-directions").hide();
		$("#checkout-address-not-listed").show();
		$(el).addClass('addressSelectorSmall');
	} else {
		$(el).removeClass('addressSelectorSmall');
		$("#checkout-additional-directions").show();
		$("#checkout-address-not-listed").hide();
	}
}

function switchLocInfoBox(el) {
	$(".locationInfoBox").hide();
	$("#location-info-box-" + $(el).val()).show();
}













function buildOrderHook() {
	return;
	$("#edit_panel_main_table input.img-link", this).click(function() {
		$.add2cart('edit_panel_main_table', 'my-order-items', function() {
			$("#edit_panel_main_table_shadow").remove();
		});
	});
}
