/**
 Comparance.com's Comparo

 URL: https://clients.comparance.com/js/main.js
*/

// ----------------------------------------------------------------------------
// C o n f i g u r a t i o n
// ----------------------------------------------------------------------------

var COMP_DLG_WIDTH				= 600;
var COMP_DLG_HEIGHT				= 480;
var COMP_AUTOCOMPLETE_DELAY		= 500;
var COMP_AUTOCOMPLETEHIDE_DELAY	= 1000;
var COMP_ERROR_TIME		   		= 100;
var COMP_ERROR_FLASHES	   		= 2;
var COMP_CARTTRANSFER_TIME 		= 500;
var COMP_CARTHIGHLIGHT_TIME		= 200;
var COMP_CARTHIDE_DELAY	   		= 500;
var COMP_CARTSLIDE_TIME	   		= 300;

// ----------------------------------------------------------------------------
// I n i t i a l i z a t i o n
// ----------------------------------------------------------------------------

// Use a custom jQuery alias in order to allow clients to use other libraries
// (ie: prototype)
var $j = jQuery.noConflict();

// Static frames, these are always present no matter which page is displayed
var compNavContent, compCartBtn, compCartContent, compContent, compDialog;

// Wether brands or types are used for the index
var listBrands = true;

/**
 When the document is ready..
*/
$j(function() {
	// Prevent the browser from caching ajax requests
	jQuery.ajaxSetup({cache:false});

	// Grab the static frames
	compNavContent = $j("#compNavContent");
	compCartBtn = $j("#compCartBtn");
	compCartContent = $j("#compCartContent");
	compContent = $j("#compContent");
	compDialog = $j("#compDialog");

	// Prevent the browser from following href="#"
	$j("#compFrame *").click(function(e){if(e.target != "http://www.comparance.com/") return false;});

	// Show the loading div when requests are pending
	var compLoading = $j("#compLoading");
	compLoading.ajaxStart(function(){$j(this).fadeIn();});
	compLoading.ajaxStop(function(){$j(this).fadeOut();});

	// Cart is initially hidden
	compCartContent.css({display: "none"});

	// Handle cart button clicks
	compCartBtn.click(function() {
		if(compCartContent.css('display') == 'none') showCart();
		else hideCart();
	});

	// Handle automatic cart hiding
    compCartBtn.mouseover(onCartOver);
	compCartBtn.mouseout(onCartOut);
	compCartContent.mouseover(onCartOver);
	compCartContent.mouseout(onCartOut);

	// Create the dialog box for compares
    compDialog.dialog({
    	autoOpen:	false,
	  	bgiframe:	true,
		modal:		true,
		width:		COMP_DLG_WIDTH,
		height:		COMP_DLG_HEIGHT
	});

	// Load the brands index
	listBrands = !listBrands;
	toggleList();
});

// ----------------------------------------------------------------------------
// N a v i g a t i o n
// ----------------------------------------------------------------------------

/**
 Toggle the list type
*/
function toggleList() {
	listBrands = !listBrands;

	if(listBrands) showBrands();
	else showBrandTypes();
}

function baseUrl() { return send_form+"&listBrands="+(listBrands ? "1" : "0"); }

/**
 Query the navigation
*/
function showMenu(brand, type, model_number) {
	$j.get(baseUrl()+"&type=menu&brand="+escape(brand)+"&atype="+escape(type)+"&model_number="+escape(model_number), function(ret) {
	   compNavContent.html(ret);
	});
}

// ----------------------------------------------------------------------------
// B r a n d s  /  T y p e s  /  A p p l i a n c e s
// ----------------------------------------------------------------------------

/**
 Query the list of brands
*/
function showBrands(type) {
	if(type == undefined) type = "";
	$j.get(baseUrl()+"&type=showbrands&atype="+escape(type), function(ret) {
		showMenu('', type, '');
		compContent.html(ret);
	});
}

/**
 Query the list of appliance types for the given brand
*/
function showBrandTypes(brand) {
	if(brand == undefined) brand = "";
	$j.get(baseUrl()+"&type=showbrandtypes&brand="+escape(brand), function(ret) {
		showMenu(brand, '', '');
  		compContent.html(ret);
  	});
}

/**
 Query the list of appliances for the given brand and type
*/
function showAppliances(brand,type) {
	$j.get(baseUrl()+"&type=showappliances&brand="+escape(brand)+"&atype="+escape(type), function(ret) {
		showMenu(brand, type, '');
		compContent.html(ret);
	});
}

// ----------------------------------------------------------------------------
// Q u i c k  C o m p a r e
// ----------------------------------------------------------------------------

/**
 Toggle the quick compare form
*/
function showQuickCompare() {
	var form = $j("#compQuickCompareForm");
	if(form.css('display') == 'none') {
		form.fadeIn();
	}
	else {
        hideQuickCompareError();
		hideAutoComplete();
		form.fadeOut();
	}
}

/**
 Query the compare results for quick compare
*/
function showQuickCompareResults() {
	hideAutoComplete();

	// Collect the values
	var values = "";
	$j("#compQuickCompareForm input").each(function(i, e) {
		if(e.className != 'submit' && e.value != "") {
			if(values != "") values += ",";
			values += e.value;
		}
	});

	if(values == "") return;

	compareRequest = "type=quickcompare&items="+values;
	$j.get(send_form+"&"+compareRequest, function(ret){
		// All good, show the compare dialog
		if(ret.substr(0, 5) != 'ERROR') {
			hideQuickCompareError();
			compareCallback(ret+"<br />");
		}

		// Something went wrong, better warn the user
		else {
			var error = $j("#compQuickCompareForm span");
			error.html(ret.substr(6));
			error.fadeIn();
		}
	});
}

/**
 Query the model numbers for the auto complete feature
*/
function showAutoComplete(e) {
	hideQuickCompareError();

	// Make sure only one timeout is active at a time
	if(queryAutoComplete_t != null) clearTimeout(queryAutoComplete_t);

	// IE doesn't like parameters to setTimeout, so here is a global
	query_e = e;

	// Allow the user some time to type in before flooding them with suggestions
    queryAutoComplete_t = setTimeout(function() {
    	if(query_e.value != '') {
			var autoComplete = $j("#compQuickCompareForm div");
			autoComplete.css('width', query_e.clientWidth+"px");
			autoComplete.css('left', query_e.offsetLeft+"px");
			autoComplete[0].targetInput = query_e;

			$j.get(send_form+"&type=autocomplete&query="+escape(query_e.value), function(ret){
				autoComplete.html(ret);
				autoComplete.css('top', query_e.offsetHeight+"px");
				autoComplete.fadeIn();
	   		});
		}
    }, COMP_AUTOCOMPLETE_DELAY);
}
var queryAutoComplete_t = null;
var query_e;

/**
 Select a model from the auto complete form
*/
function autoComplete(e) {
	var autoComplete = $j("#compQuickCompareForm div");
	autoComplete[0].targetInput.value = $j(e).html();
}

// Hide the quick compare error message / auto complete
function hideQuickCompareError() { $j("#compQuickCompareForm span").fadeOut(); }
function hideAutoComplete() { $j("#compQuickCompareForm div").fadeOut(); }

// Don't let the auto complete popup stick around for too long
var autoComplete_t = null;
function onAutoCompleteOut() {
	autoComplete_t = setTimeout(hideAutoComplete, COMP_AUTOCOMPLETEHIDE_DELAY);
}
function onAutoCompleteOver() { if(autoComplete_t) clearTimeout(autoComplete_t); }

// ----------------------------------------------------------------------------
// C o m p a r e
// ----------------------------------------------------------------------------

var compareRequest;

function printCompare() {
	compDialog.dialog('close');
	window.open('print.php?'+compareRequest);
}

/**
 Query the compare chart for the selected model
*/
function showCompare(model) {
	compareRequest = "type=compare&model_number="+escape(model);
	$j.get(send_form+"&"+compareRequest, compareCallback);
}

/**
 Select a model to compare from the cart
*/
function selectCompare(model_number) {
	// TODO: handle this better
	$j.get(send_form+"&type=selectcompare&model_number="+escape(model_number), function(ret) {
		if(ret.length && ret != "\r\n") {
			var error = $j("#compError");
			error.html(ret);
			error.effect('pulsate', {times: COMP_ERROR_FLASHES}, COMP_ERROR_TIME);

			$j('#compCompare_'+id(model_number)).attr('checked', false);
		}
		else {
			var obj = $j('#compCompare_'+id(model_number));
			obj.attr('checked', !obj.attr('checked'));
		}
	});
}

/**
 Query the models from the cart for showCompare
*/
function cartCompare() {
	compareRequest = "type=cartcompare";
	$j.get(send_form+"&"+compareRequest, compareCallback);
}

/**
 Callback for compare results
*/
function compareCallback(ret) {
	hideCart();
	compDialog.html(ret);
	compDialog.dialog('open');
}

/**
 Open a PDF link in a new window
*/
function openPDF(url) {
	compDialog.dialog('close');
	window.open(url, "Comparo", '');
}

// ----------------------------------------------------------------------------
// C a r t
// ----------------------------------------------------------------------------

/**
 Add a model to the cart
*/
function addToCart(model_number) {
	$j.get(send_form+"&type=addtocart&model_number="+escape(model_number), function (ret) {
		$j('#compAdd_'+id(model_number)).effect('transfer', {
			to: "#compCartBtn",
			className: 'compCartTransfer'
		}, COMP_CARTTRANSFER_TIME, function() {
			compCartBtn.effect('highlight', null, COMP_CARTHIGHLIGHT_TIME);
		});
	});
}

/**
 Remove a model from the cart
*/
function deleteFromCart(model_number) {
	$j.get(send_form+"&type=deletefromcart&model_number="+escape(model_number), function(ret) {
		$j('#compCart_'+id(model_number)).fadeOut();
	});
}

/**
 Query the cart's items
*/
function showCart() {
	$j.get(send_form+"&type=opencart", function(ret) {
  		compCartContent.html(ret);
		compCartContent.effect('slide', {direction:"right"}, COMP_CARTSLIDE_TIME);
	});
}
function hideCart() {
	if(compCartContent.css('display') != 'none') {
		compCartContent.effect('drop', null, COMP_CARTSLIDE_TIME, function() {
			// IE's drop effect leaves the opacity at 0, this is not good
			if($j.browser.msie) compCartContent.css('opacity', 1);
		});
	}
}

/**
 Print cart
*/
function printCart() {
	window.open('print.php?type=opencart');
}

/**
 Reset/Empty cart
*/
function resetCart() {
	$j.get(send_form+"&type=resetcart", showCart);
}
function emptyCart() {
	$j.get(send_form+"&type=emptycart", showCart);
}

// Hide the cart after the cursor is outside its region for too long
var cart_t = null;
function onCartOut() { cart_t = setTimeout("hideCart()", COMP_CARTHIDE_DELAY); }
function onCartOver(){ if(cart_t) clearTimeout(cart_t); }

// Old school mouse over effect
function cartItemOver(item){ item.className = "compCartItemOver"; }
function cartItemOut(item){ item.className = ""; }

function id(name) { return name.replace(' ', '_'); }
