/**
 * @author David Alpert
 * @author Sara J Chipps
 */
//JS

function validate(url) {


    var re = new RegExp(/^\s*((ht|f)tps?:\/\/)/i);
    if (!url.match(re))
        url = "http://" + url;

    var two = new RegExp(/[a-z]:\/\/\w*\.?\w+\.\w+/i);
    if (url.match(two))
        return true;
    else
        return false;

}
// wrap this in an anonymous closure to avoid naming collisions
//Javascript validation function
function validate(url) {
    var re = new RegExp(/^\s*((ht|f)tps?:\/\/)/i);
    if (!url.match(re))
        url = "http://" + url;
    

    var two = new RegExp(/[a-z]:\/\/\w*\.?\w+\.\w+/i);
    if (url.match(two))
       return true;
    else
      return false;
}


(function($) {
 	
	$(document).ready(function(){

		addItem();

		// -----------------------------------------------------------------
		// attatch event handlers
		//
		
		// handle 'add' clicks
		$('#url_list img.add').live('click', function(ev) {
			save($(this).closest('li')) && addItem();
		});

		// handle 'edit' clicks
		$('#url_list img.edit').live('click', function(ev) {
			hideAddField() && edit($(this).closest('li'));
		});

		// handle 'save' clicks
		$('#url_list img.save').live('click', function(ev) {
			save($(this).closest('li')) && showAddField();
		});

		// handle 'cancel' clicks
		$('#url_list img.cancel').live('click', function(ev) {
		   cancelEdit($(this).closest('li')) && showAddField();
		});

		// handle 'delete' clicks
		$('#url_list img.delete').live('click', function(ev) {
			$(this).closest('li').remove();
			addItem();
		});

		// handle keystrokes
		$('#url_list input').live('keyup', function(ev) {
			var li = $(this).closest('li');
			switch (ev.keyCode) {
				case 13: { // enter
					if (li.is('.add')) {
						save(li) && addItem();
					} 
					else 
					if (li.is('.edit')) {
						save(li);
						showAddField();
					} 
				} break;
				case 27: { // escape
					if (li.is('.add')) {
						$(this).val('');
					} 
					else 
					if (li.is('.edit')) {
						cancelEdit(li);
						showAddField();
					}
				} break;
				default: break;
			}
		});

		// handle 'generate' click
		$('#generate').click(function() {

			  var success = true,
			      includeAddField = true;

			  // if there's only one item it's an add 
			  // so we want to disallow the submit if
			  // it's empty
			  var items = $('#url_list li');
			  if (items.length == 1) {
			  		items = items.eq(0).find('input');
					if (items.val().length == 0) {
						showError('You must add at least one link before generating your capsule.');
						items.focus();
						return;
					}
			  }
			  
			  // attempt to save a pending edit.
			  $('#url_list').find('li.edit, li.add').each(function() {
				  // we can generate a capsule so long as every open url gets saved.
				  // The one exception is an add url can be empty so long as there
				  // is at least one item or edit url to place in the capsule.
				  success = success && save($(this), true);
				  });

			  if (!success) return;

			  // disable the interface
			  $(this).add('li.add, span.commands').hide();

			  // TODO: show a preloader image...

				submitUrls();
				
		 });
    
	});

	// -----------------------------------------------------------------
	// utility methods
	//
	
	var nextUniqueItemID = 1;

   function addItem() {
		var list = $('#url_list'),
			 items = list.find('li');

		// we only want one 'add' box at a time
		if (list.find('li.add').length > 0) {
			// fail silently; the UI will provide necessary cues
			return;
		}

		// we allow a maximum of 10 links
   	if (items.length == 10) {
			// fail silently; the UI will provide necessary cues
			return;
		}

		// build and add the new item
		list.append($('#AddTemplate')
				         .html().replace(/\|rowNumber\|/gi, nextUniqueItemID++));
		list.find('li.add').fadeIn('fast').find('input').focus();
   }

	function hideAddField() {
		$('li.add').hide();
		return true;
	}

	function showAddField() {
		$('li.add').fadeIn('fast').find('input').focus();
		return true;
	}

	function save(item, failSilently)
	{
		var itemID = item.attr('value'),
			 state = item
			 link = item.find('input').val(),
			 success = false;



		if (link.length==0) {
			if (!failSilently) showError(item, "Please enter a URL to bundle.");
			success = false || failSilently;
		} else if (!validate(link)) {
		    if (!failSilently) showError(item, "Sorry, that's not a valid URL. Please try again.");
			success = false || failSilently;
		} else if (link.indexOf('bundl.it') > -1){
			// testing to see if someone is trying to bundle a bundle
		  	if (!failSilently) showError(item, "Hey buster, what are you trying to do there? You can't bundle a bundl!");
			success = false || failSilently;
		} else {
			// input value is okay

		    $('#error-notification').hide();
			if (!(link.match(/^\s*((ht|f)tps?:\/\/)/i))) {link = 'http://'+link;} // if it doesn't start with a proper transport prefix, assume it intends "http://"
			link = link.replace(/^\s*/, ''); // if it starts with empty spaces, trim them.
			link = link.replace(/\s*$/, ''); // if it ends with empty spaces, trim them.

			// generate the template markup
			var linkText = link.length < 37 ? link : link.substr(0, 33)+'...',
				 newItem = $('#ItemTemplate').html();
			newItem = newItem.replace(/\|rowNumber\|/gi, itemID);
			newItem = newItem.replace(/\|itemURL\|/gi, link);
			newItem = newItem.replace(/\|itemText\|/gi, linkText);

			// swap it out with the new one.
			item.replaceWith(newItem);
			
			success = true;
		}
		return success;
	}

	function edit(item) {
		var itemID = item.attr('value'),
			 link = item.find('a').attr('href'),
			 newItem = $('#EditTemplate').html();

		newItem = newItem.replace(/\|rowNumber\|/gi, itemID);
		newItem = newItem.replace(/\|oldValue\|/gi, link);

		item.replaceWith(newItem);

		$('li.edit input').focus().select();
		
		return true;
	}

	function cancelEdit(item) {
		var itemID = item.attr('value'),
			 link = item.find('input').attr('previous'),
			 newItem = $('#ItemTemplate').html();

		newItem = newItem.replace(/\|rowNumber\|/gi, itemID);
		newItem = newItem.replace(/\|itemUrl\|/gi, link);
		newItem = newItem.replace(/\|itemText\|/gi, link);
        
		item.replaceWith(newItem);

		return true;
	}

    function submitUrls(){
		var links = $('#url_list a, #url_list input'), data = [], // to hold the urls
 		    item; // to hold an item
		links.each(function(i){
			item = this.tagName == 'A' ? $(this).attr('href') : $(this).val();
			if (item.length == 0) 
				return;
			// TODO: add other data verification here
			data.push(item);
		});
		
		if (data.length == 0) 
			return false;
		
		data = data.join(',');
		
		$.ajax({
			type: 'POST',
			url: '../Services/GenerateUrl.asmx/AddUrls',
			data: "{ urlEntries: '" + data + "'}",
			contentType: 'application/json; charset=utf-8',
			dataType: 'json',
			success: function(msg){
		    	var previewUrl = "http://bundl.it" + msg.d;
			    $('#results').show(); // kapow!
				$('#capsule').find('a').text(previewUrl).attr("href", previewUrl).end().fadeIn('slow');
			}
		});
	}

    function showError(insertionSelector, msg) {
		var notificationID = 'error-notification',
            div = $('<div id="error-notification"><h2>' + msg + '</h2><p>(click on this box to close)</p></div>'),
            fadeOut = function() {
	            $('#'+notificationID).fadeOut("fast", function() { $(this).remove(); });
	        };

        div.click(function(event) {
            fadeOut();
        });

		$('#'+notificationID).hide();	
        $(insertionSelector).after(div);
        div.fadeIn("fast");

        setTimeout(fadeOut, 1000 * 30);
    }

})(jQuery);

// end closure

