////////////////////////////////////////////////////////////////////////////
$(document).ready(function() {
	// bind button submit
	if ($("#submitButton").length > 0) {
		$("#submitButton").click( function(){
			$(this).parents("form").submit();
			return false;
		});
	}
	
	// Setup tooltip 
	doTooltip();
	
	// round input
	$(".textInput, .selectInput, .textareaInput").addClass("ui-corner-all");
	
	// on focus
	$('.textInput, .selectInput, .textareaInput').focus(function() {
		$(this).addClass('highlightInput');
	});
	
	// out focus
	$('.textInput, .selectInput, .textareaInput').blur(function() {
		$(this).removeClass('highlightInput');
	});
	
	$('#backlinkCode').click(function() {
	    var text = document.getElementById('backlinkCode');
	    if ($.browser.msie) {
	        var range = document.body.createTextRange();
	        range.moveToElementText(text);
	        range.select();
	    } else if ($.browser.mozilla || $.browser.opera) {
	        var selection = window.getSelection();
	        var range = document.createRange();
	        range.selectNodeContents(text);
	        selection.removeAllRanges();
	        selection.addRange(range);
	    } else if ($.browser.safari) {
	        var selection = window.getSelection();
	        selection.setBaseAndExtent(text, 0, text, 1);
	    }
	});
});
$(document).ajaxComplete(function() {
	// Setup tooltip 
	doTooltip();
});
////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////
function formatDisplayNumber(nStr){
	nStr += '';
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}
////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////
function generateStars(percent){

	// How many full stars?
	var fullStars=Math.floor(percent/20);
	
	// How many half stars?
	var halfStars=Math.floor( ( percent-(fullStars*20) ) / 10 );
	
	// How many empty stars
	var emptyStars=5-(fullStars+halfStars);
	
	// Produce output
	var output='';	
	for(var i=1; i<=fullStars; i++){
		output+='<img src="/images/icons/star.png">';
	}
	for(var i=1; i<=halfStars; i++){
		output+='<img src="/images/icons/starHalf.png">';
	}	
	for(var i=1; i<=emptyStars; i++){
		output+='<img src="/images/icons/starEmpty.png">';
	}
		
	return output;
}
////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////
function generateScale(percent){

	var output='';
	
	output+='<div style="border:1px solid #cccccc; height:15px; margin:0 auto; width:100px;">';
	output+='<div style="color:#585858; background-color:#eeeeee; font-size:9px; height:13px; padding-top:2px; width:' + percent + 'px; vertical-align:middle;">' + percent + '%</div>';
	output+='</div>';

	return output;
}
////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////
function shortenString(str, maxLength){
	if(str.length>maxLength){
		str=str.substring(0,maxLength)+"...";
	}
	return str;
}
////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////
function doTooltip(){
	// Handle tooltip
	var title;
	var html;

	$(".tooltip").live({
		mouseover:
			function(e){
				if($('body').data('title')){
					title=$('body').data('title');
				}
				else{
					title=$(this).attr('title');
				}
				
				$('body').data('title', title)
				
				$(this).attr('title','');
				
				if(dictionary(title)!=false){
					html=dictionary(title);
				}
				else{
					html=title.replace("[newline]", "<br>");
				}
				
				$("body").append('<div id="tooltip">'+html+'</div>');
				$("#tooltip")
					.css("top",(e.pageY - 10) + "px")
					.css("left",(e.pageX + 20) + "px")
					.fadeIn("fast"); 
			},
		mouseout:
			function(e){ 
				
				$(this).attr('title', $('body').data('title'));
				$('body').removeData('title')
				$("#tooltip").remove();
			},
		click:
			function(e){
				if (!$(this).attr('href') || $(this).attr('href') == '' || $(this).attr('href') == '#') {
					$("#tooltip").remove();
				}
			}		
	});	
}
////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////
function dictionary(term){

	// Definitions
	var dict= new Array()
	dict["Keyword Density"]="A display url is used within your ad for display purposes only. This is usually just your website address. We use \"EngineSeeker.com\" in our ad."; 
	dict["Search Engine Traffic Summary"]=""; 
	dict["What are Ranking Reports?"]="Our software checks your search engine rankings each day and organizes this information into easy to understand reports.";
	dict["What is Traffic Activity?"]="We track all your search engine traffic to help you measure the success of your optimization efforts.";
	dict["What is the Stats Tracker?"]="In order to track search engine statistics, we place a small piece of javascript code on your website.  If you are free account user, then tracking code will produce a small image advertising our website."; 
	dict["What is Custom Branding?"]="Make our interface look like your own by changing the color scheme and uploading your own logo.  You can also create a personal web address in the form of http://yourbusiness.clientseoreport.com.";
	dict["What are PDF Reports?"]="All of our reports can be exported to a PDF allowing you to email or print them for you clients.";
	dict["What is Client Access?"]="Give your clients direct access to the reports area.  You can simply assign a username and password to a client so they can login to view reports about the seo for their site.";

	// Return false if no def exists
	if(!dict[term]){
		return false
	}
		
	// Set dictionary div
	html='<b>' + term + '</b>';
	html+= dict[term];
	return html;
}
////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////
function floatElement(obj, boundryObj){

	var initialOffset=obj.offset();

    $(window).scroll(function() {
        
        if( (boundryObj.offset().top - obj.height()) < $(window).scrollTop() ){
     		obj.css({
     			/*'position':'static',
     			'marginTop': boundryObj.offset().top - ( obj.height()+initialOffset.top )*/
     			'position':'absolute',
     			'top':boundryObj.offset().top - ( obj.height()+initialOffset.top )
     		});     
     		
     		//console.log('stop at bottom ' +(boundryObj.offset().top - ( obj.height()+initialOffset.top+20)));      
        }
       else if(($(window).scrollTop()+10) > initialOffset.top) {        
    		obj.css({
    			'position':'fixed',
    			'top':'10px',
    			'margin':0
    		});
    		//console.log('float'); 
        } 
        else{        
			obj.css({
				'top' : 0,
				'position':'static',
				'margin':0
			}); 
			//console.log('stay at top');        
        }
    });
    
}
////////////////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////////
function submitForm(jqueryForm, output){
	$.ajax({
		type: $(jqueryForm).attr('method'),
		url: $(jqueryForm).attr('action'),
		data: $(jqueryForm).serialize(),
		beforeSend: function(){
			$(output).html('<center><img src="/images/spinner.gif" style="margin-top:40px;"></center>');
		},
		success: function(response){
			$(output).html(response);
			$.fancybox.resize();
			$.fancybox.center();
			//dialog.dialog('option', 'position', 'center');
		}
	}); 	
}
////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////////////////////////////////		    
function googlePlusOne(){

	// define fb data
	var fbLike='<iframe src="http://www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2FmySEOTool&amp;width=292&amp;colorscheme=light&amp;show_faces=false&amp;border_color&amp;stream=false&amp;header=false&amp;height=62" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:292px; height:62px;" allowTransparency="true"></iframe>';
	
    // create dialog
    var dialog = $('<div id="ajaxDialog" style="display:hidden">We truly appreciate your support. You can also like us on Facebook to stay in Touch!<br><br><center>' + fbLike + '</center></div>').appendTo('body');
    
    // change settings
   	dialog.dialog({
   		width:400,
   		height:200,
		modal:true,
		title:'Thanks for the Google +1',
		close: function(event, ui){ $('#ajaxDialog').remove() },
   	});
    
    // load remote content
    dialog.load(
        url, 
        {},
        function (responseText, textStatus, XMLHttpRequest) {
        	dialog.dialog('option', 'position', 'center');
       		dialog.dialog();
        }
    );

}
////////////////////////////////////////////////////////////////////////////		    

