var currStep = 1;

/** Startup stuff ** */
function startupSequence() {
	initializeModals();
	registerEventListeners();
}

var currentPicture = 0;
function loadNextPicture() {
	if(currentPicture < 12) {
		currentPicture++;
	}
	superfluid.displayImage("/visualizer/collateral/Slide" + currentPicture + ".JPG");
	
}

function loadPreviousPicture() {
	if(currentPicture > 1) {
		currentPicture--;
	}
	superfluid.displayImage("/visualizer/collateral/Slide" + currentPicture + ".JPG");
}

function initializeModals() {
	$("#help-video").dialog({
		bgiframe : true,
		autoOpen : false,
		title : "Installing the Plugin on Internet Explorer",
		draggable : false,
		resizable : false,
		modal : true,
		position : [ 'center', 150 ],
		width : 700,
		height : 580
	});
	$("#screenshotComplete").dialog({
		bgiframe : true,
		autoOpen : false,
		title : "Screenshot Successful!",
		draggable : false,
		resizable : false,
		position : [ 'center', 150 ],
		modal : true
	});
	$("#failed-id").dialog({
		bgiframe : true,
		autoOpen : false,
		title : "Failed to Identify Target",
		draggable : false,
		resizable : false,
		position : [ 'center', 150 ],
		modal : true,
		buttons : {
			OK : function() {
				$(this).dialog('close');
			}
		}
	});
	$("#productDescription").dialog({
		bgiframe : true,
		autoOpen : false,
		title : t("Product Description"),
		draggable : false,
		resizable : false,
		modal : true,
		position : [ 'center', 150 ],
		width : "50%",
		height : 450
	});
	$("#attributeDescription").dialog({
		bgiframe : true,
		autoOpen : false,
		title : t("Product Description"),
		draggable : false,
		resizable : false,
		modal : true,
		position : [ 'center', 50 ],
		width : "50%",
		height : 550
	});
	$("#save-and-share").dialog({
		dialogClass : 'share-dialog',
		bgiframe : true,
		autoOpen : false,
		title : t("Save &amp; Share"),
		draggable : false,
		resizable : false,
		modal : true,
		position : [ 'center', 150 ],
		width : 640,
		height : 500
	});
	$("#uploadImage").dialog({
		bgiframe : true,
		autoOpen : false,
		title : t("Upload Your Image"),
		draggable : false,
		resizable : false,
		modal : true,
		position : [ 'center', 150 ],
		width : "50%",
		height : 300
	});
	$("#help").dialog({
		dialogClass : 'help-dialog',
		autoOpen : false,
		title : "Helpful Hints",
		draggable : false,
		resizable : false,
		modal : true,
		position : 'center',
		width : 800,
		height : 600
	});
	$("#a.close-button").click(function() {
		$('#help').dialog("close");
	});
}

function registerEventListeners() {
	$('#share-link').click(function() {
		if(navigator.appName != 'Microsoft Internet Explorer') {
			$('#save-and-share').dialog("open");
		}
		else {
			$('#accordion-wrapper').hide();
			$('#save-and-share-sidebar').show();
		}
	});
	$('#save-and-share-results-ok').click(function() {
		$('#save-and-share-results').hide();
		$('#accordion-wrapper').show();
	});
	$('.back-to-accordion').click(function() {
		$('.sidebar-mode').hide();
		$('#accordion-wrapper').show();
	});
	$(document).keyup(function(e) {
  		if (e.keyCode == 27) {
  			superfluid.toggleTool('base');
  			
  		}
 });

}

/** ************ Help functions ****************** */
function contextualHelp(source, key) {
	showHelpStep(0);
	$('.contextual-help-item').each(function() {
		$(this).hide();
	});
	$('#' + key).show();
	$('#contextual-help').animate({
		backgroundColor : "#666666"
	}, 0, function() {
		$(this).animate({
			backgroundColor : "#333333"
		}, 300);
	});
}

function clearHelp() {
	showHelpStep(currStep);
}

function initializeHelp() {
	generateHelpFunction('#imgLoadPhoto', 'load-photo');
	generateHelpFunction('#samplePhotos', 'sample-photo');
	generateHelpFunction('#imgSaveImage', 'save-image');
	generateHelpFunction('#activeProducts', 'active-products');
	clearHelp();
	$('.step-1-link').click(function() {
		$('#accordion').accordion("activate", 0);
	});
	$('.step-2-link').click(function() {
		$('#accordion').accordion("activate", 1);
	});
	$('.step-4-link').click(function() {
		$('#accordion').accordion("activate", 3);
	});
}

function generateHelpFunction(id, key) {
	$(id).hover(function() {
		var el = $(id);
		var timeoutId = setTimeout(function() {
			contextualHelp(id, key);
		}, 100);
		$(id).mouseleave(function() {
			clearTimeout(timeoutId);
			clearHelp();
		});
	}, function() {
		clearHelp();
	});
}

function showHelpStep(step) {
	// Keep track of what step is being shown so that contextual help replaces
	// it and comes back
	if (step != 0) {
		currStep = step;
	}
	$('.help-step').each(function() {
		$(this).hide();
	});
	$('#help-content-step-' + step).show();
}

/** ************ Screenshot functions ************* */
function uploadScreenshotToServer(file, clientName) {
	var xhr = new XMLHttpRequest();
	var self = this;
	var params = {};
	var actions = [];
	
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			var text = '';
			endModal();
			if ($("#save-to-facebook").is(":checked")) {
				text += 'Your photo has been shared into the "Lynx Photos" album.';
			}
			if ($("#save-to-desktop").is(":checked")) {
				if(navigator.appName != 'Microsoft Internet Explorer') {
					text += 'Your download will begin momentarily';
					setTimeout(
						function() {
							var result = eval('(' + xhr.responseText + ')');
							$('#page-wrapper')
							.append(
											'<iframe src="/visualizer/fb/download.php?file='
											+ encodeURIComponent(result['downloadPath'])
											+ '">');
						}, 1000);
				}
				else {
					var result = eval('(' + xhr.responseText + ')');
					text += '<a href="/visualizer/fb/download.php?file='+ 
						encodeURIComponent(result['downloadPath'])
						+ '">Click here</a> to download your screenshot';
				}
			}
        	if(navigator.appName == 'Microsoft Internet Explorer') { 
        		$('#save-and-share-sidebar').hide();
        		$('#save-and-share-message').html(text);
        		$('#save-and-share-results').show();
        	}
        	else {
        		$('#screenshotComplete').dialog("open");
        		$('#feedback-message').html(text);
        	}
		}
	};
	if ($("#save-to-facebook").is(":checked")) {
		actions.push('save_to_facebook');
		params['caption'] = $('#caption').val();
	}
	if ($('#send-to-dealer').is(":checked")) {
		actions.push('email');
		params['name'] = $('#dealerform-name').val();
		params['email'] = $('#dealerform-email').val();
		params['phone'] = $('#dealerform-phone').val();
		params['additional'] = $('#dealerform-message').val();
	}
	// build query string
	var name = "UploadedFile.jpg";
	params['qqfile'] = name;
	params['client'] = clientName;
	params['actions'] = actions.join(';');
	var queryString = $.param(params);
	xhr.open("POST",
			'/visualizer/fb/upload-from-screenshot.php?' + queryString, true);
	xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
	xhr.setRequestHeader("X-File-Name", encodeURIComponent(name));
	xhr.setRequestHeader("Content-Type", "application/octet-stream");
	xhr.send(file);
	/*
	 * xhr.upload.onprogress = function(e){ if (e.lengthComputable){
	 * self._loaded[id] = e.loaded; self._options.onProgress(id, name, e.loaded,
	 * e.total); } };
	 */
}

function insertDealerInfo(zipcode, clientName) {
	$('body').css('cursor', 'progress');
	$.ajax({
				url : '/visualizer/fb/dealer-locator.php?client=' + clientName
						+ '&zipcode=' + zipcode,
				dataType : 'json',
				success : function(data) {
					var result = '<table id="dealer-locator-table"><tr><th>Dealer Name</th><th>Address</th><th>Phone</th><th>Distance</th><th></th></tr>';
					for ( var i = 0; i < data.length; i++) {
						result += '<tr><td>' + data[i]['DealerName'] + "</td>";
						result += '<td>' + data[i]['Address'] + "</td>";
						result += '<td>' + data[i]['PhoneNumber'] + "</td>";
						result += '<td>' + data[i]['Miles'].toFixed(2)
								+ "</td>";
						result += '<td><a class="use-link" href="#">Use</a></td></tr>';
					}
					result += '</table>';
					$('body').css('cursor', 'auto');
					$('#dealer-locator-table').html(result).slideDown();
					$('.use-link').click(function() {
						$('#dealer-locator-table').html(result).slideUp();
					});
				}
			});
}
