/**
 *	File: 		main.js
 *  Abstract: 	This file contains a collection of general javasctipt functions specified for the
 *            		particular web application
 *  Authors: 	Johnny Harlamert, Alex Houchens
 */



/**
 * Function displays a form within the hoverDiv from the master tamplate.
 * The form is generated by the control passed as a parameter to hoverDiv().
 * The parameters necessary to edit a database record are also passed as
 * parameters.
 *
 *   @param  string      title                   title of the popup div
 *   @param  string      control                 url of control to be loaded
 *   @param  string      vars                    post names and values seperated by '&'
 *   @param  object      event                   mouse event passed by function call
 *   @param  object      args       [optional]   object containing hoverDiv options
 *   @param  integer     divWidth   [optional] 	 value for the width of the div
 *   @param  integer     divHeight  [optional]   value for the height of the div
 *   @param  integer     relX       [optional]   if you want to move the x-coord relative px from the event
 *   @param  integer     relY       [optional]   if you want to move the y-coord relative px from the event
 *   @param  integer     absX       [optional]   if you want to hard code the x-coord
 *   @param  integer     absY       [optional]   if you want to hard code the y-coord
 *   @param  string      callType   [optional]   'send to control' via 'GET' or 'POST'
 *   @param  string      pControl   [optional]   the name of the control you'll call to refresh the data
 *   @param  string      pVars      [optional]   any vars you need for the pControl
 *   @param  string      pTargetDiv [optional]   the div surrounding the pControl
 *   @param  function    callback   [optional]   custom callback function for hoverDiv if we need more than html filling
 *   @param  function    pCallback  [optional]   custom callback function for the parent
 *   @return   void
 *
 *	note:  to close the parent hoverDiv id dynamically --> deleteNode($(this).parents('div[@name=hoverDiv]'))
 *
 */

var hoverCount=0; // global function to track count of hoverDivs in the DOM
function hoverDiv(title, control, vars, event, args)
{
	$.each( $('div[name=hoverDiv]'), function(i,n)
	{
		var hoverNum = n.id.replace('hoverDiv','');
		if($('#hoverDivTitle' + hoverNum).html() == title ) //&& $(n).attr('rel') == control
		{
			deleteNode(n);
		}
		else
		{
			$('#hoverDiv' + hoverNum).css('z-index', 900);
		}
	});	
	hoverCount++;
	var thisHover = 'hoverDiv'+ hoverCount;
	var thisHoverContent = 'hoverDivContent'+ hoverCount;
	var thisHoverTitle = 'hoverDivTitle'+ hoverCount;
	var thisHoverClose = 'hoverCloseLink'+ hoverCount;
	var hoversDisplayed = $('div[name=hoverDiv]').length;
	$('div[name=hoverDivClone]').clone().attr('id', thisHover).attr('name', 'hoverDiv').appendTo('#hoverContainer');
	//$('#'+ thisHover).attr('rel', control);
	$('#'+ thisHover + ' .defaultBackground div').attr('id',thisHoverContent);
	$('#'+ thisHover + ' .hoverHeader div').attr('id',thisHoverTitle);
	$('#'+ thisHover + ' .hoverHeader a').attr('id', thisHoverClose);
	displayLoadingImg(thisHoverContent, 'large');
	if(typeof args == 'undefined' || typeof args != 'object'){  var args =  new Object;}
	if(typeof args.callback == 'undefined' || args.callback == '' || args.callback == null){ args.callback = cb_htmlReplace; }
	if(typeof args.pCallback == 'undefined' || args.pCallback == '' || args.pCallback == null) { args.pCallback = cb_htmlReplace; }
	if(typeof args.callType == 'undefined' || args.callType == '' || args.callType == null) { args.callType = 'GET'; }
	if(typeof args.pLoadGif == 'undefined' || args.pLoadGif == '' || args.pLoadGif == null) { args.pLoadGif = 'none'; }
	if(typeof args.absX == 'undefined' || args.absX == '' || args.absX == null){ args.absX = ($('div[name=hoverDiv]').length + 1) * 40; } // formula to cascade divs
	if(typeof args.absY == 'undefined' || args.absY == '' || args.absY == null){ args.absY = ($('div[name=hoverDiv]').length + 1) * 20; }
	if(typeof vars != 'undefined' && vars != '')vars += '&hoverId='+thisHover;
	else vars = 'hoverId='+thisHover;

	$('#'+ thisHoverTitle).html(title);
	if(typeof args.divWidth != 'undefined')
	{
		$('#'+ thisHover).css('width', args.divWidth);
		$('#'+ thisHoverContent).css('width', args.divWidth);
		$('#'+ thisHoverContent).css('overflow', 'auto');
	}
	else
	{
		$('#'+ thisHoverContent).css('width', 'auto');
		$('#'+ thisHoverContent).css('overflow', 'visible');
	}
	if(typeof args.divHeight != 'undefined')
	{
		var contentHeight = args.divHeight - 25;
		$('#'+ thisHover).css('height', args.divHeight);
		$('#'+ thisHoverContent).css('height', contentHeight);
		$('#'+ thisHoverContent).css('overflow', 'auto');
	}
	else
	{
		$('#'+ thisHoverContent).css('height', 'auto');
		$('#'+ thisHoverContent).css('overflow', 'visible');
	}
	if(typeof args.relX != 'undefined' && typeof args.relY != 'undefined')
	{
		var cursor = getPosition(event);
		if(cursor.x && cursor.y)
		{
			var adjLeft = cursor.x + args.relX;
			var adjTop = cursor.y + args.relY;
			$('#'+ thisHover).css('left', adjLeft);
			$('#'+ thisHover).css('top', adjTop);
		}
		else
		{
			$('#'+ thisHover).css('left', args.relX);
			$('#'+ thisHover).css('top', args.relY);
		}
	}
	else
	{
		$('#'+ thisHover).css('left', args.absX);
		$('#'+ thisHover).css('top', args.absY);
	}
	$('#'+ thisHover).css('display','block');
	//Hover Div "Drop Shadow"
/* 	$('#'+ thisHover).css('border-right', '4px solid #aaaaaa');
	$('#'+ thisHover).css('border-bottom', '2px solid #aaaaaa');
	$('#'+ thisHover).css('border-top', '1px solid white');
	$('#'+ thisHover).css('border-left', '1px solid white'); */

	ajaxRequest(control, vars, {'callType':args.callType, 'loadGif':'none', 'callback':args.callback, 'callbackVars':{'target':thisHoverContent} });
	$('#'+ thisHoverClose).click( function()
	{
		if(typeof args.pControl != 'undefined' && args.pControl!='')
		{
			if(typeof args.pTargetDiv == 'undefined'){args.pTargetDiv = '';} // prevent main by default which sets off history plugin
			ajaxRequest(args.pControl, args.pVars, {'loadGif':args.pLoadGif, 'callback':args.pCallback, 'callbackVars':{'target':args.pTargetDiv} });
		}
		deleteNode(thisHover);
	});
	$('#'+thisHoverTitle).dblclick( function()
	{
		$('#'+thisHoverContent).toggle();
		if( $('#'+thisHover).height()!= 25)
		{
			$('#'+thisHover).height(25);

			// Remove drop shadow
			$('#'+ thisHover).css('border', 'none');
		}
		else
		{
			$('#'+thisHover).height(args.divHeight);

			// Re-apply drop shadow
//			$('#'+ thisHover).css('border-right', '4px solid #aaaaaa');
//			$('#'+ thisHover).css('border-bottom', '2px solid #aaaaaa');
//			$('#'+ thisHover).css('border-top', '1px solid white');
//			$('#'+ thisHover).css('border-left', '1px solid white');
		}
	});
	$('#'+thisHover).click( function(event)
	{
		if(typeof event.target.onclick != 'undefined')
		{
			var clicked = String(event.target.onclick);
			if(clicked.indexOf('hoverDiv') != -1){return;}
		}

		if(typeof event.target.parentNode != 'undefined' && typeof event.target.parentNode.onclick != 'undefined')
		{
			var clickedParent = String(event.target.parentNode.onclick);
			if(clickedParent.indexOf('hoverDiv') != -1)	{return;}
		}

		$('div[name="hoverDiv"]').css('z-index', 900);
		$('#'+thisHover).css('z-index', 901);
	});
	$(".hoverFormDiv").draggable({	handle: '.handle', containment: 'body' });

}

// hoverDiv function
function getPosition(e)
{
	e = e || window.event;
	var cursor = {x:0, y:0};
	if (e.pageX || e.pageY)
	{
		cursor.x = e.pageX;
		cursor.y = e.pageY;
	}
	else
	{
		cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
		cursor.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop;
	}
	return cursor;
}

// delete hoverDiv
function deleteNode(nodeObj)
{
	if(typeof nodeObj == 'string')
	{
		$('#'+nodeObj).remove();
	}
	else if(typeof nodeObj == 'object')
	{
		$(nodeObj).remove();
	}
}

// delete hoverDiv
function deleteNodesByName(type,name)
{
	$(type+'[name='+name+']').remove();
}

/* Ajax onclick category wrapper (Allows for two ajax callbacks.) */
function add_edit_wrapper(key)
{
	/*Populate subcategory select list. */
	ajaxRequest('json.select_subcategories','catid='+key+'',{'callback':cb_subcategories, 'dataType':'json'});
	ajaxRequest('json.additional_fields','catid='+key+'',{'callback':cb_additional_fields, 'dataType':'json'});
};

/* Populates a subcategory select list on the selection of a parent category. */
function cb_subcategories(response, args)
{
	$("#subcategoryId").empty();
	$.each(response, function(i, val){
		if (val == 'All Sub-Categories') { 
			$("#subcategoryId").append("<option value='"+i+"' selected=\"selected\">" +val+ "</option>");
		} else {
			$("#subcategoryId").append("<option value='"+i+"'>" +val+ "</option>");
		}
	});
}

function cb_login(json, statusText)
{
	//take a JSON response, and handle
    if(typeof json != 'object'){alert('JSON object syntax error'); return false; }

    if(typeof json.redirect != 'undefined'){ajaxRequest(json.redirect, '', {'callbackVars':{'target':'container'}});}  
    else if(typeof json.message != 'undefined'){$('#loginText').html(decode(json.message));}
}

function cb_send_confirmation(response, args)
{
	if(response == 'true'){$('#loginText').html('Email Sent');}
	else{$('#loginText').html('Email Error');}
}

function cb_reset_password(json, statusText)
{
	//take a JSON response, and handle
    if(typeof json != 'object'){alert('JSON object syntax error'); return false; }

    if(typeof json.redirect != 'undefined'){ajaxRequest(json.redirect, '', {'callbackVars':{'target':'container'}});}  
    else if(typeof json.message != 'undefined'){$('#loginText').html(json.message);}
}

function cb_logo_management(json, statusText)
{
	//take a JSON response, and handle
    if(typeof json != 'object'){alert('JSON object syntax error'); return false; }

    if(typeof json.valid != 'undefined' && json.valid == 'true')
    { 
    	var gvars = 'target=content';
    	//$('#validation_message').addClass('success_message');
    	if(typeof json.userId != 'undefined'){gvars += '&userId='+json.userId;}
    	    	
    	ajaxRequest('logo_management', gvars, {'callbackVars':{'target':'content'}});
    }
    else
    {
    	$('#validation_message').addClass('message'); 
    	$('#validation_message').html(json.message);    	    	
    }      
}

function cb_ad_management(json, statusText)
{
	//take a JSON response, and handle
    if(typeof json != 'object'){alert('JSON object syntax error'); return false; }

    if(typeof json.valid != 'undefined' && json.valid == 'true')
    {
    	var gvars = 'target=content';
    	//$('#validation_message').addClass('success_message');
    	if(typeof json.userId != 'undefined'){gvars += '&userId='+json.userId;}
    	    	
    	ajaxRequest('ad_management', gvars, {'callbackVars':{'target':'content'}});
    }
    else
    {
    	$('#validation_message').addClass('message'); 
    	$('#validation_message').html(json.message);    	    	
    }      
}

function cb_register(json, statusText)
{
	//take a JSON response, and handle
    if(typeof json != 'object'){alert('JSON object syntax error'); return false; }

    if(json.valid == 'true')
    {
    	$('#main').html(json.message);
    }
    else
    {
    	$('#validation_message').addClass('message');
    	$('#validation_message').html(json.message);    	
    }    
    $(document).scrollTop(0);
}

function cb_listing(json, statusText)
{
	//take a JSON response, and handle
    if(typeof json != 'object'){alert('JSON object syntax error'); return false; }

    if(json.valid == 'true')
    {
    	$('#main').html(json.message);
    }
    else
    {
    	$('#validation_message').addClass('message');
    	$('#validation_message').html(json.message);    	
    }
    $(document).scrollTop(0);
}

/* Populates additional form fields based on corresponding parent category. */
function cb_additional_fields(response, args)
{
	$('#addFields1').empty();
	$('#addFields2').empty();
	$('#addFields3').empty();
	$('#addFields4').empty();

	/* Get total number of additional fields. */
	var count = 0;
	$.each(response, function(i, val){count++;});

	var columnCount = 4;
	var addFieldsCnt = count;
	var boxPerColumn = Math.ceil(addFieldsCnt/ columnCount); // 14.25 = 15

	var counter = 0;
	$.each(response, function(i, val){
		if(counter < boxPerColumn){
			$('#addFields1').append('<li><label><input type="checkbox" name="additionals[]" id="additionals'+i+'" value="'+i+'" />' + val + '</label></li>');}
		else if(counter < (boxPerColumn*2)){
			$('#addFields2').append('<li><label><input type="checkbox" name="additionals[]" id="additionals'+i+'" value="'+i+'" />' + val + '</label></li>');}
		else if(counter < (boxPerColumn*3)){
			$('#addFields3').append('<li><label><input type="checkbox" name="additionals[]" id="additionals'+i+'" value="'+i+'" />' + val + '</label></li>');}
		else{
			$('#addFields4').append('<li><label><input type="checkbox" name="additionals[]" id="additionals'+i+'" value="'+i+'" />' + val + '</label></li>');}
		counter++;
	});
}

/**** Combo box functions begin. ***/
/* Returns the make list for the combo box selection. */
function cb_return_make_list(response, args) {
	$("#make_selector").empty();
	$("#make_selector").show();
	if (jQuery.isEmptyObject(response)) {
		$("#make_selector").append("There were no makes found. <br />");
	} else {
		$("#make_selector").append("Please select one of the following makes: <br />");
	}
	$.each(response, function(i, val) {
		$("#make_selector").append("<div id=\""+i+"\" onclick=\"select_make(this.id, '"+val+"');\"><a href=\"#\" onClick=\"return false\" >" +val+ "</a></div>");
	});

};

function select_make(id, val) {
	$("#manufacturerId").val(id);
	$("#make").val(val);
	$("#make_selector").fadeToggle("fast", "linear");
	$("#make_status").html("<a href=\"#\" onClick=\"unselect_make();return false\">Change</a>");
	$("#make").attr("readOnly", true);
	$('#model').removeAttr('disabled');
}

function unselect_make() {
	$("#make_selector").empty();
	$("#manufacturerId").val('');
	$("#make").val('');
	$("#make_selector").fadeToggle("fast", "linear");
	$("#make_status").html("");
	$("#make").attr("readOnly", false);
	unselect_model();
	$('#model').attr('disabled', 'disabled');
}

function cb_return_model_list(response, args) {
	$("#model_selector").empty();
	$("#model_selector").show();

	if (jQuery.isEmptyObject(response)) {
		$("#model_selector").append("There were no models found. <br />");
	} else {
		$("#model_selector").append("Please select one of the following models: <br />");
	}

	$.each(response, function(i, val) {
		$("#model_selector").append("<div id=\""+i+"\" onclick=\"select_model(this.id, '"+val+"');\"><a href=\"#\" onClick=\"return false\" >" +val+ "</a></div>");
	});
	$("#model_selector").append("<div id=\"modelAlt\" onclick=\"select_modelAlt();\">Don't see your model listed? <a href=\"#\" onClick=\"return false\" >Enter your own >></a></div>");
};

function cb_confirmListingRenew(response, args)
{
	if(typeof response.error != 'undefined')
    {
    	alert(response.error);
    	$('#'+args.target).html('<img src="/images/icons/error.png" title="Listing Renewal Unconfirmed" />');
    	return false;
    }
    $('#'+args.target).html('<img src="/images/icons/accept.png" title="Listing Renewed" />');
    $('#'+args.target2).html('90 days');
    $('#'+args.target2).removeClass('expiration_days');
}

function select_model(id, val) {
	$("#modelId").val(id);
	$("#model").val(val);
	$("#model_selector").fadeToggle("fast", "linear");
	$("#model_status").html("<a href=\"#\" onClick=\"unselect_model();return false\">Change</a>");
	$("#model").attr("readOnly", true);
}

function select_modelAlt() {
	$("#model").toggle();
	$("#modelAlt").toggle();
	$("#modelId").val('');
	$("#model").val('');
	$("#model_selector").fadeToggle("fast", "linear");
	$("#model_status").html("<a href=\"#\" onClick=\"unselect_model();return false\">Change</a>");
	$("#model").attr("readOnly", false);
}

function unselect_model(mode) {
	if( $('#model').is(':visible') ) {
		mode = 'normal';
	} else {
		mode = 'alt';
	}
	$("#model_selector").fadeToggle("fast", "linear");
	if (mode == 'normal') {
		$("#model_selector").empty();
		$("#modelId").val('');
		$("#model").val('');
		$("#model_status").html("");
		$("#model").attr("readOnly", false);
	} else if (mode == 'alt') {
		$("#model").toggle();
		$("#modelAlt").toggle();
		$("#modelAlt").val('');
		$("#model_selector").empty();
		$("#model_status").html("");
		$("#model").attr("readOnly", false);
	}
}

/* Add edit listing toggle functions */
function toggleAdditionalDetails() {
	/*Change headers */
	if($('#additional_details_container').is(":visible") && ($('#toggle_value').val() != '1')) {
		$('#toggle_additional_details').removeClass('active_section');

	} else {
		$('#toggle_additional_details').addClass('active_section');

	}

	if (($('#toggle_value').val() == '0') || ($('#toggle_value').val() == '1')) {
		$('#additional_details_container').fadeIn('slow', 'linear');
		$('#toggle_value').val('2');
	} else {
		$('#additional_details_container').fadeToggle('slow', 'linear');
		$('#toggle_value').val('2');
	}

	$('#listing_details_container').hide();
	$('#photos_container').hide();

	$('#toggle_listing_details').removeClass('active_section');
	$('#toggle_photos').removeClass('active_section');
}

function toggleListingDetails() {
	/*Change headers */
	if(($('#listing_details_container').is(":visible")) && ($('#toggle_value').val() != '1')) {
		$('#toggle_listing_details').removeClass('active_section');

	} else {
		$('#toggle_listing_details').addClass('active_section');

	}

	if (($('#toggle_value').val() == '0') || ($('#toggle_value').val() == '1')) {
		$('#listing_details_container').fadeIn('slow', 'linear');
		$('#toggle_value').val('2');
	} else {
		$('#listing_details_container').fadeToggle('slow', 'linear');
		$('#toggle_value').val('2');
	}

	$('#additional_details_container').hide();
	$('#photos_container').hide();

	$('#toggle_additional_details').removeClass('active_section');
	$('#toggle_photos').removeClass('active_section');
}

function togglePhotos() {
	/*Change headers */
	if($('#photos_container').is(":visible") && ($('#toggle_value').val() != '1'))
	{
		$('#toggle_photos').removeClass('active_section');
	}
	else
	{
		$('#toggle_photos').addClass('active_section');
		photo_order_string();
	}

	if (($('#toggle_value').val() == '0') || ($('#toggle_value').val() == '1')) {
		$('#photos_container').fadeIn('slow', 'linear');
		$('#toggle_value').val('2');
	} else {
		$('#photos_container').fadeToggle('slow', 'linear');
		$('#toggle_value').val('2');
	}

	$('#additional_details_container').hide();
	$('#listing_details_container').hide();

	$('#toggle_additional_details').removeClass('active_section');
	$('#toggle_listing_details').removeClass('active_section');
	$(document).scrollTop(0);
}

function allToggle() {
	/*0 = minimized all, 1 = expanded all, 2 = neither */
	var value = $('#toggle_value').val();

	/* if ((value == 2) || (value == 0)) { */
	if ($('#toggle_all').html() == 'Expand all steps') {
		$('#additional_details_container').fadeIn("slow");
		$('#listing_details_container').fadeIn("slow");
		$('#photos_container').fadeIn("slow");


		$('#toggle_photos').addClass('active_section');
		$('#toggle_listing_details').addClass('active_section');
		$('#toggle_additional_details').addClass('active_section');

		$('#toggle_value').val('1');
		$('#toggle_all').html('Minimize all steps');
		photo_order_string();

	} else {

		$('#additional_details_container').fadeOut("slow");
		$('#listing_details_container').fadeOut("slow");
		$('#photos_container').fadeOut("slow");

		$('#toggle_photos').removeClass('active_section');
		$('#toggle_listing_details').removeClass('active_section');
		$('#toggle_additional_details').removeClass('active_section');

		$('#toggle_value').val('0');
		$('#toggle_all').html('Expand all steps');
	}
}

/*** Combo box functions end. ***/

/*** AutoSuggest Functions ***/
// Auto-Complete PopUp Div Functions
var as_ajaxObj; //used to track current auto-complete ajax calls

function autoSuggest(formObj, e, options)
{ 
	if(formObj.value.replace(/^\s+|\s+$/g,"").length < 1)
	{ 
		$('#'+formObj.id+'_autoSuggest').css('display','none');
		return;
	}
	if(window.event) // 2009.7.14 both ie and firefox are using this if block
	{
		var k = e.keyCode;
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		var k = e.which;
	}
	if(e.ctrlKey==false && e.altKey==false && (e.metaKey==false || e.metaKey==undefined) && $(formObj).attr('readonly') != true)
	{ 
		var xtraVars = '';
		var debugVar = '';
		if(typeof as_ajaxObj != 'undefined'){as_ajaxObj.abort();}

		if(typeof options == 'undefined'){ options = new Object; }
		if(typeof options.action == 'undefined'){ options.action = 'json.auto_suggest'; }
		if(typeof options.allowTextSelect == 'undefined'){ options.allowTextSelect = false; }
		if(typeof options.onChangeCB == 'undefined'){ options.onChangeCB = 'popUp_defaultCallback';} 
		if(typeof options.debug == 'undefined' || options.debug == true){ debugVar = '&returnDebugLogs=1';}
		if(typeof options.varFields != 'undefined'){ xtraVars += '&'+$(options.varFields).fieldSerialize();}

		as_ajaxObj = ajaxRequest(options.action, 'searchType='+options.searchType +'&searchString='+ escape(formObj.value.replace( /^\s+$/g ,""))+xtraVars+debugVar,
			{
			'callback':cb_autoSuggest,
			'dataType':'json',
			'returnObj':true,
			'callbackVars':{'onChangeCallback':options.onChangeCB,'itemId':formObj.id, 'allowTextSelect':options.allowTextSelect}
			});
	}
}

function cb_autoSuggest(response, args)
{
	// add debug option for broken JSON!

	//take a JSON response, and turn it into a select list
    if(typeof response != 'object'){ return false; }

    // display debugger log information
    if(typeof response.debugLogs != 'undefined')
    {
    	debug_console(response.debugLogs);
    	delete response.debugLogs;
    }

    var options = '';
	
	//***Problem: Chrome and Opera Browsers DO NOT maintain insertion ORDER of the JSON object from PHP/SQL if the index is an integer. 
	//>>The browser just orders the object by the indexes instead. (This is not wanted if we want to preserve the order from the SQL.)
	//***Possible Solutions: 
	//>>1. In PHP append a string to the index. (Hacking not preferred but this is what is currently used. 
	//>>Two part hack: 
	//>>>Part 1a the PHP is changed for the index of the json response object. Refer to file: json.auto suggest for notes on this.
	//>>>Part 2a inside of the jquery '.each' statement for building the select list. the i.replace is used instead of just i to remove the appended string.

	//>>2. Consider writing a function to convert an object to an array. This is probably a cleaner solution but it seems like it would be resource expensive.
	
    $.each(response, function(i,item){ options = options+'<option value="'+i.replace("_str", "")+'">'+item+'</option>'; });

    if(args.allowTextSelect)
    {
    	var options = options+'<option value="override"> - Enter your own model - </option>';
    }

    //clear the request object
    //as_AjaxObj = undefined;

    if(typeof options == 'undefined' || options == '')
    {
    	$('#'+args.itemId+'_autoSuggest').css('display','none');
    	return false;
    }

    $('#'+args.itemId+'_autoSuggest').css('display', 'block');
    $('#'+args.itemId+'_autoSuggest').css('height', '0px');
	
	// For IE7 to correct strange positioning..
	if ( $.browser.msie && $.browser.version == '7.0') {
		$('#'+args.itemId+'_autoSuggest').css('margin-top', '-30px');
    }
	
    $('#'+args.itemId+'_autoSuggest').html('<div class="divSuggestBox"><select onchange="'+args.onChangeCallback+'(this);" size="5"   name="'+args.itemId+'_selectAutoSuggest" id="'+args.itemId+'_selectAutoSuggest" >'+options+'</select><a style="cursor: pointer;float:left" onclick="closeSuggestBox(\''+args.itemId+'_autoSuggest\');"><img src="/images/icons/close_icon.gif" border="0"></a></div>');
}

function closeSuggestBox(id)
{
	$('#'+id).css('display','none');
	$('#'+id).empty();
}

function popUp_defaultCallback(obj)
{ 
	var formId = obj.id.replace('_selectAutoSuggest','');
	var formType = formId.replace('Search','');
	var hidFormId = formId.replace('Search','Id');

	if(obj.value != 'override'){$('#'+formId).val(obj.options[obj.options.selectedIndex].text);}
	$('#'+hidFormId).val(obj.value);
	$('#'+formId+'_autoSuggest').empty();
	
	autoSuggestOnBlur(hidFormId, formId);
	
	lockTextbox(formType);
}

function popUp_selectManufacturerCallback(obj)
{
	$('#modelSearch').removeAttr('disabled');
	popUp_defaultCallback(obj);
}

function popUp_DealerSelect(obj) 
{ 
 	var formId = obj.id.replace('_selectAutoSuggest','');
	var formType = formId.replace('Search','');
	var hidFormId = formId.replace('Search','Id');

	if(obj.value != 'override'){$('#'+formId).val(obj.options[obj.options.selectedIndex].text);}
	$('#'+hidFormId).val(obj.value);
	$('#'+formId+'_autoSuggest').empty();
	
	autoSuggestOnBlur(hidFormId, formId);
	
	lockTextbox(formType); 
}

function popUp_salesRepSelect(obj) 
{ 
 	var formId = obj.id.replace('_selectAutoSuggest','');
	var formType = formId.replace('Search','');
	var hidFormId = formId.replace('Search','Id');

	if(obj.value != 'override'){$('#'+formId).val(obj.options[obj.options.selectedIndex].text);}
	$('#'+hidFormId).val(obj.value);
	$('#'+formId+'_autoSuggest').empty();
	/* autoSuggestOnBlur(hidFormId, formId); */
	lockTextbox(formType);
}

/**
 * Disables an input element using the readonly element attribute
 *
 */
function lockTextbox(type, searchIcon, lockIcon, clearIcon)
{ 
	if(typeof searchIcon == 'undefined'){searchIcon = '/images/icons/search.png';}
	if(typeof lockIcon   == 'undefined'){lockIcon   = '/images/icons/lock.png';}
	if(typeof clearIcon  == 'undefined'){clearIcon  = '/images/icons/clear.gif';}
	
	if($('#'+type+'Search').attr('readonly') == true)
	{
		$('#'+type+'Lock').attr('src', clearIcon);
		$('#'+type+'Search').attr('readonly', false);
		$('#'+type+'Search').val('');
		$('#'+type+'Id').val('');
		$('#'+type+'SearchIcon').attr('src', searchIcon);
	
		if (type == 'dealerAssign') {
			$(':input','#account_assignment_form')
				.not(':button, :submit, :reset, #dealerAssignment')
				.val('')
				.removeAttr('checked')
				.removeAttr('selected');
		}
	
		if (type == 'salesRepAssign') {
			$(':input','#account_assignment_form2')
				.not(':button, :submit, :reset, #salesRepAssignment')
				.val('')
				.removeAttr('checked')
				.removeAttr('selected');
		}
	
	}
	else
	{
		$('#'+type+'Lock').attr('src', lockIcon);
		$('#'+type+'Search').attr('readonly', true);
		$('#'+type+'SearchDiv').css('display', 'none');
		$('#'+type+'SearchIcon').attr('src', clearIcon);
	}
	
	
	if (type == 'dealerAssign') { 
		$('#account_assignment_form').submit();
		 
	} else if (type == 'salesRepAssign') {
		$('#account_assignment_form2').submit();  
	}
	
	
}

function lockCheck(type, per, searchIcon, lockIcon, clearIcon)//'model'
{
	if(typeof searchIcon == 'undefined'){searchIcon = '/images/icons/search.png';}
	if(typeof clearIcon  == 'undefined'){clearIcon  = '/images/icons/clear.gif';}

	if($('#'+per+'Search').attr('readonly') == false)
	{
		$('#'+type+'Lock').attr('src', clearIcon);
		$('#'+type+'Search').attr('readonly', false);
		$('#'+type+'Search').val('');
		$('#'+type+'Id').val('');
		$('#'+type+'SearchIcon').attr('src', searchIcon);
		$('#'+type+'Search').attr('disabled', true);
	}
}

function cb_toggleListingStatus(response, args)
{
	var status = response.status;
	$('#status_'+response.id).html(response.html);
}

function valiHTTP(origVal, origId){
	
	if(origVal == '')
	{
		$('#'+origId).removeClass('invalid');
		return;
	}
	
	httpRe = /^(((ht|f)tp(s?))\:\/\/)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(\/($|[a-zA-Z0-9\.\,\;\?\'\\\+&%\$#\=~_\-]+))*$/;
	if(httpRe.test(origVal))
	{
		$('#'+origId).removeClass('invalid');
		return;
	}
	else
	{
		$('#'+origId).addClass('invalid');
		return;
	}
}

function valiSSN(ssn, origId, errMsg)
{
	for(index = 0; index < ssn.length; index++)
	{
		num = ssn.substr(index, 1);
		if(num == ' ')
		{
			ssn = ssn.replace(' ',''); //ssn.replace(' ','');
		}
		if(num == '-')
		{
			ssn = ssn.replace('-',''); //ssn.replace(/-/,'');
		}
	}
	$('#'+origId).val(ssn);
	
	if(!ssn || ssn == '' || isNaN(ssn) || ssn.length != 9)
	{
		if(errMsg)
		{
			$('#'+origId).val(errMsg);
		}
		$('#'+origId).addClass('invalid');
	}
	else
	{
		$('#'+origId).removeClass('invalid');
	}
}

/**
* function will ensure that data entered as a telephone number has at least 10 digits,
* any characters except digits will be discarded
*/
function validatePhone ( fieldValue )
{
	var validatedNumber = '';	
	var phoneDigitRegEx = /^\d{10,}$/; // phone number is 10, or more, digits
	var phoneCharacterRegEx = /[-a-zA-Z\(\)\.]/; // use to check for junk chararcters
// 2009.7.10 need a way to distinguish between wats number and numbers with extensions	
	if ( fieldValue.match ( phoneDigitRegEx ) )
	{
		if ( fieldValue.length > 10 )
		{
			var firstDigits = fieldValue.substring(0,1);
			var tollFreePrefix = fieldValue.substring( 1,4 );
			var areaCode = fieldValue.substring( 4,7 );
			var exchange = fieldValue.substring( 7,11 );
			//var subscriber = fieldValue.substring( 11 );
			
			validatedNumber = firstDigits+'-'+tollFreePrefix+'-'+areaCode+'-'+exchange;
		}
		else
		{
			var areaCode = fieldValue.substring( 0,3 );
			var exchange = fieldValue.substring( 3,6 );
			var subscriber = fieldValue.substring( 6,10 );
			var extension = fieldValue.substring( 10 );
			validatedNumber = areaCode+'-'+exchange+'-'+subscriber;
			if ( extension != '' )
			{
				validatedNumber = areaCode+'-'+exchange+'-'+subscriber+' x'+extension;
			}
		}
		return validatedNumber;
	}
	else if ( fieldValue.match ( phoneCharacterRegEx ) )
	{
		var phoneNumber = fieldValue.split ('');
		for ( var i = 0; i < fieldValue.length; i++ )
		{
			if ( phoneNumber[i].match( /[0-9]/ ) )
			{
				validatedNumber += phoneNumber[i];
			}
		}
		
		// throw in some recursion
		validatedNumber = validatePhone(  validatedNumber );
		return validatedNumber;
	}
	else
	{
		return false;
	}
}

function valiPhone(phone, oId )
{
	//This function was phased out by MLR on 11/3/09 and replaced within the code with checkPhoneFields
	checkPhoneFields(oId);
	return true;
}

//
//function valiPassword(passwd, strength)
//{
//    
//   // Password Strength Factors and Weightings
//    /*
//    password length:
//    level 0 (3 point): less than 4 characters
//    level 1 (6 points): between 5 and 7 characters
//    level 2 (12 points): between 8 and 15 characters
//    level 3 (18 points): 16 or more characters
//    
//    letters:
//    level 0 (0 points): no letters
//    level 1 (5 points): all letters are lower case
//    level 2 (7 points): letters are mixed case
//    
//    numbers:
//    level 0 (0 points): no numbers exist
//    level 1 (5 points): one number exists
//    level 1 (7 points): 3 or more numbers exists
//    
//    special characters:
//    level 0 (0 points): no special characters
//    level 1 (5 points): one special character exists
//    level 2 (10 points): more than one special character exists
//    
//    combinatons:
//    level 0 (1 points): letters and numbers exist
//    level 1 (1 points): mixed case letters
//    level 1 (2 points): letters, numbers and special characters 
//    					exist
//    level 1 (2 points): mixed case letters, numbers and special characters exist
//    */
//    
//    if(typeof strength == 'undefined'){strength = 0;}
//
//	var intScore   = 0;
//	var strVerdict = 'weak';
//
//	// check password length
//	if (passwd.length < 4)          
//	{
//		intScore = (intScore + 3);		
//	}
//	else if (passwd.length >= 4 && passwd.length < 7)  
//	{
//		intScore = (intScore + 8);		
//	}
//	else if (passwd.length >= 7 && passwd.length < 12) 
//	{
//		intScore = (intScore + 15);		
//	}
//	else if (passwd.length >= 12)                     
//	{
//		intScore = (intScore + 20);
//	}
//	
//	// check for letters in the password
//	if (passwd.match(/[a-z]/))                               
//	{
//		intScore = (intScore  + 1);
//	}
//	
//	if (passwd.match(/[A-Z]/))                             
//	{
//		intScore = (intScore + 5);		
//	}
////2008.7.31 there's something in this block of code that needs to be escaped	
//	// check the numbers
//	if (passwd.match(/\d+/))                                  
//	{
//		intScore = (intScore+5);
//	}
//	
//	if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/))  
//	{
//		intScore = (intScore + 5);		
//	}
//	
//	// check for special characters
//	if (passwd.match(/.[!,@,#,$,%,^,\s,&,*,?,_,~]/))  
//	{         
//		intScore = (intScore + 8);
//	}	
//								 
//	if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/))
//	{
//		intScore = (intScore + 8);
//	}
//	
//	 // check for combinations
//	if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))        
//	{
//		intScore = (intScore + 2);
//	}
//
//	if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) 
//	{
//		intScore = (intScore + 2);
//	}
//								
//	if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,\s,_,~].*[a-zA-Z0-9])/))
//	{
//		intScore = (intScore + 2);
//	} 
//	// end block of code	
//
//	// check the total score to state password strength
//	if(intScore < 5)
//	{
//	   $('#meter_msg').html('weak password'); 
//	   $('#meter1').css('background-color', '#FFFFFF');
//	   $('#meter2').css('background-color', '#FFFFFF');
//	   $('#meter3').css('background-color', '#FFFFFF');
//       $('#meter4').css('background-color', '#FFFFFF');
//	}
//	else if (intScore > 5 && intScore < 12)
//	{
//	   $('#meter_msg').html('mediocre password');
//   	   $('#meter1').css('background-color', '#BF0000');
//	   $('#meter2').css('background-color', '#FFFFFF');
//	   $('#meter3').css('background-color', '#FFFFFF');
//       $('#meter4').css('background-color', '#FFFFFF');	   
//	}
//	else if (intScore > 11 && intScore < 22)
//	{
//	   $('#meter_msg').html('average password');
//   	   $('#meter1').css('background-color', '#EF8100');
//	   $('#meter2').css('background-color', '#EF8100');
//	   $('#meter3').css('background-color', '#FFFFFF');
//       $('#meter4').css('background-color', '#FFFFFF');	   
//	}
//	else if (intScore > 21 && intScore < 32)
//	{
//	   $('#meter_msg').html('good password');
//   	   $('#meter1').css('background-color', '#DCEF3B');
//	   $('#meter2').css('background-color', '#DCEF3B');
//	   $('#meter3').css('background-color', '#DCEF3B');
//       $('#meter4').css('background-color', '#FFFFFF');	   
//	}
//	else
//	{
//	   $('#meter_msg').html('strong password');
//   	   $('#meter1').css('background-color', '#77EF3B');
//	   $('#meter2').css('background-color', '#77EF3B');
//	   $('#meter3').css('background-color', '#77EF3B');
//       $('#meter4').css('background-color', '#77EF3B');	   
//	}  
//
//	//if(strength == 1)
//	//{
//		$('#strength').val(intScore);
//	//}	
// }

 function valiNumeric(val, id)
 { 	
 	if(val != '' && !isNumeric(val))
	{
		$('#'+id).addClass('invalid');
	}
	else
	{
		$('#'+id).removeClass('invalid');
	}
 }
 
function valiIsDigit(val)
{
	var digits="1234567890";
	for (var i=0; i < val.length; i++)
	{
		if (digits.indexOf(val.charAt(i))==-1){return false;}
	}
	return true;
}

/* The onchange event of the batch options select list (Listing Management)*/
function batch_check(value)
{
	if(value == 'change_ownership'){$("#change_ownership").show();}
	else {$("#change_ownership").hide();}
}

/* Toggle registration fields between dealer and classified. */
function toggle_registration_fields() 
{
	if($('input[name="access"]:checked').val() == 3) // dealer
	{
		$('#input_dealerCompany').css('display','');
		$('#input_farmName').css('display','none');
		$('#dealer_fields_container').css('display','');
		$('#classified_fields_container').css('display','none');		
		$('#companyName').removeAttr('disabled');
	}
	else // classified user
	{
		$('#input_dealerCompany').css('display','none');
		$('#input_farmName').css('display','');
		$('#dealer_fields_container').css('display','none');
		$('#classified_fields_container').css('display','');
		$('#companyName').attr('disabled', 'disabled');
	}
}

/*Photo Gallery Viewer*/
function swapListingImage(image)
{
	$("#primary_image").html('<a href="' + image + ' " target="_blank"> <img src="' + image + '" class="primary_listing_image"/></a>');
}

var directionDisplay;
var directionsService = new google.maps.DirectionsService();

/*The Get Directions Feature & wrapper */
function getDirections(latitude, longitude)
{
	$("#directionsPanel").empty();
	//if($('#start').val() == ''){$('#start').val(prompt('Enter your starting location\n Ex: 102 Main Street Louisville Kentucky 40202',''));}
	initialize(latitude, longitude);
}

function initialize(latitude, longitude)
{
// latitude = '36.8823111';
// longitude = '-85.9082068';
	var latlng = new google.maps.LatLng(latitude, longitude);
	directionsDisplay = new google.maps.DirectionsRenderer();

	var settings = {
		zoom: 15,
		center: latlng,
		mapTypeControl: true,
		mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		navigationControl: true,
		navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};


	var map = new google.maps.Map(document.getElementById("map_canvas"), settings);
	google.maps.event.trigger(map, 'resize');
	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(document.getElementById("directionsPanel"));

	var contentString = '<div id="content">'+
	'<div id="siteNotice">'+
	'</div>'+
	'<h1 id="firstHeading" class="firstHeading">User Name goes here.</h1>'+
	'<div id="bodyContent">'+
	'<p style="color:#000; font-size:.7em">User Description goes here.</p>'+
	'</div>'+
	'</div>';
	 /* This was the marker content window.
	var infowindow = new google.maps.InfoWindow({
	content: contentString
	});
	*/

	var companyPos = new google.maps.LatLng(latitude, longitude);
	var companyMarker = new google.maps.Marker({
		position: companyPos, map: map, title:"Start"});

	google.maps.event.addListener(companyMarker, 'click', function(){infowindow.open(map,companyMarker);});

	calcRoute(latitude, longitude);

	/*
	directionsService.route(request, function(response, status) {
	if (status == google.maps.DirectionsStatus.OK) {
	directionsDisplay.setDirections(response);
}

});
*/
}

function calcRoute(latitude, longitude)
{
	$('#map_canvas').css('width','100%');
	$('#directionsPanel').css('width','100%');

	var start = $('#start').val();
	var end = latitude + ', ' + longitude;

	var request = {
		origin:start,
		destination:end,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};

	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
		}
	});
}

function showGetDirections(latitude, longitude, multiple, company_name) {

	$('#print_directions_link').show();
	$('#directions_div').show();

	if (multiple == 'true') {
		$('#directions_title').html('Get Directions to ' +company_name);
		$('#directionsForm').attr("onSubmit", "getDirections('"+latitude+"', '"+longitude+"');return false;");
		$('#directions_button').attr("onClick", "getDirections('"+latitude+"', '"+longitude+"');return false;");
	}

	$('#directions_button').click();
}

function printDirections()
{
  var disp_setting="toolbar=yes,location=no,directories=yes,menubar=yes,";
      disp_setting+="scrollbars=yes, left=100, top=25";
  var content_vlue = document.getElementById("print_content").innerHTML;

  var docprint=window.open("","",disp_setting);
   docprint.document.open();
   docprint.document.write('<html><head><title>Inventory Report</title>');
   docprint.document.write('<link href="/css/print_friendly.css" rel="stylesheet" type="text/css" /> ');
   docprint.document.write('</head><body onLoad="self.print()"><center>');
   docprint.document.write(content_vlue);
   docprint.document.write('</center></body></html>');
   docprint.document.close();
   docprint.focus();
}

function resetTheForm(formId){
	$('#'+formId).clearForm();
}

/* Loan calculator callback */
function cb_loanCalculator(response, args) {
	$('#loan_result').html(response);
}

function reportListing(listing_id)
{
	if(confirm('Are you sure you want to report this listing as spam?'))
	{
		ajaxRequest('ajax.insert_stat','id='+listing_id+'&type=5',{'loadGif':'small', 'callback':cb_reportListing, 'dataType':'html', 'callbackVars': {'target':'#report_listing_span'}});
	}
}

function cb_reportListing(response, args) 
{
	$('#report_listing_span').html('<span style="color:#900;"><img src="/images/icons/warning.png" width="25" height="25" alt="Notice" style="margin-bottom:-8px;"/> Listing Has Been Reported</span>');
}

function cb_photo_management(response, args) 
{
	$('#photo_management').html(response);
	//Update the 'photos_order' string since the files have completed uploading.
	photo_order_string();
}

/* Photo management -- delete photo callback */
function cb_photo_management_delete_photo(json, args) 
{
	//take a JSON response, and handle
    if(typeof json != 'object'){alert('JSON object syntax error'); return false; }
    
	if(json.status == 'true') 
	{
		$('#' + json.element_id).remove();
		$('#photo_management_delete_photo').html('The file ' + json.filename + ' was successfully deleted.');
		$('#thumbnail_cropper').css('display','none');

		// decrease the photosPending count to avoid error
		if(json.in_stamp == 'true')
		{
			$('#photosPending').val(parseInt($('#photosPending').val()) - 1);
		}
		else
		{
			$('#photoCount').val(parseInt($('#photoCount').val()) - 1);
		}		
		$('#photosLeft').html(25 - parseInt($('#photosPending').val()) - parseInt($('#photoCount').val()));
		
		//Update the 'photos_order' string
		photo_order_string();
	} 
	else 
	{
		$('#photo_management_delete_photo').html('Error: File was not successfully deleted. ');
	}
}

/* Photo management -- update the 'photos_order' string inside form. */
var main_thumb = false;
var true_width = false;
var true_height = false;
var jcrop_api;

function photo_order_string()
{
	$('#crop').val(0);
	$('#crop_msg').empty();

	var list_elements = $('#photo_management').find('li');
	var order = new Array();
	var pending = 0;

	$.each(list_elements, function(i, val){
		var image_div =  $(val).attr('id');
		var filename = $('#' +image_div+ '_path').val();
		var photo_id = $('#' +image_div+ '_photoid').val();
		if(i == 0){main_thumb = image_div;}

		if(photo_id == '') { order[i] = filename; pending++;}
		else { order[i] = photo_id; }
	});

	// double check count here (if same file uploaded twice it will count 2 as 1)
	$('#photosPending').val(parseInt(pending));
	$('#photosLeft').html(25 - parseInt(pending) - parseInt($('#photoCount').val()));
	
	if(order.length > 0)
	{
		$('#photos_order').val(order.join(':'));
	}
	else
	{
		$('#photos_order').val('');
		return true;
	}

	/* Note: Use this method for accessing attributes... output = order["1"]["orderid"];  */

	// if main image does not have correct ratio then open up the image cropper
	if($('#'+main_thumb+'_ar').val() == 1)
	{
		$('#thumbnail_cropper').css('display','none');
	}
	else
	{
		true_width = parseInt($('#'+main_thumb+'_w').val());
		true_height =  parseInt($('#'+main_thumb+'_h').val());

		$('#thumbnail_cropper').css('display','block');
		$('#jcrop_div').empty();
		$('#jcrop_div').prepend('<img src="" id="jcrop" />');

		if($('#'+main_thumb+'_photoid').val() == '') { var src = 'fetch_file/?file='+$('#'+main_thumb+'_path').val()+'&stamp='+$('#listing_photoStamp').val(); }
		else if($('#show_original').val() == 1) { var src = 'fetch_file/?id='+$('#'+main_thumb+'_photoid').val();}
		else { var src = 'fetch_file/?id='+$('#'+main_thumb+'_photoid').val()+'&thumb';}
		$('#jcrop').attr('src', src);
		$('#jpreview').attr('src', src);

		$('#thumbnail_cropper').waitForImages(function(){

			jcrop_api = $('#jcrop').Jcrop({
				onChange: updateCoords,
	            onSelect: updateCoords,
				aspectRatio: 4 / 3,
				setSelect: [ 0, 0, 200, 150 ],
				trueSize: [true_width, true_height],
				boxWidth: 475 //maximum width of image
			});
			jcrop_api.animateTo([ 0, 0, 200, 150 ]);
		});
	}
}

function setCrop()
{
	$('#crop').val(1);
	$('#thumbnail_cropper').css('display','none');
	$('#crop_msg').html('Thumbnail settings are ready. We will finalize the process during the save (Publish Listing)');
}

function showOriginal(stamp, listing_id)
{
	if($('#show_original').val() == 0)
	{
		$('#show_original').val(1);
		ajaxRequest('ajax.photo_management','stamp='+stamp+'&listingid='+listing_id+'&original',{'loadGif':'small', 'callback':cb_photo_management, 'dataType':'html', 'callbackVars': {'target':'#photo_management'}});
		$('#show_original_link').html('Show Thumb');
	}
	else
	{
		$('#show_original').val(0);
		ajaxRequest('ajax.photo_management','stamp='+stamp+'&listingid='+listing_id,{'loadGif':'small', 'callback':cb_photo_management, 'dataType':'html', 'callbackVars': {'target':'#photo_management'}});
		$('#show_original_link').html('Show Original');
	}
}

/**
 * function updateCoords(c)
 * updates the selection in jCrop image
 * also prepares live preview
 */
function updateCoords(c)
{
	$('#x').val(c.x);
	$('#y').val(c.y);
	$('#w').val(c.w);
	$('#h').val(c.h);

    var rx = 200 / c.w;
    var ry = 150 / c.h;

    // Live Preview
    $('#jpreview').css({
        width: Math.round(rx * $("#jcrop").width()) + 'px',
        height: Math.round(ry * $("#jcrop").height()) + 'px',
        marginLeft: '-' + Math.round(rx * c.x) + 'px',
        marginTop: '-' + Math.round(ry * c.y) + 'px'
    });
}

/* Toggle listings mode */
function toggle_listings_mode(mode) {
	if (mode == 'gallery') {
		$('#mode').val('list');
		$('#equipmentForm').submit();
	} else {
		$('#mode').val('gallery');
		$('#equipmentForm').submit();
	}
}

function openMailMessage(ob, email_id)
{
	$(ob).toggleClass('email_active');
	$(ob).removeClass('unread_message');
	$('#email_message_container'+email_id).toggle();
	ajaxRequest('mailbox','markSelected=1&messages['+email_id+']=1',{'callback':cb_nothing,'callbackVars':{'target':''}});
}

/* Dealer Search -- Email */

function dealer_search_email(user_id, company_name_counter, company_email) {
	var company_name_string = $('#companyName_'+ company_name_counter).val();

	$('#email_form_title').html('Email ' + company_name_string);
	$('#email_form_div').show();
	$('#ownerId').val(user_id);
	$('#ownerEmail').val(company_email);
	$('#dealer_contact_email_container').html('');

	document.getElementById("name").focus();
}

/* Inventory Report, send data to hover div. */
/*
To make this function portable you could consider passing the form in as an object, then looping through it to get all the values.
Taking the hover func params as the function params.
*/
function inventory_report_hover(event, excel) 
{
/* Get the values from the form to get GET vars. */
	getVars = [];

	$("#report_checkboxes_container :checked").each(function() {
		getVars.push($(this).val() + "=" + $(this).val());
	});

	$('#select_list_container :selected').each(function() {
		getVars.push($(this).parent().attr("name") + "=" + $(this).val());
	});

	getVars.push("userId" + "=" + $('#userId').val());
	
	if (excel == 'true') {
		getVars.push('excel' + "=" + 'true');
		stringGetVars = getVars.join('&');
		window.open ("/hover.inventory_report?" +stringGetVars,"mywindow","status=1");
	} else {
		getVars.push('excel' + "=" + 'false');
		stringGetVars = getVars.join('&');
		hoverDiv('Report', 'hover.inventory_report', stringGetVars, event, {'relX':-280,'relY':-390});
	}
}

function cb_unread_mail_count(response, args){
	$(".unread_mail_count").html(response);
}

function selectCheckBox(row, isChecked, e)
{	
	e = e || window.event;	
	if(isChecked){$('#email_title_bar'+row).addClass('email_active');}
	else{$('#email_title_bar'+row).removeClass('email_active'); }		
	$('#email_message_container'+row).hide(); 	
	e.stopPropagation();
}

function selectCheckBoxAll(isChecked)
{		
	if(isChecked){$('ul[name=email_title_bar]').addClass('email_active');}
	else{$('ul[name=email_title_bar]').removeClass('email_active'); }		
	$('div[name=email_message_container]').hide(); 	
}

function autoSuggestOnBlur(hidden_id, input_id) {
/* Params needed: input field id, field name, */

	id_value = $('#'+ hidden_id).val();
	tip_div = '#' + input_id + 'Tip';	
	
	if (id_value == '') {
		
		$('#'+ input_id).css("border", "1px solid red");
		
		$(tip_div).html("<img width=\"25\" height=\"25\" style=\"margin-bottom:-8px;\" alt=\"Notice\" src=\"/images/icons/warning.png\">You have not made a selection.");
		$(tip_div).css("display", "block");
		$(tip_div).css("background-color", "#CCCCCC");
		$(tip_div).css("border-radius", "5px 5px 5px 5px");
		
	} else { /* selected so return the form field back to css state. */
		$('#' + input_id).css("border", "1px solid #CCCCCC");
		$(tip_div).css("display", "none");
		$(tip_div).empty();
	}
	
}

function select_cat_value(id, label)
{
	$('#lu_id').val(id);
	$('#lu_label').val(label);
	
	$('span[name=cat_link]').removeClass('pseudo_link_selected');
	$('#cat_link'+id).addClass('pseudo_link_selected');
	
	$('#lu_form_title').html('Edit');
	
	ajaxRequest('ajax.list_category_subcategories','categoryId='+id, {'callback':cb_fill_category_subs, 'callbackVars':{'target':'edit_subs_container'}});
	
	$(document).scrollTop(0);
}

function select_subcat_value(id, label)
{
	$('#lu_id_subcategory').val(id);
	$('#lu_label_subcategory').val(label);
	
	$('span[name=sub_link]').removeClass('pseudo_link_selected');
	$('#sub_link'+id).addClass('pseudo_link_selected');
	
	$('#lu_form_title_subcategory').html('Edit');
	
	$(document).scrollTop(0);
}

function select_make_value(id, label)
{
	$('#lu_id').val(id);
	$('#lu_label').val(label);
	
	$('span[name=make_link]').removeClass('pseudo_link_selected');
	$('#make_link'+id).addClass('pseudo_link_selected');
	
	$('#lu_form_title').html('Edit');
	
	ajaxRequest('ajax.list_manufacturer_models','manufacturerId='+id, {'callback':cb_fill_make_models, 'callbackVars':{'target':'edit_models_container'}});
	ajaxRequest('ajax.list_manufacturer_keywords','manufacturerId='+id, {'callback':cb_fill_make_keywords, 'callbackVars':{'target':'edit_keywords_container'}});
	
	$(document).scrollTop(0);
}

function select_model_value(id, label)
{
	$('#lu_id_model').val(id);
	$('#lu_label_model').val(label);
	
	$('span[name=mod_link]').removeClass('pseudo_link_selected');
	$('#mod_link'+id).addClass('pseudo_link_selected');
	
	$('#lu_form_title_model').html('Edit');
	
	$(document).scrollTop(0);
}

function select_feed_value(id)
{
	$('#feed').val(id);
	$('span[name=feed_link]').removeClass('pseudo_link_selected');
	$('#feed_link'+id).addClass('pseudo_link_selected');
	
	if($('#map').val() != ''){ajaxRequest('ajax.list_map_data','feed='+$('#feed').val()+'&map='+$('#map').val(), {'callback':cb_fill_map_data, 'callbackVars':{'target':'list_refs_container'}});}
	$('#list_ref_logs_container').hide();
	$('#referenceId').val('');
	$('#reference').val('');
	$('#matchId').val('');
	$('#matchSearch').val('');
	$('#matchSearchIcon').attr('src', '/images/icons/search.png');
	$('#matchLock').attr('src', '/images/icons/clear.gif');
	$('#matchSearch').attr('readonly', false);
}

function select_map_value(id)
{
	if(id == 1){$('#map').val('subcategory');}
	else if(id == 2) {$('#map').val('manufacturer');}
	$('span[name=map_link]').removeClass('pseudo_link_selected');
	$('#map_link'+id).addClass('pseudo_link_selected');
	if(id==1){$('#matchLabel').html('Subcategory'); $('#map').val('subcategory');}
	else if(id==2){$('#matchLabel').html('Manufacturer'); $('#map').val('manufacturer');}
	
	if($('#feed').val() != ''){ajaxRequest('ajax.list_map_data','feed='+$('#feed').val()+'&map='+$('#map').val(), {'callback':cb_fill_map_data, 'callbackVars':{'target':'list_refs_container'}});}
	$('#list_ref_logs_container').hide();
	$('#referenceId').val('');
	$('#reference').val('');
	$('#matchId').val('');
	$('#matchSearch').val('');
	$('#matchSearchIcon').attr('src', '/images/icons/search.png');
	$('#matchLock').attr('src', '/images/icons/clear.gif');
	$('#matchSearch').attr('readonly', false);
}

function select_ref_value(ref, id, s)
{
	$('#referenceId').val(ref);
	$('#reference').val(ref);
	$('#matchId').val(id);
	$('#matchSearch').val(s);
	
	$('#matchSearchIcon').attr('src', '/images/icons/clear.gif');
	$('#matchLock').attr('src', '/images/icons/lock.png');
	$('#matchSearch').attr('readonly', true);
		
	$('span[name=ref_link]').removeClass('pseudo_link_selected');
	$('#ref_link_'+ref).addClass('pseudo_link_selected');
	$('#ref_link_id_'+ref).addClass('pseudo_link_selected');

	$('#list_ref_logs_container').hide();
}

function delete_keyword_value(word)
{
	if(confirm('Are you sure you want to delete this keyword?'))
	{
		ajaxRequest('ajax.list_manufacturer_keywords','delete=1&manufacturerId='+$('#lu_id_keyword_make').val()+'&word='+word, {'callback':cb_fill_make_keywords, 'callbackVars': {'target':'edit_keywords_container'}});		
	}	
}

function cb_fill_category_subs(response, args)
{
	if(response == ''){return true;}	
	$('#edit_subs_container').show();
	$('#edit_subs_container').html(response);
	initAjaxFormListener();
}

function cb_fill_make_models(response, args)
{
	if(response == ''){return true;}	
	$('#edit_models_container').show();
	$('#edit_models_container').html(response);
	initAjaxFormListener();
}

function cb_fill_make_keywords(response, args)
{
	if(response == ''){return true;}	
	$('#edit_keywords_container').show();
	$('#edit_keywords_container').html(response);
	initAjaxFormListener();
}

function cb_fill_map_data(response, args)
{	
	$('#'+args.target).show();
	$('#'+args.target).html(response);
}

function clear_cat_value()
{
	$('#lu_id').val('');
	$('#lu_label').val('');
	$('span[name=cat_link]').removeClass('pseudo_link_selected');
	$('#lu_form_title').html('Add');

	clear_subcat_value();
	$('#lu_id_sub_category').val('');
	$('#edit_subs_container').hide();
}

function clear_subcat_value()
{
	$('#lu_id_subcategory').val('');
	$('#lu_label_subcategory').val('');
	$('span[name=sub_link]').removeClass('pseudo_link_selected');
	$('#lu_form_title_subcategory').html('Add');	
}

function clear_make_value()
{
	$('#lu_id').val('');
	$('#lu_label').val('');
	$('span[name=make_link]').removeClass('pseudo_link_selected');
	$('#lu_form_title').html('Add');

	clear_model_value();
	$('#lu_id_model_make').val('');
	$('#edit_models_container').hide();
	$('#edit_keywords_container').hide();
}

function clear_model_value()
{
	$('#lu_id_model').val('');
	$('#lu_label_model').val('');
	$('span[name=mod_link]').removeClass('pseudo_link_selected');
	$('#lu_form_title_model').html('Add');	
}

function clear_map_value()
{
	$('#feed').val('');
	$('#map').val('');
	$('#referenceId').val('');
	$('#reference').val('');	
	$('#matchId').val('');
	$('#matchSearch').val('');
	
	$('span[name=feed_link]').removeClass('pseudo_link_selected');
	$('span[name=map_link]').removeClass('pseudo_link_selected');
	$('span[name=ref_link]').removeClass('pseudo_link_selected');
	
	$('#lu_form_title').html('Add');
	$('#matchLabel').html('');
	
	$('#matchSearchIcon').attr('src', '/images/icons/search.png');
	$('#matchLock').attr('src', '/images/icons/clear.gif');
	$('#matchSearch').attr('readonly', false);
	
	$('#list_refs_container').hide();
	$('#list_ref_logs_container').hide();
}

function delete_model_value()
{
	if(confirm('Are you sure you want to delete this model?'))
	{
		ajaxRequest('ajax.delete_model','delete=1&manufacturerId='+$('#lu_id_model_make').val()+'&modelId='+$('#lu_id_model').val(), {'callback':cb_fill_make_models, 'callbackVars': {'target':'edit_models_container'}});		
	}
}

function get_data_links(ref)
{
	$('#referenceId').val(ref);
	$('#reference').val(ref);
	$('#matchId').val('');
	$('#matchSearch').val('');
	$('#matchSearchIcon').attr('src', '/images/icons/search.png');
	$('#matchLock').attr('src', '/images/icons/clear.gif');
	$('#matchSearch').attr('readonly', false);
	
	ajaxRequest('ajax.list_map_logs','feed='+$('#feed').val()+'&map='+$('#map').val()+'&reference='+ref, {'callback':cb_fill_map_data, 'callbackVars':{'target':'list_ref_logs_container'}});
	$(document).scrollTop(0);
}

function open_link(feed, file, link)
{
	$('#'+link).addClass('pseudo_link_selected');
	window.open('/fetch_log/?feed='+feed+'&file='+file);
}

function cb_clearCache(response, args) 
{
    $('#'+args.target).html(response); 
}

function cb_tractorhouseCleanup(response, args) 
{ 
//alert ('here' +args.target + 'response: ' + response);
    $('#'+args.target).html(response); 
}

function cb_analyzeDB(response, args)
{	
    $('#'+args.target).html(response); 
}

function cb_checkDeleteAccount(response, args)
{
	if(response.deleted_check.length > 0) {
		$('#delete_account').html(response.deleted_check);
	} else {
		if (response.listings_check == 1) {
			var answer = confirm("This account has listings are you sure you want to delete it and the listings?")
			
			if (answer) {
				ajaxRequest('json.delete_account','id='+response.id,{'loadGif':'small', 'callback':cb_deleteAccount, 'dataType':'json', 'callbackVars': {'target':'#delete_account'}});
			} else {
				$('#delete_account').html('Please refresh to attempt to delete account again.');
			}
			
		} else {
			ajaxRequest('json.delete_account','id='+response.id,{'loadGif':'small', 'callback':cb_deleteAccount, 'dataType':'json', 'callbackVars': {'target':'#delete_account'}});
		}
	}
}

function cb_deleteAccount(response, args) {
	$('#delete_account').html(response.html);
}

function cb_confirmAccount(response, args) {
	$('#confirm_account').html(response.html);
}
function cb_doNotUpdateAccount(response, args) {
	$('#doNotUpdate_account').html(response.html);
}
function cb_cloakListings(response, args) {
	$('#cloakListingsSpan').html(response.html);
}
function cb_batchMap(response, args) {
	$('#'+response.response_div).html(response.html);
}

function generate_sitemap()
{
	if(confirm("Sitemap is generated nightly via cron. Are you sure you want generate a new sitemap now?\nThe sitemap may take a few minutes to load"))
	{
		ajaxRequest('cron_jobs/cron.update_sitemap','', {'callback':function(){window.open('/fetch_sitemap');}, 'callbackVars': {'target':''}});
		//window.open('sitemap.xml');
		$(document).scrollTop(0);
	}
	return false;
}

function toggle_assign_form(val){

	searchIcon = '/images/icons/search.png';
	lockIcon   = '/images/icons/lock.png';
	clearIcon  = '/images/icons/clear.gif';

	if (val == 'dealer_account_assignment_form') {
		$('#'+val).show();
		$('#salesrep_account_assignment_form').hide();
		$('#dealerAssignmentTable').hide(); 
		$('#salesRepAssignmentTable').hide();
		$('#account_assignment_title').html("<span style=\"color:#090; padding-right:15px;\">Step 2:</span>Dealer Account Assignment");
		
		//clear out other assignment form...
  		$(':input','#account_assignment_form2')
			.not(':button, :submit, :reset, #dealerAssignment, #salesRepAssignment')
			.val('')
			.removeAttr('checked')
			.removeAttr('selected');  
	
		var type = 'salesRepAssign';
		$('#'+type+'Lock').attr('src', clearIcon);
		$('#'+type+'Search').attr('readonly', false);
		$('#'+type+'Search').val('');
		$('#'+type+'Id').val('');
		$('#'+type+'SearchIcon').attr('src', searchIcon);

 		var type = 'salesRepAdd';
		$('#'+type+'Lock').attr('src', clearIcon);
		$('#'+type+'Search').attr('readonly', false);
		$('#'+type+'Search').val('');
		$('#'+type+'Id').val('');
		$('#'+type+'SearchIcon').attr('src', searchIcon);
	
	} else if (val == 'salesrep_account_assignment_form') {
		$('#'+val).show();
		$('#dealer_account_assignment_form').hide();
		$('#salesRepAssignmentTable').hide();
		$('#dealerAssignmentTable').hide();
		
		$('#account_assignment_title').html("<span style=\"color:#090; padding-right:15px;\">Step 2:</span>Sales Rep Account Assignment");
		
		//clear out other assignment form...
  		$(':input','#account_assignment_form')
			.not(':button, :submit, :reset, #dealerAssignment, #salesRepAssignment')
			.val('')
			.removeAttr('checked')
			.removeAttr('selected');  
		
  		var type = 'dealerAssign';
		$('#'+type+'Lock').attr('src', clearIcon);
		$('#'+type+'Search').attr('readonly', false);
		$('#'+type+'Search').val('');
		$('#'+type+'Id').val('');
		$('#'+type+'SearchIcon').attr('src', searchIcon);
		
		var type = 'dealerAdd';
		$('#'+type+'Lock').attr('src', clearIcon);
		$('#'+type+'Search').attr('readonly', false);
		$('#'+type+'Search').val('');
		$('#'+type+'Id').val('');
		$('#'+type+'SearchIcon').attr('src', searchIcon); 	
		
	}
}

function assignment_link(dealer_id, dealer_name) {

	//Switch to the dealer form.
	$('#dealer_account_assignment_form').show();
	$('#salesrep_account_assignment_form').hide();
	$('#dealerAssignmentTable').hide(); 
	$('#salesRepAssignmentTable').hide();
	$('#account_assignment_title').html("Dealer Account Assignment");
	
	//clear out other assignment form...
	$(':input','#account_assignment_form2')
		.not(':button, :submit, :reset, #dealerAssignment, #salesRepAssignment')
		.val('')
		.removeAttr('checked')
		.removeAttr('selected');  

	var type = 'salesRepAssign';
	$('#'+type+'Lock').attr('src', clearIcon);
	$('#'+type+'Search').attr('readonly', false);
	$('#'+type+'Search').val('');
	$('#'+type+'Id').val('');
	$('#'+type+'SearchIcon').attr('src', searchIcon);

	var type = 'salesRepAdd';
	$('#'+type+'Lock').attr('src', clearIcon);
	$('#'+type+'Search').attr('readonly', false);
	$('#'+type+'Search').val('');
	$('#'+type+'Id').val('');
	$('#'+type+'SearchIcon').attr('src', searchIcon);

	//submit the dealer form with the dealer_id param
	$('#dealerAssignId').val(dealer_id);
	$('#dealerAssignSearch').val(dealer_name);
	
	$('#account_assignment_form').submit();
	
}

function toggle_visibility (object) {
	/* Loop through each show object and show it. */
	$.each(object.show, function() {
		
		$(''+this).show();  
	});
	
	/* Loop through each hidden object and hide it.  */
	$.each(object.hide, function() {
		$(''+this).hide(); 
	});

}

function validation (object, type, params) {
	
	/***
	Properties of form element to use...
	
	Name: object.name
	Value: object.value
	Text length: object.textLength
	Tag Name (What type of form element.. input, select, etc.) : object.element.tagName
	
	The following function will show you all attributes of the form element you are working within the 
	firebug console:
	
		$.each(object.element, function(index, value){
			console.log('index: ' +index+ ' value:'+value);
		});
	
	*** Types ***
	'charlimit' : This will specify that the field needs to have a character limit. This will only work on text area and input.
		Params:
			limit: the character limit.
	
	
	
	***/
	
	//alert(type.charlimit.limit);	
	
	
	/* Character Limit */
	if(typeof type.charlimit != 'undefined'){
				
		//character limit value
		var character_number_value = type.charlimit.number;
		
		//input value
		var input_value = object.value;
				
		if (input_value.length > character_number_value) {
			
			allowed_value = input_value.substr(0, character_number_value)
			
			$('[name="'+object.name +'"]').val(allowed_value);
		
			if(typeof type.charlimit.message != 'undefined'){
				var char_limit_message = type.charlimit.message;
			} else {
				var char_limit_message = 'The character limit of ' +character_number_value+ ' characters has been exceeded!';
			}
			
			if ($('#'+object.name+'_validate').length == 0) {
				$('[name="'+object.name +'"]').after('<div id="'+object.name+'_validate">'+char_limit_message+'</div>');
			} 

			
		} else {
			if ($('#'+object.name+'_validate').length) {
				$('#'+object.name+'_validate').remove();
			}
		
		}
		
	}
		
}

function cb_add_user_email(json, statusText)
{
	//take a JSON response, and handle
    if(typeof json != 'object'){alert('JSON object syntax error'); return false; }

    if(typeof json.valid != 'undefined' && json.valid == 'true')
    {
    	$('#add_email_span').addClass('green_text');
    	ajaxRequest('ajax.user_email_list', 'userId='+json.userId, {'callbackVars':{'target':'user_email_list'}});
    }
    else
    {
    	$('#add_email_span').addClass('red_text');    	    	    	
    }
    $('#add_email_span').html(json.message);
}

function ObjectToArray(obj) {

	var arr = [];

	for (var key in obj) {
		if (obj.hasOwnProperty(key)) {
		  arr.push(obj[key]);  
		}
	}
	return arr;

}
