var rWebRoot = window.location.protocol+'//www.tahoeturbines.com';
var rPageItemDisplay = rWebRoot+'/itemdisplay.php';
var rArgs = getUrlVars();
var rInv;

function getUrlVars() {
	var map = {};
	var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
		map[key] = value;
	});
	return map;
}

function rAjaxError() { alert('Ajax Error'); }

function loadFullSizeImg(e) {
	$(".inv-loadFullSize").html('<img src="'+ $(e).attr("src") +'" height="270" width="363" />');
}

function loadCMS(data) {
	// display the item
	if (rArgs['idi']) {
		var str = "";
		for(var i in data['results']['item']) {
			var engineOH = data['results']['item'][i]['engine_overhaul'] == 'Yes' ? ' (since overhaul)' : ' (since new)';
			var propOH = data['results']['item'][i]['prop_overhaul'] == 'Yes' ? ' (since overhaul)' : ' (since new)';

			// suppress display if DB says so
			var display_serial_num 	= data['results']['item'][i]['display_serial_number'] 		== 'Yes' ? 1 : 0;
			var display_reg_num	= data['results']['item'][i]['display_registration_number'] 	== 'Yes' ? 1 : 0;

			for(var i2 in data['results']['item'][i]) {
				var str = data['results']['item'][i][i2];
				if (i2.substring(4,0) == 'img_' && str && str != '') {
					// thumb
					var thumb = '<img style="margin: 0 3px 5px 0;" src="/admin/images/inventory/'+ str +'" height="60" width="80" onmouseover="loadFullSizeImg(this);return true;" />';
					$(".inv-"+i2+"-thumb").each(function () {
						$(this).html(thumb);
					});
					// full image
					str = '<img src="/admin/images/inventory/'+ str +'" height="270" width="363" />';
				} else if (i2.substring(4,0) == 'pdf_' && str && str != '') {
					//str = '<span class="link"><span><span><a href="/admin/pdf/inventory/'+ str +'">Download Quick Specifications (PDF)</a></span></span></span>';
					str = '<a class="link" target="_blank" href="/admin/pdf/inventory/'+ str +'"><span><span>Download Quick Specifications (PDF)</span></span></a>';
				} else if (i2.match(/engine_time$/) && str && str != '') {
					str = str + engineOH;
				} else if (i2.match(/prop_time$/) && str && str != '') {
					str = str + propOH;
				} else if (i2.match(/(serial_number|registration_number)/) && str && str != '') {
					if (
						(i2 == 'serial_number' 		&& !display_serial_num) ||
						(i2 == 'registration_number' 	&& !display_reg_num)
					) {
						str = 'Not shown at seller&rsquo;s request';
					}
					
				} else if (i2.match(/(list_avionics|list_additional_equipment|list_comments|list_maintenance|list_exterior_description|list_interior_description)/) && str && str != '') {
					opts = str.split(';');
					str = '<ul class="list-cms">';
					for(var i3 in opts) {
						str += '<li>'+opts[i3]+'</li>';
					}
					str += '</ul>';
				}
				$(".inv-"+i2).each(function () {
					$(this).html(str);
				});
			};
		};
	}

	var strListAll = "";
	var listAll = [];
	if (rArgs['all']) {
		for(var i in data['results']['list_all']) {
			var details = data['results']['list_all'];
			var engineOH = details[i]['engine_overhaul'] == 'Yes' ? ' (since overhaul)' : ' (since new)';
			strListAll += '<span id="inventory_listAll-'+i+'">';
			strListAll += '<table><tr><td style="padding-right:20px;">';
			strListAll += '<img src="/admin/images/inventory/'+(details[i]['img_fullsize_1'] ? details[i]['img_fullsize_1'] : 'no_image_available.jpg')+'" width="240" height="179" />';
			strListAll += '</div>';
			strListAll += '</td><td>';
			strListAll += '<h2>'+details[i]['description']+'</h2>';
			strListAll += 'Engine Time: '+details[i]['engine_time']+' '+engineOH+'<br/>';
			strListAll += details[i]['additional_comments']+'<br/>';
			strListAll += 'Asking Price: '+details[i]['asking_price']+'<br/><br/>';
			strListAll += '<a href="/itemdisplay.php?idi='+details[i]['id']+'" class="link"><span><span>Click here to learn more</span></span></a>';
			strListAll += '</td></tr></table>';
			strListAll += '</span><br /><br />';
		}
	}
	$(".inv-listAll").html(strListAll);

	// display the list
	var strList = "";
	var strListAll = "";
	for(var i in data['results']['list']) {
		var url = rPageItemDisplay;
		var id = i.replace(/'/g,'');
		strList += '<li><a href="'+url+'?idi='+id+'">'+data['results']['list'][i]+'</a></li>';
	}
	$(".inv-list").html(strList);
	$(".inv-drop").html(strList);
}

$(document).ready(function() { 
	//if (window.location.href == '') { rArgs['all'] = 1; }
	getInventory();

	// bind the form and provide a simple callback function 
//	$('#rContact').ajaxForm({
//		dataType:       'jsonp',
//		success:        rProcessContactSuccess,
//		error:		rNull,
//		type:           'get',
//		url:            rWebRoot+'/ws/contact_us.php',
//		clearForm:      true,
//		timeout:        3000
//	});

});
function rNull() {}

function getInventory() {
	$.ajax({
		dataType:       'jsonp',
		success:        loadCMS,
		error:		getInventory,
		type:           'get',
		url:            rWebRoot+'/admin/ws_cms.php?list=1'+ (rArgs['idi']?'&idi='+rArgs['idi']:'')+ (rArgs['all']?'&all=1':''),
		timeout:        3000
	});
}



/**
 * Function : rDump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function rDump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += rDump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

