var defaultCondition = 450;
var Product = "";
var quotedProducts = 0;
var notQuotedProducts = 0;

function setBasketButtonsOnLoad( quotedProducts_, notQuotedProducts_ )
{
	quotedProducts = quotedProducts_;
	notQuotedProducts = notQuotedProducts_;
	setButtons();
}

$(function(){

	$("#searchWrap a").live('click', function() {
		$("#categoryWrap").show();
		$("#usedQuotesSuggestions").hide();
		$("#searchWrap").hide();
		$("#resultSect").hide();
	});

	$("#categoryWrap a").live('click',  function() {
		$("#categoryWrap").hide();
		$("#searchWrap").show();  
	});
	
	$("#searchWrap input").livequery('focus', function() { 
		if($(this).attr("defaultValue") == $(this).attr("value"))
		$(this).attr("value", "");
	});
	
	$("#searchSubmit").live('click', function() {
		search();
	});
	
	$("#brand").livequery('keyup', function(event) {
		suggestionsKeys( this, event );
		
		if( isValidForAutocomplete( event.which ) )
			autocomplete( this );
	});
	
	$("#model").livequery('keyup', function(event) {
	
		suggestionsKeys( this, event );

		if( $("#model").val().length < 2 )
			$("#usedQuotesSuggestions").hide();
		
		else if( isValidForAutocomplete( event.which ) )
			autocomplete( this );
	});
	
	$(".suggestionList ul li").live('mouseover',function(e) {
		$(this).addClass("hoverOver");
		$(this).siblings().removeAttr("class");
	});
	
	$("#addProduct").livequery('click',function() {
		
		changeProduct();
		refreshItem();
		refreshBasket();
	});
	
	
	$("#tbd").live('mouseover',function() {
	var position = $(this).position();
      $('#tbdPop').css({left: (position.left-80), top: (position.top-120)});
   }); 
	
	$("#tbd").live('mouseout',function() {
      $('#tbdPop').css('left', '-10000px');
   }); 

	$("#categoryBrowse ul li").live( "click", function() {

		var clickedUL = $(this).parent();
			if(!$(this).hasClass("current")){
				$(this).addClass("current");
				$(this).siblings().removeAttr("class");
		}

		if( $(this).attr("name") == "other" ) {
			createOtherFields( this );
			return;
		}
		
		$("#browseBrand").html('<label>Brand</label><select disabled id="ebrand"><option>select a brand</option></select>');
		$("#browseModel").html('<label>Model</label><select disabled id="emodel"><option>select a model</option></select>');

		var categoryId = $(this).attr("value");
		var showBrands = $(this).attr( "isLowestLevel" );
		
		if( showBrands == "true" )
		{
			getBrands(categoryId);
			$("#cInstructions").slideDown("1000");
			
			if(clickedUL.attr('id') == "cat3") {
				$("#cInstructions").css("width","670px");
			}
			else {
				$("#typeHeader").hide();
				$("#cInstructions").css("width","446px");
			}
		}
		else {
			$("#cInstructions").hide();

			QuoteServer.getChildrenById(categoryId, function( categories )
			{
				var liHolder = "";
				
				$.each(categories, function() {
					liHolder += "<li value='" +this.id+ "' title='"+this.name+ "' isLowestLevel='"+this.isLowestLevel+"'>" +this.name+ (!this.isLowestLevel?" >":"") +"</li>";
				});
				
				liHolder += "<li value='other' name='other'>Other</li>";
				
				if(clickedUL.attr('id') == "cat1"){
					$("#cat2").html(liHolder);
					$("#typeHeader").hide();
				}
				else if( clickedUL.attr('id') == "cat2" && clickedUL.find(":contains('Select a category')").length < 1 ){
					$("#cat3").html(liHolder);
					$("#typeHeader").show();
				}
			});
		}
	});
	
	$("#ebrand").livequery( "change", function() {
		if( $("#ebrand option:selected").attr("name") != "other" )
			getModels();
		else
			createOtherFields( this );
	});
	
	$("#emodel").livequery( "change", function() {
		if( $("#emodel option:selected").attr("name") != "other" )
		{	
			productId = $(this).val();
			addProduct( productId );
		}
		else
			createOtherFields( this );
	});
	
	$("*[id='addOtherToBasket']").livequery( "click", function() {
	
		var brand, model;
	
		if( $(this).attr("name").indexOf("brandModel_") == 0 )
		{
			var array = $(this).attr("name").split("_");
			brand = array[1];
			model = array[2];
		}
		else
		{
			if( $("#ebrand").length )
				brand = $('#ebrand option:selected').text();
			else
				brand = $("#brandOther").val();

			model = $("#modelOther").val();
			
			if( brand.replace(/^\s+|\s+$/g,"") == "" && model.replace(/^\s+|\s+$/g,"") == "" ) // space
			{
				alert("Enter a Brand or Model");
				return;
			}
		}
		
		QuoteServer.addNoneExistingProduct( brand, model, defaultCondition, function( product )
		{
			$("#howitworks").hide();
			Product = product;
			showProduct(true);
			notQuotedProducts++;
			setButtons();
		});
	});
	
	$('#cartSection [save="true"]').click( function(e)
	{
		changeProduct();
		
		if( $(this).attr("id") == "rejectQuote" )
		{
			$("#rejectPopup").show();
			return false;
		}
	});

	$("#editProduct").live( "click", function() 
	{
		changeProduct();
		hideSearchBrowse();
		
		
		var productKey = $(this).attr("name");

		getProductThruKey( productKey );

		refreshBasket();
		
		$("#cartItems [id='" + productKey + "'] [id='editProduct']").hide();
		$("#cartItems [id='" + productKey + "'] [id='quantity']").attr( "disabled", false );

		$("#cartItems .itemSell").removeClass("currentItem");
		$("#cartItems [id='" + productKey + "']").attr("class","itemSell currentItem");
		

		return false;
	});
	
	$("#removeProduct").live( "click", function() 
	{
		changeProduct();
		
		var productKey = $(this).attr("name");
		QuoteServer.removeProduct( productKey, function( product )
		{
			if( product.isCreatedByUser )
				notQuotedProducts--;
			else quotedProducts--;
			
			setButtons();
		});

		if( Product != "" && Product.key ==  productKey )
			refreshItem();

		var currentProduct = $(this).parents(".itemSell");
		currentProduct.slideUp("slow",function()
		{
			currentProduct.remove();
			showTotal();
		});

		return false;
	});
	
	$("#startOver").live( "click", function() 
	{
		QuoteServer.removeAll( function()
		{
			window.location.reload();
		});

		return false;
	});
	
	$("#cartItems [id='quantity']").live( "keyup", function(e) {

		var productKey = $(this).attr("name");
		var quantity = $(this).val();

		if( new RegExp("^[0-9]+$","g").test( quantity ) )
		{
			Product.quantity = quantity;
			showOfferTotal();
		}
		else {
			if( quantity != ""  && quantity != " " ) 
				alert("Please enter only numbers.");
				
			$(this).val(  quantity.replace( /[^0-9]/g , "") );
		}
    });
	
	$("#cartItems [id='quantity']").livequery( "blur", function(e) {
		if(  $.trim( $(this).val() ) == "" ) {
			alert("Please enter a quantity.");
			$(this).focus();
		}
	});

	$("#accessories input[type='checkbox']").live( "click", function() {
	
		var productKey = $("#productKey").attr("value");
		var accessory = $(this).attr("value");
		var checked = $(this).attr("checked") ;
		var accessories = Product.accessories;
		var deduct = 0;
		
		for(var i=0; i<accessories.length; i++)
		{
			if( accessories[i].description  == accessory )
				accessories[i].added = checked;
		}

		$( "#cartItems [id='" + Product.key + "'] [id='brandModelAcc']").html( Product.brand.name + " " + Product.model + 
				(Product.accessories.length>0?"<p>Accessories: " + getNumberOfAddedAcc() + "</p>" : "") );

		showOfferTotal();
	});
	
	$("#accessories a").livequery('click', function() 
	{
		 $(this).prev().trigger('click');
		 return false;
	});

	$("#cartSection [id='rejectForm']").livequery( "submit", function(e) {
		$(this).append('<input type="hidden" name="uq_comment" value="'+ $("#uq_comment").attr("value") +'"/>');
		$(this).append('<input type="hidden" name="email" value="'+ $("#uq_email").attr("value") +'"/>');
	});
	
});

function getNumberOfAddedAcc()
{
	var accessories = Product.accessories;
	var number = 0;
	
	for(var i=0; i<accessories.length; i++)
	{
		if( accessories[i].added )
			number++;
	}
	return number;
}

function hideSearchBrowse()
{
	$("#categoryWrap").hide();
	$("#searchWrap").hide();
	$("#resultSect").hide();
}

function getProductThruKey( productKey )
{
	QuoteServer.getProductThruKey( productKey, function( product )
	{
		Product = product;
		showProduct();
	});
	
}

function changeProduct()
{
	if( Product != "" )
		QuoteServer.changeProduct( Product.key, Product.quantity, getUsersCondition(), getUsersAccessories() );
}

function getUsersCondition()
{
	var conditions = Product.conditions;
	
	for(var i=0; i<conditions.length; i++)
	{
		if( conditions[i].selected )
			return conditions[i].webCode;
	}
}

function getUsersAccessories()
{
	var accessories = Product.accessories;
	var usersAcc = "";
	
	for(var i=0; i<accessories.length; i++) {
		if( accessories[i].added )
			usersAcc += accessories[i].description + ":";
	}
	
	return usersAcc;
}

function addProduct( productId )
{
	QuoteServer.addProduct( productId, defaultCondition, function( product )
	{
		$("#howitworks").hide();
		Product = product;
		showProduct(true);

		quotedProducts++;
		setButtons();
	});
}

function showProduct( newProduct )
{
	$("#headerLeft").html("<h2>" + Product.brand.name + " " + Product.model + "</h2>");
	
	showImage();						
	showAccessories( Product.accessories );
	slideMe();
	
	if( newProduct )
		addProductToPage();
		
	showOfferTotal();
	$("#addProduct").show();
	
	$("#cartItems .itemSell").removeClass("currentItem");
	$("#cartItems [id='" + Product.key + "']").attr("class","itemSell currentItem");
}

function addProductToPage()
{
	var emptyItem = $("#emptyItem").clone();
	emptyItem.show();
	emptyItem.attr( "id", Product.key );
	$("#cartItems").prepend( emptyItem );
	var newItem = "#cartItems [id='" + Product.key+ "'] ";
	$( newItem + "[id='brandModelAcc']").html( Product.brand.name + " " + Product.model + 
				(Product.accessories.length>0?"<p>Accessories: " + getNumberOfAddedAcc() + "</p>" : "") );
	$( newItem + "[id='editProduct']").attr( "name", Product.key );
	$( newItem + "[id='removeProduct']").attr( "name", Product.key );
	
	refreshBasket();

	$( newItem + "[id='quantity']").attr( "disabled", false );
	$( newItem + "[id='editProduct']").hide();	
}

function showImage()
{
	if( Product.hasImage )
	{
		$("#productImg img").attr("src", "/images/images150x150/" + Product.sku + ".jpg");
		$("#productImg img").attr("alt", Product.brand.name + " " + Product.model );
	}
	else {
		$("#productImg img").attr("src", "/images/na.gif");
	}
}

function showAccessories( acc )
{
	hideSearchBrowse();
	$("#includedWrap").hide();
	$("#accessories").html("");

	if( acc.length > 0 ) 
	{
		$("#includedWrap").show(); 
		
		for(var i=0; i<acc.length; i++)
		{
			var width = acc.length > 5? 'style=width:47%' : "";
			$("#accessories").append('<li '+width+'><input type="checkbox" name="accessory" value="'+acc[i].description+'" ' + (acc[i].added?'checked':'') + '/>' +
									 '<a href="">'+acc[i].description+'</a></li>');
		}
	}
}

function showOfferTotal()
{
	var currentItem = "#cartItems [id='" + Product.key + "'] ";
	
	var price = Product.price + getConditionDeduction() - getAccDeduction();
	price = price < 0 ? 0 : parseNumber( Product.quantity * price );
	$( currentItem + "[id='quote']").html( Product.isCreatedByUser ? "Quote: <a href='#' id='tbd'>To Be Determined</a> " : "Quote: $" + price );
	
	if( !Product.isCreatedByUser && price < 1 && ( getUsersCondition() == 450 || getUsersCondition() == 600 ) )
		$( currentItem + "[id='quote']").prepend( "<div id='zeroItem'>This item has no value without accessories.</div>" );
		
	$( currentItem + "[id='quote']").attr( "name",  price );
	showTotal();
}

function parseNumber( number )
{
	var array = number.toString().split(".");
	
	if( array.length > 1 )
	{
		if( parseInt( array[1] ) < 1 )
			return number.toFixed(0);
		else return number.toFixed(2);
	}
	return number;
}

function showTotal()
{
	var quoteVal = $("#cartItems [id='quote']");
	
	var total = 0;
	 $.each(quoteVal, function() {
		total += parseFloat( $(this).attr("name") );
	});

	if( quoteVal.length > 0 ) 
	{
		$("#totalPrice").fadeOut(100, function()
		{
			$("#totalPrice").show();
			$("#totalPrice").html( "<h2>Total: $" + parseNumber(total) + "</h2>");	
		});
		
		$("#totalPrice").fadeIn(500);
	}
}

function getAccDeduction()
{
	var accessories = Product.accessories;
	var deduct = 0;
	
	for(var i=0; i<accessories.length; i++)
	{
		if( !accessories[i].added )
			deduct += accessories[i].value;
	}
	
	return deduct;
}

function getConditionDeduction()
{
	var conditions = Product.conditions;
	
	for(var i=0; i<conditions.length; i++)
	{
		if( conditions[i].selected )
			return conditions[i].deduction;
	}
}

function slideMe() 
{
	$("#productSpecs").show();
	$("#headerLeft").css('background','url(/images/used/headerTitle.gif) repeat-x');
	$("#headerLeft h2").show();
	
	if( $("#slider").is(":empty") )
	{
		$("#slider").slider({
			value: ( Product == "" ? defaultCondition : getUsersCondition() ),
			min: 0,
			max: 612,
			step: (150),
			slide: function(event, ui) 
			{
				setCondition( ui.value );
				showOfferTotal();
			}
		});
	}
	else {
		$("#slider").slider('option', 'value', ( Product == "" ? defaultCondition : getUsersCondition() ) );
	}
}

function setCondition( condition )
{
	var conditions = Product.conditions;
	
	for(var i=0; i<conditions.length; i++)
	{
		var currentCondition = conditions[i];

		if( currentCondition.webCode == condition  )
			currentCondition.selected = true;
		else
			currentCondition.selected = false;
	}
}

function refreshBasket() 
{
	$("#cartItems [id='editProduct']").show();
	$("#cartItems [id='quantity']").attr("disabled",true);
}

function refreshItem() 
{
	Product = "";
	
	$("#headerLeft").css('background','url(/images/used/headerBK.gif) repeat-x');
	$("#headerLeft h2").hide();
		
	QuoteServer.getSellUsedProductPage( function( value ) { 
	    $(".usedWrap").html( value );
	});
}

function createOtherFields( t )
{
	if( $(t).parent().attr("id") != "browseModel" )
		$("#browseBrand").html('<label>Brand</label><input type="text" size="31" id="brandOther"/>');
		
	$("#browseModel").html('<label>Model</label><input type="text" size="32" id="modelOther"/>');
	$("#browseModel").append('<li style="margin:1em 0 0 9.6em"><input type="button" value="" id="addOtherToBasket"/></li>');
}

function suggestionsKeys( t, event )
{
	var id = $(t).attr("id");

	if( event.shiftKey == true && event.which == 53 ) // %
	{
		$(t).val( $(t).val().replace(/%/g,"") );
	}
	else if(event.which == 13) // enter
	{
		$("#usedQuotesSuggestions").hide();
		
		if( id == "brand")
			$("#model").focus();
		else if( $(t).attr("id")=="model")
			search();
	}
	else if(event.which == 40)//down
	{
		if( ! $(".suggestionList ul li").hasClass("hoverOver") )
			$(".suggestionList ul li:first").addClass("hoverOver");
		else
			$(".suggestionList .hoverOver").next().addClass("hoverOver").siblings().removeClass("hoverOver");
	}
	else if(event.which == 38)//up
		$(".suggestionList .hoverOver").prev().addClass("hoverOver").siblings().removeClass("hoverOver");

	var isSuggestionsOnFocusedField =  ($("#usedQuotesSuggestions").css("left")=="0px"&&id=="brand") || ($("#usedQuotesSuggestions").css("left")!="0px" && id!="brand"); 
	
	if( $(".suggestionList .hoverOver").text() != "" && ( event.which == 40 || event.which == 38 ) && isSuggestionsOnFocusedField )
		$(t).val( $(".suggestionList .hoverOver").text() );
}

function autocomplete( t )
{
	var searchValue = $(t).val();
	var id = $(t).attr("id");

	if( searchValue == "" || searchValue == " " ) {
		$("#usedQuotesSuggestions").hide();
		return;
	}
	
	QuoteServer.autocomplete( $("#brand").val(), $("#model").val(), id, function( list )
	{
		if( list.length < 1 ) {
			$("#usedQuotesSuggestions").hide();
			return;
		}
		var results = "<ul>";
		for(var i=0; i<list.length; i++)
		{
			results += "<li>" + list[i] +"</li>";
		}
		results += "</ul>";
		$("#usedQuotesSuggestions").show();
		$("#usedQuotesSuggestions").css({'left' : id == "brand" ? '0px' : '208px', 'width': id == "brand" ? '203px' : '400px'});
		$("#autoSuggestionsListUsedQuotes").html( results );
		$("#autoSuggestionsListUsedQuotes ul li").click(function(){
			var brandVal = $(this).text();
			$(t).val(brandVal);
			$("#usedQuotesSuggestions").hide();
			if(id!="brand")
				search();
		});
	});
	
}

function search()
{
	$("#usedQuotesSuggestions").hide();
	var brand = $("#brand").attr("value").replace(/%/g,"");
	var model = $("#model").attr("value").replace(/%/g,"");
	
	if( (brand == $("#brand").attr("defaultValue") || brand == "") && (model == $("#model").attr("defaultValue") || model=="")){
		alert("Enter a Brand or Model");
		return false;
	}else if(brand == $("#brand").attr("defaultValue")){
		brand = ""; 
	}else if(model == $("#model").attr("defaultValue")){
		model = "";
	}
	$(".loader").show();
	var results = "";
	QuoteServer.search(  brand, model , function( models )
	{
		if( models.length > 0 )
		{
			results = "<p><strong>Found: </strong>"+models.length+" product(s)</strong></p>";
		
			for(var i=0; i<models.length; i++)
			{
				var image =  !models[i].hasImage ? "used/noimage.gif" : "smallimages/" + models[i].sku + ".jpg";
				results += '<ul class="clearfix">' +
					           '<li><img src="/images/' + image + '" alt="'+ models[i].brand +' '+ models[i].model +'"/></li>' +
							   '<li class="link"><a href="javascript:addProduct(' + models[i].id + ')">' 
								+ models[i].brand +" "+ models[i].model + '</a></li>' +
				            '</ul>';
			}
		}
		else {
			results = "<p><strong>No Results: </strong>found for <strong>\""+brand +(brand==''||model==''?"":" ")+ model+"\".</strong></p>" +
					  "<div><p style='background:#FFF'>Your item is not in our catalog. Press the 'get a quote' button to continue.</p><input type='button' name='brandModel_" +brand+"_"+model+ "' value='' id='addOtherToBasket'/></div>";
		}
		$("#resultSect").html( results );
		$("#resultSect").show();
		$(".loader").hide();
	});
}

function getBrands(categoryId)
{
	QuoteServer.getBrands( categoryId, function( brands )
	{
		if( brands != null )
		{
			$("#browseBrand").html('<label>Choose a Brand</label><select id="ebrand" name="getBrand"><option value="0">Choose a brand</option></select>');

			for (var i=0; i<brands.length; i++)
				$('#ebrand').append("<option value='" + brands[i].id + "'>" + brands[i].name + "</option>");
			$('#ebrand').append("<option name='other'>Other</option>");
			$('#ebrand').attr("category", categoryId );
		}
	});
}

function getModels()
{
	$("#browseModel").html('<label>Choose a Model</label><select id="emodel" name="getModel"><option value="0">Choose a model</option></select>');
	
	QuoteServer.getProducts( $("#ebrand").attr("category") , $('#ebrand option:selected').val(), function( products )
	{
		if( products != null ) {
			for (var i=0; i<products.length; i++)
				$('#emodel').append("<option value='" + products[i].id + "'>" + products[i].model + "</option>");
		}
		$('#emodel').append("<option name='other'>Other</option>");
	});
}

function isValidForAutocomplete( e )
{
    return e!=16 && e!=17 && e!=18 && e!=13 && e!=37 && e!=38 && e!=39 && e!=40;
}

function setButtons()
{
	if( quotedProducts > 0 && notQuotedProducts < 1 )
	{
		$("#quotedForm").show();
		$("#rejectQuotedForm").show();
		$("#notQuotedForm").hide();
		$("#rejectNotQuotedForm").hide();
	}
	else if( notQuotedProducts > 0 && quotedProducts < 1 )
	{
		$("#notQuotedForm").show();
		$("#rejectNotQuotedForm").hide();
		$("#quotedForm").hide();
		$("#rejectQuotedForm").hide();
	}
	else if( notQuotedProducts > 0 && quotedProducts > 0 )
	{
		$("#quotedForm").show();
		$("#rejectNotQuotedForm").show();
		$("#notQuotedForm").hide();
		$("#rejectQuotedForm").hide();
	}
	else
	{
		$("#notQuotedForm").hide();
		$("#rejectNotQuotedForm").hide();
		$("#quotedForm").hide();
		$("#rejectQuotedForm").hide();
		$("#totalPrice").hide();
		$("#addProduct").hide();
		$("#howitworks").show();
	}
}

dwr.engine.setErrorHandler(function() {
	alert("Your session has expired." );
	window.location.reload();
});
