/*
 * 	 imDomainSearch - A JQuery Plugin
 * 	 @author Les Green
 * 	 Copyright (C) 2009 Intriguing Minds, Inc.
 *   Version 0.5
 * 
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.

 *   Demo and Documentation can be found at:   
 *   http://www.grasshopperpebbles.com
 *   
 */
 
;(function($) {
	$.fn.extend({
        imDomainSearch: function(options) { 
        	opts = $.extend({}, $.imDSearch.defaults, options);
			return this.each(function() {
				new $.imDSearch(this, opts);
			});
        }
    });	

$.imDSearch = function(obj, opts) {
	var $this = $(obj);
	var arCats = new Array();
	var arWeb20 = new Array();
	
	doAjax('GET', opts.web2_url, '', '', addWeb20);
	
	function addWeb20(data) {
		$.each(data, function(i, itm) {
			arWeb20[itm.name] = itm.label;
		});
		createSearch();
	};
		
	function createSearch() {
		var ch = '';
		var n = '';
		var checkText = '';
		var aCheck = ['com','org','net'];
		var arr = opts.tlds;
		arr = arr.split(',');
		if (opts.tlds) {
			$.each(arr, function (i, itm) {
				checkText = ($.inArray(itm, aCheck) >= 0) ? ' checked="checked"' : '';
				ch += '<input type="checkbox" id="'+itm+'" name="' + itm + '" value="' + itm + '"'+ checkText +' /><label for="'+itm+'">.'+itm+'</label>';
			});
		}
		$this.append($('<div></div>').attr("id", 'suggestCntnr').css('background-color','#ffffff').append(
					
					$('<div></div>').attr("id", 'suggestFields').append(
					$('<label></label>').html('Name:'),
					$('<input type="text" name="tSuggest" id="tSuggest" />'),
					$('<label></label>').html('Category:'),
					$('<select name="cbCategory" id="cbCategory"></select>'),
					$('<button></button>').attr('id', 'btnSearch').attr('class','fg-button ui-state-default ui-corner-all').append('Suggest')),
					$('<div></div>').attr("id", 'suggestResults').append(
					$('<p></p>').html('Enter a name and select a category to view a list of domain names'))
				
				),
		$('<h3></h3>').attr('class', opts.searchText.class_name).html(opts.searchText.caption),
				
				$('<form action="'+ opts.search_url +'" method="post" name="'+opts.searchForm+'" id="'+opts.searchForm+'"></form>')
				.append(
				    $('<div></div>').attr("id", opts.searchCntnr).append(
					$('<input type="text" name="'+opts.domainName+'" id="'+opts.domainName+'"  />'),
					$('<a href="#" id="'+opts.submitBtn+'"></a>')))
					
				.append($('<div></div>').attr("id", opts.searchOptions).append(
				
				$('<button></button>').attr('id', 'btnGenerate').attr('class','fg-button ui-state-default ui-corner-all').append('Web 2.0'),
				$('<button></button>').attr('id', opts.optionsBtn).attr('class','fg-button ui-state-default ui-corner-all')
				            //.append($('<span></span>').attr('class','ui-icon ui-icon-newwin'))
				            .append('Suggest'),
				(' Click <strong>Web 2.0</strong> to generate a Web 2.0 Domain Name. Click <strong>Suggest</strong> for more options.')))
				//$('<div></div>').attr("id", 'otherOptions')
				//.append($('<button></button>').attr('id', opts.optionsBtn).attr('class','fg-button ui-state-default ui-corner-all')
				            //.append($('<span></span>').attr('class','ui-icon ui-icon-newwin'))
				 //           .append('More Options'))
				//))	
				.append($('<div></div>').attr("id", opts.tldCntnr).append($(ch)))
				.append($('<div></div>').attr("class", opts.errorResponse))
				.append($('<div></div>').attr("class", 'ajaxLoader'))
				
				.append($('<div></div>').attr("id", opts.optionsDialog).attr("title", "Web 2.0")
				    		.append($('<iframe></iframe>').attr("id", "popupUrban").css({'width': "100%",'height':'350px'})
				    		)));      
						
				$('#'+opts.submitBtn).click(function() {
					doSearch();
				});
				/*$("#"+opts.domainName).keypress(function (e) {
					if (e.which == '13') {
						e.preventDefault();
						doSearch();
					}
				});*/
				
		//var mL = (parseInt($this.css('width')) - parseInt($('#'+opts.searchCntnr).css('width')))/2 + 'px';
		//console.log($this.innerWidth());
		//console.log($('#'+opts.searchCntnr).innerWidth());
		var mL = ($this.innerWidth() - $('#'+opts.searchCntnr).innerWidth())/2 + 'px';
		$('#'+opts.searchCntnr).css('margin-left', mL);
		$('#'+opts.tldCntnr).css('margin-left', mL);
		$('#'+opts.searchOptions).css('margin-left', mL);
		$('.'+opts.errorResponse).css('margin-left', mL);
		//var mL = (parseInt($this.css('width')) - parseInt($('#suggestCntnr').css('width')))/2 + 'px';
		var mL = ($this.innerWidth() - parseInt($('#suggestCntnr').css('width')))/2+ 'px';
		$('#suggestCntnr').css('margin-left', mL);
		if (opts.showOptions) {
			$('#'+opts.searchOptions).css('display', 'block');
			$('#btnGenerate').click(function(e) {
				e.preventDefault();
				doWeb20();
			});
			opts.uiDialogOptions = {
				autoOpen: false,
				modal: true,
				bgiframe: true,
				width: 700,
				buttons: {
					"close":function() {
							$(this).dialog("close");
					} 
				},
				title:'Urban Dictionary'
			};
			
			$('#'+opts.optionsDialog).insertAfter($this).dialog(opts.uiDialogOptions);

			$('#'+opts.optionsBtn).hover(
				function() { $(this).addClass('ui-state-hover'); }, 
				function() { $(this).removeClass('ui-state-hover'); }
			);
			$('#btnGenerate').hover(
				function() { $(this).addClass('ui-state-hover'); }, 
				function() { $(this).removeClass('ui-state-hover'); }
			);
			$('#btnSearch').hover(
				function() { $(this).addClass('ui-state-hover'); }, 
				function() { $(this).removeClass('ui-state-hover'); }
			);

			$('#btnSearch').click(function() {
				suggest();
				return false;
			});
			$('#'+opts.optionsBtn).toggle(
				function(){
					$('#suggestCntnr').slideDown('slow');
					$(this).html('Close');
				},
				function() {
					$('#suggestCntnr').slideUp('slow');
					$(this).html('Suggest');
				}
			);
			
			doAjax('GET', opts.category_url, '', '', addCategories);
		}
	};
	
	function addCategories(result) {
		$.each(result, function(i, itm) {
			$('#cbCategory').append($('<option value="'+i+'">'+itm.name+'</option>'));
			arCats[i] = itm.label;
		});
	};
	
	function suggest() {
		if ($('#tSuggest').val() != '') {
			var n = $('#cbCategory')[0].selectedIndex;
			var cats = arCats[n];
			cats = cats.split(',');
			var catName = $('#cbCategory')[0].options[n].text;
			$('#suggestResults').empty();
			$.each(cats, function(i, itm) {
				$('#suggestResults').append($('<h3></h3>').html($('#tSuggest').val() + itm+ '<br />').data('category',{'label': itm}));
				$('#suggestResults').append($('<h3></h3>').html(itm + $('#tSuggest').val() + '<br />').data('category',{'label': itm}));
			});
			$('#suggestResults h3').click(function() {
				var v = $(this).html();
				var d = $(this).data('category').label;
				//<br> is at the end of each name
				v = v.split('<');
				$("#"+opts.domainName).val(v[0]);
				if (catName == 'urban dictionary') {
					$('#popupUrban').attr('src','http://www.urbandictionary.com/define.php?term='+d);
					$('#'+opts.optionsDialog).dialog('option', 'title', d);
					$('#'+opts.optionsDialog).dialog('open');
				}
				return false;
			});
		}
	};
	
	function doSearch() {
		$('.'+opts.errorResponse).css('display','none').html('');
		var e = checkDomainName($('#'+opts.domainName).val()); 
		if (e) {
			$('.'+opts.errorResponse).css('display','block').html(e);
		} else {
			$('.'+opts.domainResponse).remove();
			$('.ajaxLoader').show();
			var formData = getFormValues($('#'+opts.searchForm));
			doAjax('POST', opts.search_url, formData, '', showDomainInfo);
		}
	};
	
	function checkDomainName(dVal) {
		var rVal = ''
		var re = /^-|-$/;
		var hyphen = re.test(dVal);
		var re = /[0-9a-zA-Z]/;
		// /[\D\W]/
		var alphanum = re.test(dVal);
		if (!dVal) {
			rVal = 'You must enter a domain name';
		} else if (hyphen) {
			rVal = 'Domain Name cannot begin or end with a hyphen';
		} else if (!alphanum) {
			rVal = 'Domain name cannot contain special characters';
		} else if (dVal.length < 3) {
			rVal = 'Domain Name is too short';
		} else if (dVal.length > 57) {
			rVal = 'Domain Name cannot exceed 57 characters';
		}
		return rVal; 
	};
	
	function getFormValues(form) {
		var str = "";
		$(':input', form).each(function(i) {	
			if ((this.type == 'radio') || (this.type == 'checkbox')) {
				if (this.checked) {
					str += this.name + "=" + escape(this.value) + "&";		
				}
			} else {
				str += this.name + "=" + escape(this.value) + "&";
			}
		});
		str = str.substr(0, str.length-1);
		return str;
	};
	
	function doAjax(t, u, d, fnBefore, fnSuccess) {
		$.ajax({
			type: t,
			url: u,
			data: d,
			dataType: 'json',
			beforeSend: fnBefore, //function(){$("#loading").show("fast");}, //show loading just when link is clicked
			//complete: function(){ $("#loading").hide("fast");}, //stop showing loading when the process is complete
			success: fnSuccess,//{ //so, if data is retrieved, store it in html
			error: showError
	 	}); //close $.ajax(
	};
	
	function showError(XMLHttpRequest, textStatus, errorThrown) {
		console.log(textStatus);
	};
	
	function showDomainInfo(data) {
		var re = /not/;
		var rCntnr = $('<div></div>').attr("id", 'domainResultCntnr');
		var dI =$('#'+opts.domainName).val();
		$('.ajaxLoader').hide();
		$.each(data, function(i, itm) {
			var notAvail = re.test(itm.value);
			if (notAvail) {
				$(rCntnr).append(
					$('<div></div>').attr("class", opts.domainResponse + ' ui-corner-all').append(
					$('<p></p>').attr('class','headerText ui-state-default ui-corner-top').html(itm.name +' '+itm.value),
					$('<a href="http://www.'+dI+itm.name+'" target="_blank">Vist Website</a><br />'),

					//$('<a href="http://www.alexa.com/siteinfo/"'+dI+itm.name+'" target="_blank">Alexa</a><br />'),
					$('<p></p>').html('Page Rank: ' +itm.rank),
					$('<p></p>').html('Alexa Rank: ' +itm.alexa),
					$('<p></p>').html('Google Backlinks: ' +itm.google),
					$('<p></p>').html('Yahoo Backlinks: ' +itm.yahoo),
					$('<p></p>').html('Bing Backlinks: ' +itm.bing),
					$('<a href="http://www.whois.net/whois/"'+dI+itm.name+'" target="_blank">Whois</a><br />'),
					$('<a href="http://www.alexa.com/siteinfo/"'+dI+itm.name+'#trafficstats" target="_blank">Alexa Overview</a>')));
			} else {
				$(rCntnr).append(
					$('<div></div>').attr("class", opts.domainResponse + ' ui-corner-all').append(
					$('<p></p>').attr('class','headerText ui-state-default ui-corner-top').html(itm.name +' '+itm.value),
					$('<br />'),
					$('<p></p>').html('Register:'),
					$('<a href="http://www.godaddy.com" target="_blank">Godaddy.com</a><br />'),
					$('<a href="http://www.networksolutions.com" target="_blank">Network Solutions</a><br />'),
					$('<a href="http://www.register.com" target="_blank">Register.com</a><br />'),
					$('<a href="http://smallbusiness.yahoo.com/domains/" target="_blank">Yahoo Small Business</a>')));				
			}	
		});
		$(rCntnr).appendTo($this);
	};

	function doWeb20() {
		var prefix = arWeb20['prefix'];
		prefix = prefix.split(',');
		prefix = prefix[ doRand(prefix.length) ];
		
		var suffix = arWeb20['suffix'];
		suffix = suffix.split(',');
		suffix = suffix[ doRand(suffix.length) ];
		
		$("#"+opts.domainName).val(prefix+suffix);
	};
	
	function doRand(num) {
 		return Math.floor(Math.random() * num );
	};

};

/*http://services.digg.com/1.0/stories?domain=doitmyway.net&type=json&appkey=b7d0040e8dedbd88f5a39291ae30ff0b
	
	$(document).ready(function(){
  var tweeturl = "http://twitter.com/status/"
      +"user_timeline/sitepointdotcom.json?count=5"
      +"&callback=?";
  $.getJSON(tweeturl, function(data){
    //read the JSON data here...  
  });
});
	
	<script type="text/javascript">
//the callback -- what do we do with the json response?
function get_delicious_count(info) { 
	//get the number of saves
	var num = info[0].total_posts
	//if none, do nothing
	if(!num) return;
	//if some, I add the number to the end of my link, like at the top of every one of my article posts.
	return $('delic').set({ 
		'text': $('delic').get('text') + ' (' + num + ')',
		'title': num + ' people found this post delicious!'
	});
}
</script>


<script src='http://badges.del.icio.us/feeds/json/url/data?url=http://davidwalsh.name/delicious-url-count-javascript&callback=get_delicious_count'></script>
*/	

$.imDSearch.defaults = {
	search_url: '',
	searchText: {"class_name": "searchText", "caption":"Type Your Domain Name Below"},
	searchCntnr: 'domainSearchCntnr',
	searchForm: 'frmSearch',
	domainName: 'domainName',
	submitBtn: 'domainBtn',
	tldCntnr: 'tldCntnr',
	tlds: 'com,net,org,info,biz,us,ca,co.uk,me,mobi,tv',
	domainResponse: 'domainResponse',
	errorResponse: 'errorResponse',
	domainGenCntnr: 'domainGenCntnr',
	showOptions: false,
	searchOptions: 'searchOptions',
	optionsBtn: 'optionsBtn',
	optionsDialog: 'optionsDialog',
	uiDialogOptions: '',
	web2_url: '',
	category_url: ''
};
})(jQuery);		   
