var loading 	= '<p align="center"><span class="loader">Loading, Please Wait...</span><br><img src="images/ajax-flower-bg.gif" border="0" width="35" height="35" alt="Loading..."></p>';
var smloading 	= '<span class="goodtext">Loading...</span><img src="images/ajax-flower-sm.gif" border="0" width="15" height="15" alt="Loading...">';

//fix for having forms in modal overlay
$.extend($.ui.dialog.prototype.options, {
   zIndex: 10001
});

$.extend($.ui.dialog.overlay, { create: function(dialog){
	if (this.instances.length === 0) {
		// prevent use of anchors and inputs
		// we use a setTimeout in case the overlay is created from an
		// event that we're going to be cancelling (see #2804)
		setTimeout(function() {
			// handle $(el).dialog().dialog('close') (see #4065)
			if ($.ui.dialog.overlay.instances.length) {
				$(document).bind($.ui.dialog.overlay.events, function(event) {
					var parentDialog = $(event.target).parents('.ui-dialog');
					if (parentDialog.length > 0) {
						var parentDialogZIndex = parentDialog.css('zIndex') || 0;
						return parentDialogZIndex > $.ui.dialog.overlay.maxZ;
					}

					var aboveOverlay = false;
					$(event.target).parents().each(function() {
						var currentZ = $(this).css('zIndex') || 0;
						if (currentZ > $.ui.dialog.overlay.maxZ) {
							aboveOverlay = true;
							return;
						}
					});

					return aboveOverlay;
				});
			}
		}, 1);

		// allow closing by pressing the escape key
		$(document).bind('keydown.dialog-overlay', function(event) {
			(dialog.options.closeOnEscape && event.keyCode
					&& event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event));
		});

		// handle window resize
		$(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize);
	}

	var $el = $('<div></div>').appendTo(document.body)
		.addClass('ui-widget-overlay').css({
		width: this.width(),
		height: this.height()
	});

	(dialog.options.stackfix && $.fn.stackfix && $el.stackfix());

	this.instances.push($el);
	return $el;
}});

//jQuery extention to preload images
(function($) {
	var cache = [];
	$.preLoadImages = function() {
		var args_len = arguments.length;
		for (var i = args_len; i--;) {
			var cacheImage = document.createElement('img');
			cacheImage.src = arguments[i];
			cache.push(cacheImage);
		}
	}
})(jQuery);

//fix for zindex
function zFix() {
	var zIndexNumber = 10000;
	$('div').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 1;
	});
}

//ajax setup
$.ajaxSetup({
	type: "post"
});

//**************end setup stuff*******************
$(document).ready(function() {
	//preload some images
	jQuery.preLoadImages("images/ajax-flower-bg.gif", "images/ajax-flower-sm.gif");

	//this is to make sure all elements are in the correct stacking order (fucking ie!)
	zFix();
	//start terms
	$( "#termsLink" ).click(function() {
		termsAndPrivacy('terms', 'terms_main');
		return false;
	});
	//end terms

	//start privacy
	$( "#privacyLink" ).click(function() {
		termsAndPrivacy('privacy', 'privacy_main');
		return false;
	});
	//end privacy

	//start feedback form
	$( "#feedLink" ).click(function() {
		popReset();
		var form = $(
		'<div id="feed_response">'+
			'Use this form to provide us with feedback on the site:'+
		'</div>'+
		'<form action="#" method="post" name="feedform" id="feedform">'+
			'<label class="labelsm" for="name">Name:</label>'+
			'<div class="clearStuff"></div>'+
			'<input type="text" name="name" id="name" class="textxlg">'+
			'<div class="clearStuff"></div>'+
			'<label class="labelsm" for="email">Email:</label>'+
			'<div class="clearStuff"></div>'+
			'<input type="text" name="email" id="email" class="textxlg">'+
			'<div class="clearStuff"></div>'+
			'<label class="labelsm" for="subject">Subject:</label>'+
			'<div class="clearStuff"></div>'+
			'<input type="text" name="subject" id="subject" class="textxlg">'+
			'<div class="clearStuff"></div>'+
			'<label class="labelsm" for="feedtxt">Message:</label>'+
			'<div class="clearStuff"></div>'+
			'<textarea cols="22" rows="4" name="feedtxt" id="feedtxt" class="areafull"></textarea>'+
		'</form>'
		);

		$( "#popDialogDiv" ).empty().dialog({
			autoOpen: true,
			modal: true,
			width: 420,
			height: 'auto',
			position: 'center',
			title: 'Send Us Your Feedback',
			buttons: {
				Submit	: function() {
					var name = $('#name').val();
					var email = $('#email').val();
					var subject = $('#subject').val();
					var message = $('#feedtxt').val();
					var nocache = Math.random();
					$( "#popDialogDiv" ).html(loading);
					$.ajax({
						url: "global_feedback.php",
						dataType: "json",
						data: {
							name: name,
							email: email,
							subject: subject,
							message: message,
							nocache: nocache
						},
						success: function (response) {
							var status = response[0].status;
							var message = response[0].message;
							if (status == 'success') {
								$('#popDialogDiv').dialog('option', 'buttons', {
									close	: function() {
										$( this ).dialog( "close" );
									}
								});
								$( "#popDialogDiv" ).html(message);
							} else {
								$('#popDialogDiv').dialog('option', 'buttons', {
									close	: function() {
										$( this ).dialog( "close" );
									}
								});
								$( "#popDialogDiv" ).html(message);
							}
						}
					});
				},
				Cancel	: function() {
					$( this ).dialog( "close" );
				}
			}
		}).html(form);

		highlightField();
		$("#name").focus();
		return false;
	});
	//end feedback form

	if (location.pathname == '/' || location.pathname == '/index.php') {
		//start tour button
		$( "#tourBut" ).click(function() {
			dialogReset();

			$( "#dialogDiv" ).empty().dialog({
				autoOpen: true,
				modal: true,
				width: 600,
				height: 'auto',
				position: 'center',
				title: 'Enchanted Pages Tour'
			});
			return false;
		});
		//end tour

		//stuff for login
		$('#loglink').click(function() {
			$('#user').val('');
			$('#pass').val('');
			var logText = $('#loglink').text();
			if (logText == 'Cancel') {
				$('#loglink').text('Log In');
				$('#log').hide();
			} else {
				$('#loglink').text('Cancel');
				$('#log').show();
				highlightField();
				$('#user').focus();
			}
			return false;
		});

		$('#logCancel').click(function(){
			$('#loglink').text('Log In');
			$('#user').val('');
			$('#pass').val('');
			$('#log').hide();
		});

		$('#logform').submit(function() {
			var noCache = Math.random();
			var user = $('#user').val();
			var pass = $('#pass').val();
			var chal = $('#chal').val();
			$('#login_response').html(smloading);
			$.ajax({
				url: "http://www.enchantedpages.com/global_login.php",
				dataType: "json",
				data: {
					user: user,
					pass: pass,
					chal: chal,
					noCache: noCache
				},
				success: function (response) {
					//console.log(response);
					var status = response[0].status;
					var message = response[0].message;
					var reason = response[0].reason;
					if (status == 'failed') {
						$('#login_response').html(message);
						//console.log(reason);
					} else {
						$('#login_response').html(message);
						window.location = 'home.php';
					}
				}
			});
			return false;
		});

		//start forgot password
		$( "#forgot_pass" ).click(function() {
			popReset();
			$('#loglink').text('Log In');
			$('#user').val('');
			$('#pass').val('');
			$('#log').hide();
			var nocache = Math.random();
			$.ajax({
				url: "global_passForm.php",
				dataType: "json",
				data: {
					nocache: nocache
				},
				success: function (response) {
					var status = response[0].status;
					var message = response[0].message;
					$( "#popDialogDiv" ).html(message);
				}
			});

			$( "#popDialogDiv" ).empty().dialog({
				autoOpen: true,
				modal: true,
				width: 420,
				height: 'auto',
				position: 'center',
				title: 'Forgot Password',
				buttons: {
					Submit	: function() {
						var username = SHA1($('#username').val());
						var email = $('#email').val();
						var sqid = $('#sqid').val();
						var sqans = $('#sqans').val();
						var nocache = Math.random();
						$( "#popDialogDiv" ).html(loading);
						$.ajax({
							url: "global_passReset.php",
							dataType: "json",
							data: {
								username: username,
								email: email,
								sqid: sqid,
								sqans: sqans,
								nocache: nocache
							},
							success: function (response) {
								var status = response[0].status;
								var message = response[0].message;
								if (status == 'success') {
									$('#popDialogDiv').dialog('option', 'buttons', {
										close	: function() {
											$( this ).dialog( "close" );
										}
									});
									$( "#popDialogDiv" ).html(message);
								} else {
									$('#popDialogDiv').dialog('option', 'buttons', {
										close	: function() {
											$( this ).dialog( "close" );
										}
									});
									$( "#popDialogDiv" ).html(message);
								}
							}
						});
					},
					Cancel	: function() {
						$( this ).dialog( "close" );
					}
				}
			}).html(loading);

			highlightField();
			$("#email").focus();
			return false;
		});
		//end forgot password
		//end login stuff

		spotLight();

		//for fun poll
		$("input:radio").click(function() {
			fpUpdate();
		});
	}
});

//utility functions
function dialogReset() {
	var openDiv = $( "#dialogDiv" ).css('display');
	if (openDiv == 'block') {
		$( "#dialogDiv" ).empty().dialog( "close" );
	}
}

function helpReset()
{
	var openDiv = $( "#helpDiv" ).css('display');
	if (openDiv == 'block') {
		$( "#helpDiv" ).empty().dialog( "close" );
	}
}

function scrollTop() {
	$('html, body').animate({scrollTop: '0px'}, 75);
}

function popReset()
{
	var openDiv = $( "#popDialogDiv" ).css('display');
	if (openDiv == 'block') {
		$( "#popDialogDiv" ).empty().dialog( "close" );
	}
}

function highlightField()
{
	$("input[type='text'], select, input[type='password'], textarea").focus(function(e){
		$(this).addClass("focusField")
		.blur(function() {
			$(this).removeClass("focusField").addClass("idleField");
		});
	});
}

//end utility functions

//sets up and displays spotlights for index page
function spotLight()
{
	var noCache = Math.random();
	$.ajax({
		url: "start_getRand.php",
		dataType: "text",
		data: {
			noCache: noCache
		},
		success: function (response) {
			data = $.parseJSON( response );//global var to hold results so other functions can access them
			dataLength = 0;//glabal var to hold length of results so other functions can access it
			var a = 1;
			var m = 1;
			var r = 1;
			$.each(data,function(i){
				var test = data[i].utype;
				dataLength++;
				if (test == 0 && a == 1) {
					var div = $(
					'<span>'+data[i].dname+'</span>' +
					'<br>'+
					'<img src="'+data[i].purl+'" width="'+data[i].pw+'" height="'+data[i].ph+'" alt="">'
					);
					$('#aspot').html(div);
					a = 0;
				}
				if (test == 1 && m == 1) {
					var div = $(
					'<span>'+data[i].dname+'</span>' +
					'<br>'+
					'<img src="'+data[i].purl+'" width="'+data[i].pw+'" height="'+data[i].ph+'" alt="">'
					);
					$('#mspot').html(div);
					m = 0;
				}
				if (test == 2 && r == 1) {
					var div = $(
					'<span>'+data[i].dname+'</span>' +
					'<br>'+
					'<img src="'+data[i].purl+'" width="'+data[i].pw+'" height="'+data[i].ph+'" alt="">'
					);
					$('#rspot').html(div);
					r = 0;
				}
			});
			var sp = setInterval('spotRotate()', 3000);//start rotating spotlight
			window.setTimeout(function () {
			    sp = window.clearInterval(sp);//stops rotating spotlight after 1 minute
			}, 60000);//stop rotating after 1 minute
		}
	});
}

function spotRotate()
{
	//get random row from data
	var whichSpot = Math.floor(Math.random()* dataLength)
	//determine which spot to put it in
	var ut = data[whichSpot].utype;
	switch(ut) {
		case '0':
			var spot = $('#aspot');
			break;
		case '1':
			var spot = $('#mspot');
			break;
		case '2':
			var spot = $('#rspot');
			break;
	}
	//update the spot
	var div = $(
	'<span>'+data[whichSpot].dname+'</span>' +
	'<br>'+
	'<img src="'+data[whichSpot].purl+'" width="'+data[whichSpot].pw+'" height="'+data[whichSpot].ph+'" alt="">'
	);

	spot.html(div);
}

//start fpupdate
function fpUpdate()
{
	var ans = $('input[name=ans]:checked').val();
	var nocache = Math.random();
	$.ajax({
		url: "start_fpupdate.php",
		type: "POST",
		dataType: "html",
		data: {
			rowid: ans,
			nocache: nocache
		},
		success: function (res) {
			$('div.fpQuest').html('<span class="goodtext">Answer Recorded.  Thank You!</span>');
			$('#ansDiv').html(res);
		}
	});
}
//end fpupdate

//for terms and privacy links
function termsAndPrivacy(type, lookup)
{
	if (type == 'terms') {
		var title = 'Enchanted Pages - Terms and Conditions';
	} else {
		var title = 'Enchanted Pages - Privacy Policies';
	}
	dialogReset();
	var vpHeight = $(window).height() - 20;
	$( "#dialogDiv" ).empty().dialog({
		autoOpen: true,
		modal: true,
		width: 600,
		height: vpHeight,
		position: ["top"],
		title: title,
		buttons: {
			Close	: function() {
				$( this ).dialog( "close" );
			}
		}
	}).html(loading);

	var nocache = Math.random();
	$.ajax({
		url: "global_policy.php",
		dataType: "json",
		data: {
			type: type,
			lookup: lookup,
			nocache: nocache
		},
		success: function (response) {
			var status = response[0].status;
			var message = response[0].message;
			if (status == 'success') {
				$( "#dialogDiv" ).html(message);
				$('#dialogDiv .tpLink').click(function () {
					var whichLookup = $(this).attr('data-lookup');
					var whichType = $(this).attr('data-type');
					termsAndPrivacy(whichType, whichLookup);
					return false;
				});
			} else {
				$( "#dialogDiv" ).html(message);
			}
		}
	});
	return false;
}
