/**
 * Adds a bookmark to the current site.
 */
function bookmark()
{
	if(document.all)
	{
		window.external.AddFavorite(location.href, document.title);
	}
	else if(window.sidebar)
	{
		window.sidebar.addPanel(document.title, location.href, '');
	}
}

/**
 * Prints the current page.
 */
function print_page()
{
	window.print();
}

	
/**
 * Checks to see if a given email is valid (format-wise)
 *
 * @param email - value entered into the email input box 
 */
function checkEmail(email)
{
  var rexp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,8}$/;
  return rexp.test(email);
}

/**
 * Checks to see if a given phone number is valid (format-wise)
 *
 * @param phone - value entered into the phone input box
 */
function checkPhone(phone)
{
    var rexp = /^(\(?\d{3}\)?[ -]?)?\d{3}[ -]?\d{4}$/;
    return rexp.test(phone);
}

/**
 * Checks to see if a given date is valid (format-wise)
 *
 * @param date - value entered into the date input box
 */
function checkDate(date)
{
    var rexp = /([1-9]|0[1-9]|[12][0-9]|3[01])-([1-9]|0[1-9]|1[012])-(19|20)\d\d ([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-9]|0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]):([0-9]|0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9])/;
    return rexp.test(date);
}

/**
 * Remove "UserName" and "Password" from the box when someone clicks.
 * Remove the handler so it only clears once.
 */
 var login_clear_once=1;
function login_clear(form)
{
 	var form_id = '.' + form;
 	var user = form_id + ' #LoginUsername';
 	var username = $(user).attr('value');
 	//alert(form_id);
	if(username == 'UserName')
	{
		$(form_id).clearForm();
		//var pass = form_id + ' #LoginUsername';
		//$(pass).attr('value', 'I like money');
 		login_clear_once = 0;
 	}
}

/**
 * Attempts to log a user into the site
 */
 function login(form)
 {
 	var form_id = '.' + form;
 	//alert(form_id);
 	var fdata = $(form_id).formToArray();
 	var adata = associate(fdata);
 	
 	
 	//Verify the username and password was provided
 	if(adata['data[Login][username]'] === undefined)
 	{
 		alert("Please enter your username to login");
 		return;
 	}
 	if(adata['data[Login][password]'] === undefined)
 	{
 		alert("Please enter your password to login");
 		return;
 	}
 	
 	$.post(PATH_BASE+"/account/login", 
 		fdata, 
 		function(data) 
 		{
 			if(data["token"])
 			{
 				//set the userid &session cookies
 				document.cookie = "username=" + adata['data[Login][username]'] + COOKIE_SUFFIX; //; domain=.partpal.com";
 				document.cookie = "token=" + data['token'] + COOKIE_SUFFIX; //; domain=.partpal.com";

 				//Update the status
 				$("#status").html("<h3>Login successful</h3>");
 				
 				//Reload the page			
 				//window.location="";
 				if (form == 'popup') {
 					GB_hide();
 				} 				
 				else {
 					window.location.reload();
 				}
 				
 			}
 			else
 			{
 				$("#status").html('<h3>Login Failed</h3>' + data["error"]);
 			}
 			
 		}, "json");

 }
//(caption, url, height, width, onclose, postdata, onload) 
function requireLogin(onDone){
	if (isLoggedin()) {
		onDone();
		return;
	}
	else {
		fdata = $('.popup').formToArray();
		data = associate(fdata);
		
		GB_show("Please Login", PATH_BASE+'/sellapart/login/', 
			125, 285, onDone,
			fdata);
	}
} 

function isLoggedin()
{
	if (document.cookie.length > 0)
	{
	  c_start=document.cookie.indexOf("username=");
	    if (c_start!=-1)
	      return true;
	    else
	      return false;
  	}
  	
}
  
function getMake()
{
	var year = $("#Year").attr("value");

	if(document.getElementById('Year').value != "*")
	{
 		$.post("index.php?action=services&subaction=getmake&isajax=1", 
 		{
 			year:year
 		}, 
 		function(data) 
 		{				
 			$("#Make")
 				.html(data["html"])
 				.attr("disabled", "")
 				.attr("onchange", "javascript:getModel()");
 		}, "json");
	}
	else
	{
		document.getElementById('Make').disabled = true;
		document.getElementById('advSearch').disabled = true;
		document.getElementById('aftermarketSubmit').disabled = true;
		document.getElementById('MakeArea').innerHTML = defaultSelect('Make');
	}
}

function getModel()
{

	var make = $("#Make").attr("value");
	var year = $("#Year").attr("value");

	if(document.getElementById('Make').value != "*")
	{
 		$.post("index.php?action=services&subaction=getmodel&isajax=1", 
 		{
			year:year, 		
 			make:make
 		}, 
 		function(data) 
 		{				
 			$("#Model")
 				.html(data["html"])
 				.attr("disabled", "");
 		}, "json");
	}	
	else
	{
		document.getElementById('Model').disabled = true;
		document.getElementById('advSearch').disabled = true;
		document.getElementById('aftermarketSubmit').disabled = true;
		document.getElementById('ModelArea').innerHTML = defaultSelect('Model');
	}
}

function category_change(allow_any)
{
	//Reset the subcategory
	$("#Subcategory").html("");
	$("#PartTerminology").html("");
	$("#Position").html("");
	
	
	//Figure out the category
	var categoryid = $("#Category").attr("value");
	
	//The "Any" option
	var any_opt = "<option value=\"0\">Any</option>\n";
	
	//Handle "Any" category
	if(categoryid == 0)
	{
		$("#Subcategory").html(any_opt);
	}
	//Handle a selected category
	else
	{
		//Replace it with the appropriate choices
		$.get("?",
			{
				action:"services",
				subaction:"getsubcategory",
				isajax:1,
				categoryid:categoryid
			}, 
			function(data)
			{
				if(allow_any !== undefined)
				{
					data = any_opt + data;
				}
				$("#Subcategory").html(data);
			});
	}
}
 
function clearTextBox(node)
{
	node.value = ""; 
}
 
 
 function logout()
 {
 	//Delete the cookies
 	document.cookie = "username=;expires=Thu, 01-Jan-1970 00:00:01 GMT" + COOKIE_SUFFIX;// domain=.lucidhelix.com;";
 	document.cookie = "token=;expires=Thu, 01-Jan-1970 00:00:01 GMT" + COOKIE_SUFFIX;// domain=.lucidhelix.com;";
 	
 	//Redirect to refresh the login box
 	window.location = PATH_BASE;
 }
 
 function quicksearch()
 {
 
 	document.quicksearch.submit();
 }
//**************************************
//Shared by findapart and sell a part
//**************************************
function yearChange(allowany) {
	year = $('#find-year').attr('value');
	make = $('#find-make').attr('value');
	$('#ajax-make').show();
	$('#ajax-model').show();
	$('#ajax-submodel').show();
	$.post(PATH_BASE + 'services/makeselect/', {
			year:year,
			make:make,
			allowany:allowany
		}, function(data) {
			$('#find-make').html(data);
			$('#ajax-make').hide();
			makeChange(allowany);
			
		});
}

function makeChange(allowany) {
	year = $('#find-year').attr('value');
	make = $('#find-make').attr('value');
	model = $('#find-model').attr('value');
	$('#ajax-model').show();
	$('#ajax-submodel').show();
	$.post(PATH_BASE+'services/modelselect/', {
			year:year,
			make:make,
			model:model,
			allowany:allowany
		}, function(data) {
			$('#find-model').html(data);
			$('#ajax-model').hide();
			modelChange(allowany);
		});
}

function modelChange(allowany) {
	year = $('#find-year').attr('value');
	make = $('#find-make').attr('value');
	model = $('#find-model').attr('value');
	submodel = $('#find-submodel').attr('value');
	$('#ajax-submodel').show();
	$.post(PATH_BASE+'services/submodelselect/', {
			year:year,
			make:make,
			model:model,
			submodel:submodel,
			allowany:allowany
		}, function(data) {
			$('#find-submodel').html(data);
			$('#ajax-submodel').hide();
		});
}

//keyword search
function keywordBlur() {
	keywords = $('#find-keywords').attr('value');
	
	//Show the hint if the keyword field goes blank
	if(!keywords) {
		$('#find-keyword-hint').show();
		$('#find-keywords').hide();
	}
}

function keywordChange() {
	var keys = $('#find-keywords').attr('value');
	$('#ajax-keywords').show();
	//Do an AJAX call to fill the select box
	$.post(PATH_BASE + '/services/keyword_matches', {
			keys:keys
		}, function(jdata) {
			$('#ajax-keywords').hide();
			//jdata = eval( '('+data+')');
			
			//Display the data
			//$('#find-keyword-status').html(jdata.matches + ' listings match your keywords');
		});
} 

function keywordKeypress(e) {
	if (!e) var e = window.event;
	if(e.charCode == e.DOM_VK_SPACE) {
		keywordChange();
	} else if (e.keyCode == e.DOM_VK_ENTER || e.keyCode == e.DOM_VK_RETURN ) {
		search();
//	} else if (window.event.keyCode == e.DOM_VK_ENTER || window.event.keyCode == e.DOM_VK_RETURN ) {
//		search();
	}
}

function keywordHintFocus() {
	$('#find-keywords').show().focus();
	$('#find-keyword-hint').hide();
}

//Extra function for jQuery Forms add in
function associate(data) {
	var rvalue = [];
	for(var i in data) {
		rvalue[data[i]['name']] = data[i]['value'];
	}
	return rvalue;
}

var redirect = '';
function ajaxTrack(data) {
	var href = data.href;
	var location = document.location;
		
	//Do an AJAX call to track
	$.post(PATH_BASE + '/click/index/'+href, {
			href:href,
			location:location
		}, function(jdata) {

		});
		
	redirect = href;
	setTimeout(function() { delay(); }, 100);
	
	
	return false;
}

function delay() {
	window.location = redirect;
}
/*
function trackSponsor(organization, part) {
	// Ajax will get cut off, but an image load won't (see facebook)

	//(new Image()).src = PATH_BASE + 'click/sponsor/' + part + '/' + organization;
        (new Image()).src = PATH_BASE + 'click/sponsor/' + part + '/' + organization + "?_cache=" + (+(new Date()));

	return false;
}
*/
var YUI3 = {};

YUI().use('io', function(Y) {

   function trackSponsor(organization, part) {
       var url = PATH_BASE + 'click/sponsor/' + part + '/' + organization + "?_cache=" + (+(new Date()));
       var click = Y.io(url);
   }

   YUI3.trackSponsor = trackSponsor;

});
