$(function(){
	$.preloadCssImages(); 

	$('#searchForm a').click(function(){$('#searchForm').submit();return false;});
	$('#searchForm input').keypress(function(e){if(e.which == 13){$('#searchForm').submit();}});
	if ($('#searchForm input').val() != '') {$("#searchForm input").focus();}

	if (page == 'home') {
		$("#packages a").each(function() {
			var packageID = this.id.replace(/package/,'');
			if (isNaN(packageID) == false) {
				$('#package'+packageID).hover(function() {
				  $('#packButton'+packageID).css("background-position", "0 -40px");
				}, function() {
				  $('#packButton'+packageID).css("background-position", "0 0");
				});
			}		});
	} else if (page == 'login') {
		$('#loginForm').jqTransform({imgPath:'jqtransformplugin/img/'});
		$('#loginForm input').keypress(function(e){if(e.which == 13){$('#loginButton').trigger('click');return false;}});

		var incomingErrorMsg = $.url.param("error");
		if (incomingErrorMsg != '') {
		    $('body').showMessage({thisMessage:[incomingErrorMsg], className:'fail', 'displayNavigation':false});
		}
		
		$('#loginButton').mouseover(function(){
			$('#loginButton').css("background-position", "0 -40px");
		}).mouseleave(function(){
			$('#loginButton').css("background-position", "0 0");
		});
		
		$('#registerButton').mouseover(function(){
			$('#registerButton').css("background-position", "0 -120px");
		}).mouseleave(function(){
			$('#registerButton').css("background-position", "0 -80px");
		}).click(function(){
		    window.location = URL + 'register.html';
		});

		
		$('#loginButton').click(function() {
			var formData = $('#loginform').serializeArray();

			var errorMessage=[], elFocus;

			if ( $('#username').val() === '' ) {
				errorMessage.push("Please enter a username");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#username');
				}
			}

			if ( $('#password').val() === '' ) {
				errorMessage.push("Please enter a password");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#password');
				}
			}

			if ( errorMessage.length > 0 ) {
				$('body').showMessage({thisMessage:errorMessage, className:'fail', 'displayNavigation':false});
				elFocus.focus();
			} else {
				document.login.submit();
			}
			return false;
		});
	} else if (page == 'controlPanel') {
	
		oTable = $('#pressReleases').dataTable({
			"bJQueryUI": true,
			"sPaginationType": "full_numbers",
        "bAutoWidth": false,
        "aoColumns" : [
            { sWidth: '305px' },
            { sWidth: '100px' },
            { sWidth: '72px' },
            { sWidth: '65px' },
            { sWidth: '47px' }
        ]  
		});
	
		$.easing.bouncy = function (x, t, b, c, d) {
			var s = 1.70158;
			if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
			return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
		}
		$.tools.tooltip.addEffect("bouncy",
			function(done) {
				this.getTip().animate({top: '+=10'}, 500, 'bouncy', done).show();
			},
			function(done) {
				this.getTip().animate({top: '-=10'}, 500, 'bouncy', function()  {
					$(this).hide();
					done.call();
				});
			}
		);
		$(".icons").each(function() {
			$(this).tooltip({effect: 'bouncy', 
							 tip: '#' + $(this).attr('id') + '_tip', 
							 offset: [10, 2],
							 effect: 'slide'}).dynamic({ bottom: { direction: 'down', bounce: true } });
		});
		
		$('#icon_1').click(function(){
				$.blockUI({ message: '<h1 id="loadMsg" style="margin-top: 15px;">Choose your package<br><input type="button" value="Package One (Free)" id="pack1"/><input type="button" value="Package Two (Free)" id="pack2"/><input type="button" value="Package Three (\u00A330)" id="pack3"/></h1>', css: { 
					cursor:'default',
					border: 'none', 
					padding: '15px', 
					backgroundColor: '#000', 
					'-webkit-border-radius': '10px', 
					'-moz-border-radius': '10px', 
					opacity: 1, 
					color: '#fff' 
				},overlayCSS: { backgroundColor: '#000',opacity:0.2,cursor:'default' } }); 	
				
				$('#pack1').click(function(){window.location= URL  + 'control-panel/add-press-release.html';});
				$('#pack2').click(function(){window.location= URL  + 'control-panel/add-press-release.html?package=2';});
				$('#pack3').click(function(){window.location= URL  + 'control-panel/add-press-release.html?package=3';});
				
				return false;
		});

	} else if (page == 'pressrelease') {
		$(".sourcetitle").tooltip({position: 'bottom center',effect: 'slide'}).dynamic({ bottom: { direction: 'down', bounce: true } });
	} else if (page == 'register') {
		var alreadyClicked = false;

		$('#registerForm').jqTransform({imgPath:'jqtransformplugin/img/'});
		$('#registerForm input').keypress(function(e){if(e.which == 13){$('#registerButton').trigger('click');return false;}});
		
		$('#registerButton').mouseover(function(){
			$('#registerButton').css("background-position", "0 -120px");
		}).mouseleave(function(){
			$('#registerButton').css("background-position", "0 -80px");
		});

		if ($.url.param("source") == 'register') {
			$('body').showMessage({thisMessage:['Please fill out the form below to register and begin submitting press releases'], className:'success', 'displayNavigation':false});
		}
		
		if ($.url.param("source") == 'try') {
			$('body').showMessage({thisMessage:['Please fill out the form below to register and try out our FREE submission package'], className:'success', 'displayNavigation':false});
		}
		
		$('#registerButton').click(function() {

		var emailFilter=/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		var formData = $('#registerForm').serializeArray();

		var errorMessage=[], elFocus;
		
		if ( $('input[name=username]').val() === '' ) {
			errorMessage.push("Please enter a username");
			if (typeof(elFocus) == 'undefined') {
				elFocus=$('input[name=username]');
			}
		}

		if ( $('input[name=email]').val() !== '' && !emailFilter.test($('input[name=email]').val()) ) {
			errorMessage.push("Please enter a valid email address");
			if (typeof(elFocus) == 'undefined') {
				elFocus=$('input[name=email]');
			}
		}

		if ( $('input[name=email]').val() === '' ) {
			errorMessage.push("Please enter an email address");
			if (typeof(elFocus) == 'undefined') {
				elFocus=$('input[name=email]');
			}
		}

		if ( $('#password').val() === '' ) {
			errorMessage.push("Please enter a password");
			if (typeof(elFocus) == 'undefined') {
				elFocus=$('#password');
			}
		}

		if ( errorMessage.length > 0 ) {
			$('body').showMessage({thisMessage:errorMessage, className:'fail', 'displayNavigation':false});
			elFocus.focus();
		} else {
			if (alreadyClicked == true) {
				errorMessage.push("You have already registered, please check your email");
				$('body').showMessage({thisMessage:errorMessage, className:'success', 'autoClose':false,'displayNavigation':true});
			} else {
				$.ajax({
						type: "GET",
						url: "/createaccount",
						data: formData,
						dataType: "xml",
						success: function(xml) {
							$(xml).find('response').each(function(){
								var error = $(this).find('error').text();
								var returnMessage = $(this).find('returnMessage').text();

								if (error == "false") {
									errorMessage.push(returnMessage);
									$('body').showMessage({thisMessage:errorMessage, className:'success', 'autoClose':false,'displayNavigation':true});
									alreadyClicked = true;
								} else {
									errorMessage.push(returnMessage);
									$('body').showMessage({thisMessage:errorMessage, className:'fail', 'displayNavigation':false});
								}
							});
						}
					});
			}
		}
		return false;
		});
	} else if (page == 'editPersonal') {
		$('#editDetailsForm').jqTransform({imgPath:'jqtransformplugin/img/'});
		
		var incomingMsg = $.url.param("fill");
		if (incomingMsg != '') {
		    $('body').showMessage({thisMessage:['Please complete this form to continue adding your press releases'], className:'success', 'displayNavigation':false});
		}
		
		$('.save-settings').click(function() {

			var errorMessage=[], elFocus;
			
			if ( $('#companyName').val() === '' ) {
				errorMessage.push("Please enter your company name");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#companyName');
				}
			}
			
			if ( $('#companyWebsite').val() === '' ) {
				errorMessage.push("Please enter the website of your company");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#companyWebsite');
				}
			}
			
			if ( $('#companyPhone').val() === '' ) {
				errorMessage.push("Please enter a telephone number");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#companyPhone');
				}
			}
			
			if ( $('#companyStreet').val() === '' ) {
				errorMessage.push("Please enter your company's street address");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#companyStreet');
				}
			}
			
			if ( $('#companyCity').val() === '' ) {
				errorMessage.push("Please enter your company's city");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#companyCity');
				}
			}
			
			if ( $('#companyPostalCode').val() === '' ) {
				errorMessage.push("Please enter your company's postal / zip code");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#companyPostalCode');
				}
			}
			
			if ( $('#companyState').val() === '' ) {
				errorMessage.push("Please enter your company's state or county");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#companyState');
				}
			}
			
			if ( $('#companyCountry').val() === '' ) {
				errorMessage.push("Please select a country");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#companyCountry');
				}
			}


			if ( errorMessage.length > 0 ) {
				$('body').showMessage({thisMessage:errorMessage, className:'fail', 'displayNavigation':false});
				elFocus.focus();
				return false;
			} else {
				document.companySettings.submit();
				return true;
			}
		});
	} else if (page == 'addPressRelease') {
	
		$('#pressReleaseForm').jqTransform({imgPath:'jqtransformplugin/img/'});
		$('#anchorTextBlock').hide();
	
		$('#summary').tinymce({
			editor_selector : "mceSimple",
			script_url : '/assets/templates/activehigh/javascript/tiny_mce/tiny_mce.js',
			theme : "simple",
			height: "1"
		});
		
		$('#newsBody').tinymce({
			editor_selector : "mceSimple",
			script_url : '/assets/templates/activehigh/javascript/tiny_mce/tiny_mce.js',
			theme : "simple"
		});
	
		var incomingMsg = $.url.param("error");
		if (incomingMsg != '') {
		   $('body').showMessage({thisMessage:[incomingMsg], className:'fail', 'displayNavigation':false});
		}
	
		var pressPackage = $(this).find('input[name=package]').val();
	
		$('#anchorTextHeader').click(function(){
		    if (pressPackage == 1) {
			    alert("Anchortext links are not available with our Free service, please try package 2");
			} else {
				$('#anchorTextBlock').slideDown(400,function(){$('#anchorTextHeader').css("background-image", "none").css("cursor","default")});
			}
		});
		
		$('#imagesHeader').click(function(){
		    if (pressPackage != 3) {
			    alert("Images are only available with package 3");
			} else {
				$('#imagesBlock').slideDown(400,function(){$('#imagesHeader').css("background-image", "none").css("cursor","default")});
			}
		});
		
		$('#videoHeader').click(function(){
		    if (pressPackage != 3) {
			    alert("Videos are only available with package 3");
			} else {
				$('#videoBlock').slideDown(400,function(){$('#videoHeader').css("background-image", "none").css("cursor","default")});
			}
		});
	
		$('.save-settings').click(function() {
			var errorMessage = [];
		
			if ( $('#title').val() === '' ) {
				errorMessage.push("Please enter a title");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#title');
				}
			}
			
			if ( $('#summary').val() === '' ) {
				errorMessage.push("Please enter a summary for your press release");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#summary');
				}
			}
			
			if ( $('#newsBody').val() === '' ) {
				errorMessage.push("Please enter your press release into the news body box");
				if (typeof(elFocus) == 'undefined') {
					elFocus = $('#newsBody');
				}
			}
		
			if ( errorMessage.length > 0 ) {
				$('body').showMessage({thisMessage:errorMessage, className:'fail', 'displayNavigation':false});
				elFocus.focus();
				return false;
			} else {
			
			if (pressPackage == 1) {
			
				$.blockUI({ message: '<img id="loadImg" src="/assets/templates/activehigh/images/ajax-loader.gif" style="float:left;"/><h1 id="loadMsg" style="margin-top: 15px;">Scanning for plagiarism...</h1><input type="button" value="Rewrite and make unique" id="rewriteButton" style="display:none"><input type="button" value="Upgrade to Package Two" id="upgradeButton" style="display:none">', css: { 
					cursor:'default',
					border: 'none', 
					padding: '15px', 
					backgroundColor: '#000', 
					'-webkit-border-radius': '10px', 
					'-moz-border-radius': '10px', 
					opacity: 1, 
					color: '#fff' 
				},overlayCSS: { backgroundColor: '#000',opacity:0.2,cursor:'default' } }); 	
			   
			   var pressReleaseData = $('#newsBody').val();
			   
				$.ajax({
				   type: "POST",
				   url: "plagiarism.php",
				   data: ({news : pressReleaseData}),
				   success: function(msg){
				       if (msg == 0) {
							$('#loadMsg').html('Unfortunately, your content is not unique and<br>cannot be published via our free service<br/>');
							$('#loadMsg').css({'margin-top' : '15px', 'font-size' : '15px'});
							$('#loadImg').hide();
							$('#upgradeButton').show();
							$('#rewriteButton').show();
							
							$('#upgradeButton').click(function(){
								$.unblockUI({fadeOut: 0});
							
								$('#loadMsg').html('Scanning for plagiarism...<br/>');
								$('#loadMsg').css({'margin-top' : '15px', 'font-size' : '32px'});
								$('#upgradeButton').hide();
								$('#rewriteButton').hide();
								$('#loadImg').show();
								
								$('input[name=package]').val('2');
								pressPackage = 2;
								
								document.companySettings.submit();
								return false;
							});
							
							$('#rewriteButton').click(function(){
								$.unblockUI({fadeOut: 0});
							
								$('#loadMsg').html('Scanning for plagiarism...<br/>');
								$('#loadMsg').css({'margin-top' : '15px', 'font-size' : '32px'});
								$('#upgradeButton').hide();
								$('#rewriteButton').hide();
								$('#loadImg').show();
								
								return false;
							});
							

							return false;
					   } else {
							$('#loadMsg').html('Your content is unique, thank you...');
							$('#loadImg').hide();
							setTimeout(function(){document.companySettings.submit();return true;}, 1000); 
					        
							return true;
					   }
				   }
				 });
			} else {
				document.companySettings.submit();
				return true;
			}
			}
		});
	}
});
