/**
 * @name	HTTPMon
 * @version	1.0b
 * @author	marc
 */

/* AddThis custom configuration */

var addthis_config = {
     ui_cobrand: "HTTPMon"
}

/* Add new function to retreive URL parameters */

$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return $.getUrlVars()[name];
  }
});

/* Variables */

var regExpPatternMonitorUrl = /\/monitor\/(.+)/;

/* DOCUMENT READY */

$(document).ready(function(){

	/* Nifty Cube - rounded div boxes */
	Nifty("div#header","big");
	Nifty("div#menu_container","big");
	Nifty("ul#nav a","small transparent");
	Nifty("div#monitor_input","big");
	Nifty("ul#monitor_container a","small transparent");
	Nifty("div#websites_counter","big");
	Nifty("div#footer","big");
	Nifty("div#report_title","big");

	/* ColorBox */
	$('.colorboxts').live('click', function() {
		$.fn.colorbox({href:$(this).attr('href'), title:$(this).attr('title'), open:true, opacity: 0.7});
		return false;
	});

	/* Add title in input box */
	function switchText()
	{
		if ($(this).val() == $(this).attr('title'))
			$(this).val('').removeClass('exampleText');
		else if ($.trim($(this).val()) == '')
			$(this).addClass('exampleText').val($(this).attr('title'));
	}
	
	$('input[type=text][title!=""]').each(function() {
		if ($.trim($(this).val()) == '') $(this).val($(this).attr('title'));
		if ($(this).val() == $(this).attr('title')) $(this).addClass('exampleText');
	}).focus(switchText).blur(switchText);
	
	$('form').submit(function() {
		$(this).find('input[type=text][title!=""]').each(function() {
			if ($(this).val() == $(this).attr('title')) $(this).val('');
		});
	});

	/* When selecting a tab delete it's content first */
	$('#tabs').bind( 'tabsselect', function( event, ui )
	{
		$(ui.panel).text('');
	});

	/* Sign up form validation (uses live because the form content gets loaded via AJAX load) */

	$("#signup").live('focus', function(){
		$(this).validate({
			rules: {
				firstname: {
					required: true,
		      	},
		      	lastname: {
		        	required: true,
		      	},
		      	email: {
		        	required: true,
			        email: true
			    },
				website: {
				  	required: true,
				  	minlength: 10,
			  	},
		      	password: {
		        	minlength: 8,
		        	required: true
		      	},
		     	passconf: {
		        	equalTo: "#password"
		      	}
		    },
			messages: { 
				website: {
					required: "Enter a website to be monitored.",
				},
				firstname: "Enter your firstname.", 
	            lastname: "Enter your lastname.", 
				password: { 
					required: "Provide a password.", 
					rangelength: jQuery.format("Enter at least {0} characters") 
				}, 
				passconf: { 
					required: "Repeat your password.", 
					minlength: jQuery.format("Enter at least {0} characters."), 
					equalTo: "Enter the same password as above." 
				}, 
				email: { 
				    required: "Please enter a valid email address.", 
				    minlength: "Please enter a valid email address.", 
				}
	        }, 
		    success: function(label) {
				label.text('OK!').addClass('valid');
				/* Stop the live of website input field */
				$('#website').die('focus');
				/* Put title back in website input field */
				$('.it_website_name').val($('.it_website_name').attr('title')).addClass('exampleText');
		    }
		});
	});

	/* Hijax the menu */

	$('#nav a').click( function( e )
	{
		/* First get rid of the old content (home/about) to avoid flashing effect */
		$('#static_content').text('');
		/* Change page title */
		document.title = $(this).attr('title') + ' | HTTPMon';
		/* Hide jQuery UI tabs if present */
		if( ! $('#nav li').hasClass('activelink') )
			$('#tabs').tabs().hide();
		/* Load content */
		var _url = $(this).attr('href');
		$('#static_content').load('/?page=' + _url + '&f=a');
		/* Show content */
		$('#static_content').show();
		/* Prevent loading the HTML page */
		e.preventDefault();	
//		var x = document.getElementsByTagName("title").item(0);
//		alert( x.firstChild.nodeValue );
	});

	/* Menu highlighting and showing content */

	$('#about').click(function() {
		$('#content h2').text('');
		$('#static_content div').hide();
		$('.it_website_name').val($('.it_website_name').attr('title')).addClass('exampleText');
		$('.activelink').removeClass('activelink');
		$(this).addClass('activelink');
	});

	$('#news').click(function() {
		$('#content h2').text('');
//		$('#static_content div').hide();
		$('.it_website_name').val($('.it_website_name').attr('title')).addClass('exampleText');
		$('.activelink').removeClass('activelink');
		$(this).addClass('activelink');
	});

	$('#stats').click(function() {
		$('#content h2').text('');
//		$('#static_content div').hide();
		$('.it_website_name').val($('.it_website_name').attr('title')).addClass('exampleText');
		$('.activelink').removeClass('activelink');
		$(this).addClass('activelink');
	});

	$('#faq').click(function() {
		$('#content h2').text('');
//		$('#static_content div').hide();
		$('.it_website_name').val($('.it_website_name').attr('title')).addClass('exampleText');
		$('.activelink').removeClass('activelink');
		$(this).addClass('activelink');
	});

	$('#contact').click(function() {
		$('#content h2').text('');
//		$('#static_content div').hide();
		$('#static_content div div').show();
		$('.it_website_name').val($('.it_website_name').attr('title')).addClass('exampleText');
		$('.activelink').removeClass('activelink');
		$(this).addClass('activelink');
	});

	/* Hijax the footer */

	$('#footer_sec a').click( function( e )
	{
		/* First get rid of the old content (home/about) to avoid flashing effect */
		$('#static_content').text('');
		/* Change page title */
		document.title = $(this).attr('title') + ' | HTTPMon';
		/* Hide jQuery UI tabs if present */
		if( ! $('#nav li').hasClass('activelink') )
			$('#tabs').tabs().hide();
		/* Load content */
		var _url = $(this).attr('href');
		$('#static_content').load('/?page=' + _url + '&f=a');
		/* Show content */
		$('#static_content').show();
		/* Remove the title from the monitor ui tab */
		$('#content h2').text('');
		/* Put back example text in monitor input */
		$('.it_website_name').val($('.it_website_name').attr('title')).addClass('exampleText');
		/* Remove menu highlight */
		$('.activelink').removeClass('activelink');
		/* Prevent loading the HTML page */
		e.preventDefault();	
	});
	
	/* Sign up form submit process */

	$('#signup :submit').live('click', function(event) {

		var _form_data = $('#signup').serialize();
		_form_data += '&v=' + $('#signup').valid();
	
		/* Post signup form data to API */
		$.ajax({
			type:	'POST',
			url:	'/api.php?swid=sup',
			data:	_form_data,
			async:	true,
			beforeSend: function() {
				if ($('#signup').valid()) {
					$.blockUI({
						css: {
							border: 'none',
							padding: '15px',
							backgroundColor: '#000',
							'-webkit-border-radius': '10px',
							'-moz-border-radius': '10px',
							opacity: .5,
							color: '#fff'
						}
					});
				}
			},
			complete: function() {
//				if ($('#signup').valid())
//				{
					$.unblockUI();
//				}
			}, 
			success: function( data ) {
				if ($('#signup').valid())
				{
					/* Reset validator and form */
					var validator = $("#signup").validate();
					validator.resetForm();
					$('#signup')[ 0 ].reset();
					/* TODO: warn of good complention depending on output of api.php */
					if( data )
						$('label.formfeedback').html('<img src="images/valid.png"> Sign up successful, your website will soon be monitored by HTTPMon!').delay(6000).fadeOut('slow');
				}
			}
		});
		/* Might need to be disabled */
		event.preventDefault();
	});

	/* Monitor for enter key */
	$('.it_website_name').keypress(function(event) {
		if( event.keyCode == '13' ) {
			var _websiteName = $('input[name=website_name]').val().toLowerCase();  

			/* Check for a minimum of characters in website input */
			if( _websiteName.length < 5 )
				return false;
			
			var _websiteFound = 0;
			/* Check if website exists */
			$.ajax({
				type:	'GET',
				url:	'/api.php',
				data:	{ swid: 'wse', ws: _websiteName },
				async:	false,
				success: function( data ) {
					if (data) {
						_websiteFound = 1;
						_websiteName = data;
					}
				}
			});
	
			if( _websiteFound == 0 )
			{
				$('#no_website_dialog').dialog('open');			
				return false;		
			}

			/* Remove the menu item highlighted when another menu item has been clicked */
			$('.activelink').removeClass('activelink');

			/* Hide all static content */
			$('#static_content').hide();

			/* Modify the HTML title of the page to include the website name */
			document.title = 'Website Monitoring Report for ' +  _websiteName + ' | HTTPMon';

			/* Add the website name as h2 title */
			$('#content h2').text( 'Website: ' + _websiteName );

			var tabs = $("#tabs").tabs( {
				selected: '-1',
				fx: {
					opacity: 'toggle',
					duration: 'fast'
				},
				spinner: '<img src="/images/ajax-loader-small.gif" border="0" /> <i>Loading...</i>'
			} );

			/* Add the ws URL parameter to each tab URL */
			$('#tabs a').each(function(i) {
				var _oldHref = $.data(this, 'href.tabs');
				var _selectedTab = tabs.tabs("option", "selected");
//				console.log(i + ' ' + i + ' ' + _oldHref + ' ' + _selectedTab);
				tabs.tabs('url', i, _oldHref + '&ws=' + _websiteName);
			});

			/* Select and load the first tab */
			$( '#tabs' ).tabs( "option", "selected", 0 );
			$( '#tabs' ).tabs( "load", 0 );

			tabs.show();
			event.preventDefault();
		}
	});

	/* Monitor button was pressed */
	$('#monitor_button').click(function(e) {
		var _websiteName = $('input[name=website_name]').val().toLowerCase();

		/* Check for a minimum of characters in website input */
		if( _websiteName.length < 5 )
			return false;

		/* Check if nothing has been entered in the website input field */
		if( _websiteName == 'enter website here' )
			return false;

		var _websiteFound = 0;
		/* Check if website exists */
		$.ajax({
			type:	'GET',
			url:	'/api.php',
			data:	{ swid: 'wse', ws: _websiteName },
			async:	false,
			success: function( data ) {
				if (data) {
					_websiteFound = 1;
					_websiteName = data;
				}
			}
		});

		if( _websiteFound == 0 )
		{
			$('#no_website_dialog').dialog('open');			
			return false;		
		}

		/* Remove the menu item highlighted when another menu item has been clicked */
		$('.activelink').removeClass('activelink');

		/* Hide all static content */
		$('#static_content').hide();

		/* Modify the HTML title of the page to include the website name */
		document.title = 'Website Monitoring Report for ' +  _websiteName + ' | HTTPMon';

		/* Add the website name as h2 title */
		$('#content h2').text( 'Website: ' + _websiteName );

		var tabs = $("#tabs").tabs( {
			selected: '-1',
			fx: {
				opacity: 'toggle',
				duration: 'fast'
			},
			spinner: '<img src="/images/ajax-loader-small.gif" border="0" /> <i>Loading...</i>'
		} );

		/* Add the ws URL parameter to each tab URL  */
		$('#tabs a').each(function(i) {
			var _oldHref = $.data(this, 'href.tabs');
			var _selectedTab = tabs.tabs("option", "selected");
//			console.log(i + ' ' + i + ' ' + _oldHref + ' ' + _selectedTab);
			tabs.tabs('url', i, _oldHref + '&ws=' + _websiteName);
			/* Reload the current tab */
//			if( _selectedTab == i )
//				tabs.tabs( 'load', _selectedTab );
		});

		/* Select and load the first tab */
		$( '#tabs' ).tabs( "option", "selected", 0 );
		$( '#tabs' ).tabs( "load", 0 );

		tabs.show();
		e.preventDefault();	
	});

	/* Hide the tabs */
//	alert('test');
//	$('#tabs').tabs().hide();

	/* Default page to show on entering website */
	$('li#about').addClass('activelink');

	/* Display static content */
	$('#static_content').show();

	/* Only show the default page if no other page has been requested */
//	if( window.location.pathname == '/' )
//		$('#static_content').load('/?page=web-monitoring-about&f=a');

	/* Dialog for no website found */
	$('#no_website_dialog').dialog({
		autoOpen: false,
		closeOnEscape: false,
		resizable: false,
		modal: true,
		draggable: false,
		width: 400,
		height: 200,
		buttons: {
			'Cancel': function()
			{
				$(this).dialog('close');
				/* If we access a website directly from the URL we have to load some content if website doesn't exist */
				var path = window.location.pathname;
				var match = path.match(regExpPatternMonitorUrl);
				if (match) 
					$('#static_content').load('/?page=web-monitoring-about&f=a');
			},
			'Sign Up Now': function()
			{
				$(this).dialog('close');
				/* Hide tabs */
				$('#tabs').tabs().hide();
				$('#content h2').text('');
				/* Highlight menu button */
				$('.activelink').removeClass('activelink');
				$('li#contact').addClass('activelink');
				/* Load the static contact for the signup form */
				$('#static_content').load('/?page=web-monitoring-signup&f=a');
				$('#static_content').show();
				/* Put the website name from monitor input into the signup form */
				$('#website').live('focus', function(event) {
					$(this).val($('.it_website_name').val());
				});
			}
		}	
	});

	/* Getting URL var by its name either as directory or parameter */

	var path = window.location.pathname;
	var match = path.match(regExpPatternMonitorUrl);
	if (match) 
		var byName = match[1].toLowerCase();
	else {
		if ($.getUrlVar('ws')) 
			var byName = $.getUrlVar('ws').toLowerCase();
	}

	/* Enter website monitor page through URL ?ws=websiteURL or /monitor/websiteURL */
	if( byName ) {
		var _websiteName = byName;  
		var _websiteFound = 0;
		/* Check if website exists */
		$.ajax({
			type:	'GET',
			url:	'/api.php',
			data:	{ swid: 'wse', ws: _websiteName },
			async:	false,
			success: function( data ) {
				if (data) {
					_websiteFound = 1;
					_websiteName = data;
				}
			}
		});

		if( _websiteFound == 0 )
		{
			$('#no_website_dialog').dialog('open');			
			return false;
		}

		/* Remove the menu item highlighted when another menu item has been clicked */
		$('.activelink').removeClass('activelink');

		/* Hide all static content */
		$('#static_content').hide();

		/* Modify the HTML title of the page to include the website name */
		document.title = 'Website Monitoring Report for ' +  _websiteName + ' | HTTPMon';

        /* Remove exampleText class and set the input box to the website name gotten from the URL */
        $('.it_website_name').val($('.it_website_name').attr('title')).removeClass('exampleText');
        $('input[type=text][name="website_name"]').val( byName );

		/* Add the website name as h2 title */
		$('#content h2').text( 'Website: ' + _websiteName );

		var tabs = $("#tabs").tabs( {
			selected: -1,
			fx: {
				opacity: 'toggle',
				duration: 'fast'
			},
			spinner: '<img src="/images/ajax-loader-small.gif" border="0" /> <i>Loading...</i>'
		} );

		/* Add the ws URL parameter to each tab URL  */
		$('#tabs a').each(function(i) {
			var _oldHref = $.data(this, 'href.tabs');
			var _selectedTab = tabs.tabs("option", "selected");
//			console.log(i + ' ' + i + ' ' + _oldHref + ' ' + _selectedTab);
			tabs.tabs('url', i, _oldHref + '&ws=' + _websiteName);
			/* Reload the current tab */
//			if( _selectedTab == i )
//				tabs.tabs( 'load', _selectedTab );
		});

		/* Select and load the first tab */
		$( '#tabs' ).tabs( "option", "selected", 0 );
		$( '#tabs' ).tabs( "load", 0 );

		tabs.show();
	}

});
