/*
	This function runs when the page load is complete.
	It set up the global interface overrides etc.
*/
$(document).ready( function() {						
		
	heartBeat(ident);
		
	/* behaviours for Manufacturer / Model drop-down selectors in site header */
	$("#STM_selManufacturer").change( function() {
		var name = $(this).val();
		//console.log('/ajax/__lampModels.asp?name='+encodeURIComponent(name));
		$.ajax({
			type: "POST", 
			url: "/ajax/__lampModels.asp", 
			data: "name="+encodeURIComponent(name), 
			dataType: "xml", 
			async: true,
			cache: false,
			success: function(xml) { populateModels(xml); }, 
			error: function() { alert("ERROR - AJAX failed: "+encodeURIComponent(name)); }	
		});
	});

	$("#STM_selModel")
		.change( function() {
			var mo = this.value;
			var ma = $("#STM_selManufacturer").val();
			//console.log('/ajax/__lampResults.asp?make='+ma+'&model='+mo);
			$.ajax({
				type: "POST",
				url: "/ajax/__lampResults.asp",
				data: "make="+ma+"&model="+mo,
				dataType: "html",
				async: true,
				cache: false,
				success: function(html) { populateResults(html); }, 
				error: function() { alert("ERROR - AJAX failed ??"); }	
			});				   
		})
		.ajaxStart(function() {$(this).attr("disabled", "disabled");})
		.ajaxStop(function() {$(this).attr("disabled", "");});
		
	$(".STM_loading").hide()
		.ajaxStart( function() { $(this).show(); })
		.ajaxStop( function() { $(this).hide(); });
		
	$("#STM_results").hide();
	$("#emailResult").hide();
	
	//Keep Alive heartbeat
	setInterval("heartBeat(ident);", 1080000); // every 5 minutes
	
});


//Keep Alive heartbeat AJAX call
function heartBeat(ident) {
	$.ajax({
		type: "POST", 
		url: "/ajax/__keepAlive.asp", 
		dataType: "html", 
		async: false,
		cache: false,
		success: function(html) { if (html!=ident)
		{
			if ($.browser.version != $.browser.safari) {
				var href = window.location.href; 
				window.location.href = href;
			}
			
			// DO NOTHING HERE becuase of Safari
		} }
	});
}

/*
	This function uses and AJAX call to populate the Lamp Model selector 
	based on the selected lamp manufacturer
*/
function populateModels(xml) {
	var error = $("error", xml).text();
	if(error != '') {
		$("#STM_selModel").empty().addOption("", error, true);
	} else {
		$("#STM_selModel").empty().addOption("", choose_model, true);
		$("model", xml).each( function(i) { 
			var iID = $(this).attr("id");
			var sName = $(this).attr("name");
			//console.log(iID + " | " + sName);
			$("#STM_selModel").addOption(iID, sName, false); 
		});
	};
}

function populateResults(html) {
	$("#STM_results").slideUp('slow', function(){ $(this).html(html).slideDown('slow'); });	
	$(".linkback").click( function() { 
		var rel= $(this).attr("rel");
		var href = $(this).attr("href");
		var bReturn = false;		
		if (rel != '') {			
			var arrData = rel.split("|");			
			$.ajax({
				type: "POST",
				url: "/ajax/__recordStats.asp",
				data: "make="+arrData[0]+"&model="+arrData[1],
				dataType: "html",
				async: true,
				cache: false,
				complete: function() { 
					$("#STM_selManufacturer").selectOptions("", true); 
					try {
						parent.window.location.href = href;

					} catch(ex) { 
						// do nothing 
					}

				}
			});		
		}
		return true;
	});
	
	
}

function handleEnquiryForm() {

		var frmData = $("#frmEmailRequest").serialize();
		$("#emailRequest").hide();
		$("#emailResult").html("<p>Sending...</p>").show();
		$.ajax({
			type: "POST",
			url: "/ajax/__sendEnquiry.asp",
			data: frmData,
			dataType: "xml",
			async: false,
			cache: false,
			success: function(xml) { 
				var iStatus = $("status", xml).text();
				var sMessage = $("message", xml).text();
				//sMessage = utf8_decode(sMessage);
				
				$("#emailResult").html("<p>"+sMessage+"</p>");
				if (iStatus != 1) { $("#emailRequest").show(); }					
				//console.log(iStatus + ' : ' + sMessage);
			},
			error: function() {
				$("#emailResult").hide().html();
				$("#emailRequest").show();				
				alert("AJAX Error!");	
			}
		});
		return false;							
}



function utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    
    str_data += '';
    
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }

    return tmp_arr.join('');
}



