//Initiating jQuery to work with Prototype;
//var $ = jQuery.noConflict(); located inside jquery-1.2.3.min.js file

$(document).ready(function() { onDocumentLoad(); });
$(window).load(function() { onWindowLoad(); });

//Global Variables

/*
 * Standard page loading functions for prototype / jQuery
 */
function onDocumentLoad(){
	$('#footerMenu ul').children('li').not(':last').append('<li>|</li>');

	$("#twitterWrap").appendTo("a[title=Twitter]");

	var twitHeight = $('#twitterWrap').height()+20;

	$('#twitterWrap').css('margin-top','-'+twitHeight+'px');

	$("a[title=Twitter]").hover(function(){
		$("#twitterWrap").show()
	},function(){
		$("#twitterWrap").hide();
	});
}

//Stuff put into this function doesnt run until the entire document is loaded flash and all
function onWindowLoad(){

	if ($.browser.msie && $.browser.version < 7) {
		intHeight = 350;
	} else {
		intHeight = 340;
	}

	$('.external').attr('target','_blank');

	windowWidth = $(window).width();
	windowHeight = $(window).height();

	intContactWidth = Math.floor(windowWidth / 2);
	intContactHeight = Math.min(Math.floor(windowHeight - 80), intHeight);

	intContactLeft = Math.floor((intContactWidth / 3)*-1);
	intContactTop = Math.floor((intContactHeight / 2)*-1);
	
	$('DIV#headerContentLeft').click(function() { window.location = "http://www.lycosidea.com/"; });

	$('.external').click(function(e){
		e.preventDefault();
		window.open(this.href);
	});

	$('.contact, .contract').click(function(e){
		e.preventDefault();

		windowWidth = $(window).width();
		windowHeight = $(window).height();

		intContactWidth = Math.floor(windowWidth / 2);
		intContactHeight = Math.floor(windowHeight - 80);
		intContactHeight = Math.min(Math.floor(windowHeight - 80), intHeight);

		intContactLeft = Math.floor((intContactWidth / 2)*-1);
		intContactTop = Math.floor((intContactHeight / 2)*-1);

		if($(this).hasClass('contract')){
			$('#subject').val('Contract request');
		}

		inputArray = {
			name:"Full Name",
			email:"email@email.com",
			vericode:"insert code above",
			subject:$('#subject').val()
		};

		$('#contactForm').modal({
			overlayId: ('contactOverlay'),
			containerId: ('contactContainer'),
			onOpen: contactForm.open,
			onShow: contactForm.show
			//onclose doesnt work with the dual modal windows the closing is called else where
		});

		$("input").each(function(){
			var id = $(this).attr("id");
			if($(this).val()==inputArray[id]){
				$(this).css("color","#999999");
			}
			if(!$(this).val()){
				$(this).css("color","#999999").val(inputArray[id]);
			}
		});

		$("input").focus(function(e){
			var id = $(this).attr("id");
			if($(this).val()==inputArray[id]){
				$(this).animate({ color: "#FFFFFF" }, "slow", function(e){
					$(this).css('color','#000000').val('');
				});
			}
		}).blur(function(e){
			var id = $(this).attr("id");
			if(!$(this).val()||$(this).val()==inputArray[id]){
				$(this).css("color","#999999").val(inputArray[id]);
			}
		});

		$("input[name='reset']").click(function(e){
			$("input:not(:submit,:button,:hidden)").each(function(){
				$(this).val("");
				$(this).trigger('blur');
			});

			$("#comments").val("");

			if ($('#contactContainer .contactMessage:visible').length > 0) {
				var msg = $('#contactContainer .contactMessage div');
				msg.fadeOut(400, function () {
					msg.empty();
					$('#contactContainer .contactMessage').fadeOut(200);
					$('#contactContainer').animate({
						height: intContactHeight
					});
				});
			}

			$('#subject').val(inputArray["subject"]);

		});

		$("#reloadCaptcha").click(function(){
			$('#contactForm').children('form').find('img').replaceWith('<img style="border: 1px solid ;" alt="verification code" src="/manager/includes/veriword.php?rand='+Math.random()+'"/>');
		});
	});

	var contactForm = {
		message: null,
		open: function(dialog){
			$('#contactContainer').css({'width': 400, 'height': 100, 'margin-left': -200, 'margin-top': intContactTop});
			
			if($("iframe").css('display')){
				var currentID = $(".cfMiddle").attr('id').replace("image","");
				var currentDoc = $(coverFlowItems).get(currentID);
				var loc;
				
				siteURL = currentDoc.weburl+"/assets/plugins/lycosideaPortal/clientJS/"+clientIP+".js";
				$.ajax({
					type: "GET",
					dataType: "script",
					url: siteURL,
					success: function(){
						loc = (typeof(loc) == 'undefined')?$("#viewWindowFront").attr("src"):loc;
					}
				});
			}

			title = $('#contactContainer .contactTitle').html();
			$('#contactContainer .contactTitle').html('Loading...');
			dialog.overlay.fadeIn(1000, function () {
				dialog.container.fadeIn(1000, function () {
					dialog.data.fadeIn(500, function () {
						$('#contactContainer').animate({
							height: intContactHeight
						}, function () {
							$("#reloadCaptcha").trigger('click');
							title = ($('#subject').val()==="Support request")?"Support Form":title;
							inputArray['subject'] = $('#subject').val();
							$('#contactContainer .contactTitle').fadeOut(200,function(){
								$(this).html(title).fadeIn(200);
							});
							$('#contactContainer form').fadeIn(1000);
							$('#vericode').val(inputArray['vericode']);
							$("#contactContainer .modalCloseImg").unbind().click(function(){
								contactForm.close(dialog);
							});
						});
					});
				});
			});

			$("input[name='close']").click(function(){
				contactForm.close(dialog);
			});			

		},
		show: function (dialog) {
			$("#contactContainer input[name='submit']").click(function (e) {
				e.preventDefault();
		
				var getContactContainerPreHeight = $('#contactContainer').height();
				$("input[name='topic']").val($('#subject')[0].selectedIndex+1);
		
				// validate form
				if (contactForm.validate(dialog)) {
					$('#contactContainer .contactMessage').fadeOut(function () {
						$('#contactContainer .contactMessage').removeClass('contactError').empty();
					});
					$('#contactContainer .contactTitle').html('Sending...');
					$('#contactContainer form').fadeOut(200);
					$('#contactContainer').animate({
						height: '200px'
					}, function () {
						$('#contactContainer .contactLoading').fadeIn(200, function () {
							loc = (typeof(loc) == 'undefined')?"":loc;
							$.ajax({
								url: $('#contactContainer form').attr("action"),
								data: $('#contactContainer form').serialize() + '&action=send&currentLoc='+loc+'&currentIP='+clientIP,
								type: 'post',
								cache: false,
								dataType: 'html',
								complete: function (xhr) {
									$('#contactContainer .contactLoading').fadeOut(200, function () {
										var contactMessage = ($(xhr.responseText).children('p').length > 0)?$(xhr.responseText).children('p').parents("#contactForm").html():$(xhr.responseText).children('.contactMessage').html();
										var veriCode = $(xhr.responseText).children('form').find('img');
		
										if(contactMessage.indexOf("errors")!=-1){
											$('#contactContainer').animate({
												height: getContactContainerPreHeight
											}, function(){
												$('#contactContainer .contactTitle').html(title);
												$('#contactForm').children('form').find('img').replaceWith(veriCode)
												$('#contactContainer form').fadeIn(200);
												contactForm.message = contactMessage;
												contactForm.createError();
											});
										} else {
											$('#contactContainer .contactTitle').html('Thank you!');
											$("#contactContainer .contactMessage").html(contactMessage).fadeIn(200);
										}

										$(".contactClose").click(function(){
											contactForm.close(dialog);
										})
									});
								},
								error: contactForm.error
							});
						});
					});
				} else {
					contactForm.createError();
				}
			});
		},
		close: function(dialog){
			$('#contactContainer .contactMessage').fadeOut();
			$('#contactContainer .contactTitle').html('Closing...');
			$('#contactContainer form').fadeOut(500);
			$('#contactContainer').animate({
				height: 100
			}, function () {
				dialog.container.fadeOut(500, function () {
					dialog.overlay.fadeOut(500, function () {
						$.modal.close();
					});
				});
			});
		},
		validate: function(dialog){
			contactForm.message = '';
			$('#contactContainer form input').each(function(){
				inputObj = $(this);
				inputObjName = inputObj.attr('name');
				if(!inputObj.val() || inputObj.val()===inputArray[inputObjName]){
					contactForm.message = (contactForm.message.length > 0)?contactForm.message:'The following fields are required:<br />';
					inputObjName = inputObjName.charAt(0).toUpperCase() + inputObjName.slice(1);
					contactForm.message += inputObjName+' is required. ';
				}
			});

			if (contactForm.message.length > 0) {
				return false;
			} else {
				return true;
			}
		},
		error: function (xhr) {
			alert(xhr.statusText);
		},
		createError: function() {
			if ($('#contactContainer .contactMessage:visible').length > 0) {
				var msg = $('#contactContainer .contactMessage div');
				msg.fadeOut(400, function () {
					msg.empty();
					contactForm.showError();
					msg.fadeIn(400);
				});
			} else {
				setHeight = ($(contactForm.message).html().length>150)?40:30;
				$('#contactContainer .contactMessage').animate({
					height: setHeight
				}, contactForm.showError);
			}
		},
		showError: function () {
			$('#vericode').val('');
			$('#contactContainer .contactMessage').html($('<div class="contactError">').append(contactForm.message)).fadeIn(400,function(){
				$('#contactContainer').animate({
					height: intContactHeight+setHeight
				});
			});
		}
	}
}
