$(init_function);

function init_function() {
	yearChange(0);
}

function ajaxSubmit2(data) {
	var form = data['form'];
	var target = data['target'];
	var type = data['type'];
	var ondone = data['ondone'];
	var onbefore = data['onbefore'];
	var url = data['url'];
	
	params = $(form).formToArray();
	
	if(onbefore) {
		onbefore();
	}
	
	switch(type) {
		case 'post':
		case 'POST':
			$.post(url, params, function(data) {
					$(target).html(data);
					if(ondone) {
						ondone();
					}
				});
			break;
		case 'get':
		case 'GET':
			$.get(url, params, function(data) {
					$(target).html(data);
					if(ondone) {
						ondone();
					}
				});
			break;
	}
}

// validate the promo code entered
function validateCode()
{
	var promo     = $("#promo").attr("value");

 	//Verify the mfr & part were provided
 	if(promo == null)
 	{
 		alert("Please enter a Promo Code");
 		return;
 	}
	
 	
 	$("#promoStatus").html("<h3>Checking promo code...</h3>");
 	$.post(PATH_BASE + "promocodes/checkpromocode", 
 		{
 			promo:promo
 		}, 
 		function(data) 
 		{
 		/*
 			var cost = $("#he_cost").attr('value');
			var newTotal;	
			if(newTotal < 0)
		  	{
		  	  newTotal = 0;
		  	 }
		  	$("#cost").html(newTotal.toFixed(2));
		  */
		  //$("#promoStatus").html(data);
			
				
							
			switch(data["type"])
			{
			  case "% Discount":
			  	$("#promoStatus").html("<h3>You save: " + data["amount"] + "%</h3>");
			  	break;
			  case "$ Discount":
			  	$("#promoStatus").html("<h3>You save: $" + data["amount"] + "</h3>");
			  	break;
			  case "Free Listings":
			  	$("#promoStatus").html("<h3>" + data["amount"] + " Free Listings!</h3>");
			 	break;
			  case "Invalid":
			    $("#promoStatus").html("<h3>Invalid Promo Code. Codes are case sensitive</h3>");
			    break;
			  case "Used":
			    $("#promoStatus").html("<h3>You have already used this Promo Code.</h3>");
			    break;
			  case "Expired":
			    $("#promoStatus").html("<h3>This Promo Code is Expired.</h3>");
			    break;    
			  default:
			    $("#discount_amount").html("$0.00");
			    $("#promoStatus").html("<h3>Invalid Promo Code. Codes are case sensitive</h3>");
			  	break;
			}
			
			$("#discount").html("Your total discount is: " + data["discount"]);
			
			if (data["newTotal"] == 0) {
				alert("This one's on the house. checkout or list more Parts");
				$("#freebie").show();
				$(".btnPaypal").hide();
				$(".btnCredits").hide();
			}
							
 		}, "json");
}

function step1(type){
	var url = PATH_BASE + 'sellapart/step1/' + type + '/';
    
	
	switch(type) {
		case 1: //List by Part Number
			
			var mfr_in = $('#manufacturer').attr('value');
			var pn_in = $('#partnumber').attr('value');	
			var mfr;
  			var pn; 
  			
  			//Need to do base64 encoding to get past mod-rewrite and cakePHP for special characters
		 	if (mfr_in === undefined)
		 	  mfr = '';
		 	else 
		 	  mfr = /*Base64.encode*/escape(mfr_in);
		 	if (pn_in === undefined)
		 	  pn = ''; 
		 	else 
		 	  pn = /*Base64.encode*/escape(pn_in);; 
		 	url +=  mfr + '/' + pn + '/';  		
			document.option1.submit();
			break;
		case 2: //List by Vehicle
			var year = $('#find-year').attr('value');
			var make = $('#find-make').attr('value');
			var model = $('#find-model').attr('value');		
			url +=  year + '/' + make + '/' + model + '/';
			document.option2.submit();
			break;
		case 3: //List by Engine
			alert("We are currently testing the Sell by Engine type.\n\n Check back soon for updates!");
			exit;
			break;				
	}
	//if(isLoggedin()) { 
  	//	url += '&subaction=step1';
   //// } else {
    	//url += '&subaction=login';	
    //}	
    
   //	window.location = url;
   
   
}

function checkLogin(type)
{	
	var result;
	var callback = function() {
			if (!isLoggedin()) {
				// do whatever
			} else {
				step1(type);
			}
		};
	
	requireLogin(callback);
	return;
}

function load_step1()
{
	var mfr = escape($('#manufacturer').attr('value'));
	var pn = escape($('#partnumber').attr('value'));
	var type = escape($('#sellapart_type').attr('value'));
	var title = escape($('#title').attr('value'));
	var price = escape($('#price').attr('value'));
	var currency = escape($('#currency').attr('value'));
	var desc= escape($('#description').attr('value'));
	var length = $('#listing_length').attr('value');
	var featured = $('#featured').attr('value');
	
	var url = '?action=sellapart&subaction=step1&sellapart_type=' + type + '&manufacturer=' + mfr + '&partnumber=' + pn
				+ '&title=' + title + '&price=' + price + '&currency=' + currency + '&description=' + desc 
				+ '&listing_length=' + length + '&featured=' + featured;

	
	window.location = url; 
}

function update_cost()
{
	var price = $('#price').attr('value');
	var listCost3, listCost6;
	
	var regex = /^\d*\.?\d+$/;
	
	if ( !regex.test(price)) {
		alert('Your price is not formatted as 0.00');
		return false;
	}	
	
	// 1% of price, plus $0.50 fixed.	
	listCost3 = (price * (0.010)) + 0.50;
	listCost6 = (price * (0.015)) + 0.50;
	
	if(listCost3 < 1.50)
	  listCost3 = 1.50;
	else if (listCost3 > 100)
	  listCost3 = 100.00;
	
	if(listCost6 < 2.00)
	  listCost6 = 2.00;
	else if (listCost6 > 100)
	  listCost6 = 100.00;  
	
	$('#listCost1').html('($' + listCost3.toFixed(2) + ')');
	$('#listCost3').html('($' + listCost3.toFixed(2) + ')');
	$('#listCost6').html('($' + listCost6.toFixed(2) + ')');
}
/*
function paypal_payment()
{
	var promo = $("#promo").attr("value");
	
	if (promo === undefined)
		promo = '';

	$.post("?action=sellapart&subaction=paypal_payment&isajax=1",
		{
		 	action:"sellapart",
			subaction:"paypal_payment",
			isajax:1,
			promo:promo 
		},
		function(data)
		{		
		   // update total and the item_number
		   $("#amount").attr('value', data["total"]);
		   $("#item_number").attr('value', data["parentID"]);
		   //alert("item is:" + data["parentID"] + " total " + data["total"]);
		   if (data["total"] != 0)
		     document.paypal.submit();
		   else
		     window.location = "?action=sellapart&subaction=nocost";
		},
		"json");			
}
*/
function step3(type) 
{
 	if (type==1) {
		ajaxSubmit2({form:'#sellapart-step3', target:'#sellapart', type:'POST', url:'?action=sellapart&subaction=step4&isajax=1'});
	} else {
		$('#sellapart-step3').ajaxSubmit({target:'#sellapart', type:'POST', url:'?action=sellapart&subaction=step5&isajax=1'});
	}
	
}

function step5(type) {
	$('#payment').attr('value', type);
	document.Payment.submit();
}

function paypal_payment()
{
	var promo = $("#promo").attr("value");
	
	if (promo === undefined)
		promo = '';

	$.post(PATH_BASE + "sellapart/paypal_payment/",
		{
			promo:promo 
		},
		function(data)
		{		
		   // update total and the item_number
		   $("#amount").attr('value', data["total"]);
		   $("#item_number").attr('value', data["parentID"]);
		   alert("item is:" + data["parentID"] + " total " + data["total"]);
		   if (data["total"] != 0)
		     document.paypal.submit();
		   else
		     window.location = PATH_BASE +  "sellapart/nocost";
		},
		"json");			
}

function my_step5(type) 
{ 

 	if (type==1) {
		ajaxSubmit2({form:'#sellapart-step5', target:'#sellapart', type:'POST', url:'?action=sellapart&subaction=step4&isajax=1'});
	} else {
		ajaxSubmit2({form:'#sellapart-step5', target:'#sellapart', type:'POST', url:'?action=sellapart&subaction=step3&isajax=1'});
	}
	
}

function showAddress() {
	$('.hiddenAddress').show();
}
function hideAddress() {
	$('.hiddenAddress').hide();
}

//**************************************************
//* Handle Photo uploads
//**************************************************

function aurigma_callback(data) {
	//alert(document.cookie);
	//$('#status').html(data);
	var i;
	var ids_value = $('#image_ids').attr('value');
	var cur_ids = [];
	var data_arr = eval('(' + data + ')');
	var new_ids = data_arr['ids'];
	var html = '';
		
	if ((ids_value !== undefined) && (ids_value != '')) {
		cur_ids = ids_value.split(',');
	}
	for(i = 0; i < new_ids.length; i++) {
		if (new_ids[i] != '') {
			cur_ids.push(new_ids[i]);
		}
	}
	new_ids = [];
	for (i = Math.max(0, cur_ids.length - 4); i < cur_ids.length; i++) {
		html += '<img src="' + PATH_BASE + '/img/photos/thumbs-50/' + cur_ids[i] + '.jpg" />';
		new_ids.push(cur_ids[i]);
	}
	$('#image_ids').attr('value', new_ids.join(','));
	$('#images').html(html);
}

//**************************************************
//* Functions for handling moving between the steps
//**************************************************
function previous(step) {
	var url;
	var go;
	url = PATH_BASE+'sellapart/';
	if ( (step > 0) && (step < 4) ) {
		url += 'step' + step + '/';
		go = true;
	} else {
		go = confirm('Are you sure you would like to cancel this listing?');
	}
	if (go) {
		document.location = url;
	}
}

//**************************************************
//* Functions for handling Part Terminology
//* selection in step4 
//**************************************************
function partpal_keyword_blur() {
	partpal_keyword_change();
}

function partpal_keyword_keyup(e) {
	if(e.keyCode == e.DOM_VK_SPACE) {
		partpal_keyword_change();
	}
}

function partpal_keyword_change() {
	var keys = $('#partpal_keywords').attr('value');
	
	//Ajax Spinners
	$('#ajax-keywords').show();
	$('#ajax-parttype').show();
	$('#ajax-partposition').show();
	
	//Do an AJAX call to fill the select box
	$.post(PATH_BASE + '/services/category_matches', {
			keys:keys
		}, function(data) {
			var jdata = eval( '('+data+')');
				
			//Display the data
			$('#parttype-select').html(jdata.options);
			if(jdata.matches != 100) {
				$('#part-type-matches').html('('+jdata.matches+' potential matches)');
			} else {
				$('#part-type-matches').html('(Over 100 matches, only first 100 will be shown)');
			}	
			
			//Hide the spinners
			$('#ajax-keywords').hide();
			$('#ajax-parttype').hide();
			
			//Reload the positions
			load_positions();

			
		});
} 

function load_positions() {
	var partTerminologyId = $('#parttype-select').attr('value');
	
	//Do an AJAX call to fill the select box
	$.post(PATH_BASE + '/services/position_matches', {
			partTerminologyId:partTerminologyId
		}, function(data) {
			jdata = eval( '('+data+')');
			
			//Hide the spinner
			$('#ajax-partposition').hide();
			
			//Display the data
			$('#partposition-select').html(jdata.options);
		});
}