 


//////////////// BEGIN COMMENTS ////////////////

//Our XmlHttpRequest object to get the auto suggest
var httpReq = getXmlHttpRequestObject();

var entityID = '';
var commentsAvailable = 0;
var typeID = '';

var minR = 0;
var maxR = 12;

var perPage = maxR;

function initComments(entity,type,cAvailable)
{
	entityID 		= entity;
	typeID			= type;
	commentsAvailable = cAvailable;
	
	commentChange(0);
}
function showCommentReply(commentID)
{
	$("#commentDiv_"+commentID).show();
}
function sendComment(replyID)
{
	var rID		= $("#comments_obj_id").val();
	var rTID	= $("#comments_obj_tid").val();
	
	if(!replyID) {
		var msg		= $("#WallCommentArea").val(); alert('um?'); }
		
	else
	{
		var msg	= $("#commentsReply_"+replyID).val();
		alert("Message="+msg);
	}
	
	alert("Passing rid = " + rID + " rTID = " + rTID + " MSG = " + msg );
	return false;
	
	var params	= "rID="+rID+"&rTID="+rTID+"&msg="+msg;
	
	$.ajax({
       type: "POST",
       url: "/ajax/sendComment.php",
       data: params,
       success: function(msg){
         
         alert("Test mode: " + msg );
         initComments(entityID,typeID,commentsAvailable);
       }
    });
}
function deleteComment(cid)
{
	if (httpReq.readyState == 4 || httpReq.readyState == 0) 
	{
		var params = "rm="+cid;
		var url = '/ajax/comments.php';
		
		commentsAvailable -= 1;
		
		httpReq.open("POST", url, false);
		
		httpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		httpReq.setRequestHeader("Content-length", params.length);
		httpReq.setRequestHeader("Connection", "close");
		
		httpReq.onreadystatechange = function() {//Call a function when the state changes.
			if(httpReq.readyState == 4 && httpReq.status == 200) {
				//alert(httpReq.responseText);
				startGrowl("Comment Removed","Your comment has been deleted.");
			}
		}
		httpReq.send(params);
		
		commentChange(0);
	}
}
//Called from link on vehicleProfile
//Starts the AJAX request.
function commentChange(dir) 
{
	var ic = document.getElementById('commentWrapper');
	
	$("#commentWrapper").html("<img src=\"/images/icons/ajax-loader.gif\" alt=\"loading\" />");
	
	try { gradientshadow.position(); }
	catch(err) { }
	
	if (httpReq.readyState == 4 || httpReq.readyState == 0) 
	{
		if(dir != 0)
		{
			$("#commentWrapper").css("min-height",300);;
		}
		if(commentsAvailable > maxR && dir == 0)
		{
			document.getElementById('NextCommentLink').style.display = "block";
		}
		else if(maxR < commentsAvailable && dir == 1)
		{
			minR += perPage;
			maxR += perPage;
			
			document.getElementById('PrevCommentLink').style.display = "block";
			
			if(maxR >= commentsAvailable)
				document.getElementById('NextCommentLink').style.display = "none";
		}
		else if(dir == -1)
		{
			if(minR > 0)
			{
				minR -= perPage;
				maxR -= perPage;
				
				if(minR < 0)
					minR = 0;
				
				if(minR  == 0)
					document.getElementById('PrevCommentLink').style.display = "none";
				
				document.getElementById('NextCommentLink').style.display = "block";
			}
		}
		else
		{
			minR = 0;
			maxR = perPage;
			
			document.getElementById('NextCommentLink').style.display = "none";
			document.getElementById('PrevCommentLink').style.display = "none";
		}	
		
		var url = '/ajax/comments.php?min='+minR+'&max='+maxR+'&entityID='+entityID+'&tid='+typeID;
		
		httpReq.open("GET", url, true);
		httpReq.onreadystatechange = handleCommentChange; 
		httpReq.send(null);
	}
}

//Called when the AJAX response is returned.
function handleCommentChange() 
{
	if (httpReq.readyState == 4) 
	{
		var ic = document.getElementById('commentWrapper');
		var str = httpReq.responseText;
		
		ic.innerHTML = str;
		
		$("#commentWrapper").css("height","auto");
		
		try { gradientshadow.position(); }
		catch(err) { }
	}
}
//////////////// END COMMENTS ///////////////////

function clearNotifications() 
{

	alert("Clearing");
	$("#notifyIcon").src = '/images/icons/mail-black.png';
	$("#notifyMessageCount").val = 'No New Messages';
	alert("Done!");
}
function addValidator(formID) {
	
	$.validator.addMethod("urlsafe", function(value, element) {
		return this.optional(element) || /^[a-z0-9\_]+$/i.test(value);
	}, "Letters,Numbers,and Underscore only");
	
	$("#"+formID).validate();
}
function deleteForumPost(postID,redirURL)
{
	var params = "pid="+postID;
	
	if(!confirmDelete('post'))
		return false;
	
	$.ajax({
       type: "POST",
       url: "/ajax/forum/deletePost.php",
       data: params,
       success: function(msg){
       
       /*
         startGrowl("Post Removed");
         setSuccess("Post Removed");
        */
        
        window.location=redirURL+"&postDeleted=true";
       }
    });
    
    return false;
}
function stripslashes(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\0/g,'\0');
	str=str.replace(/\\\\/g,'\\');
	return str;
}
function setSuccess(message)
{
	$('#notice').removeClass('warningNotice errorNotice');
	$('#notice').addClass('successNotice');
	$('#notice').html(message);
	
	$('#notice').slideDown();
}
function setWarning(message)
{	
	$('#notice').removeClass('successNotice errorNotice');
	$('#notice').addClass('warningNotice');
	$('#notice').html(message);
	
	$('#notice').slideDown();
}
function setError(message)
{
	$('#notice').removeClass('warningNotice successNotice');
	$('#notice').addClass('errorNotice');
	$('#notice').html(message);
	
	$('#notice').slideDown();
}

// Replace w/ jQuery method
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject() {
	if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	} else if(window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		// Old Browser
               return false;
	}
}
// Contains all custom (Site-Wide) SpeedCountry Javascript
function clearSearch(obj) { obj.value = ''; }
function changeBox()
{
	document.getElementById('div1').style.display='none';
	document.getElementById('div2').style.display='';
	document.getElementById('password').focus();
}
function restoreBox()
{
	if(document.getElementById('password').value=='')
	{
		document.getElementById('div1').style.display='';
		document.getElementById('div2').style.display='none';
	}
}
function toggleVisible(obj)
{
	if(obj.style.display != "block")
		obj.style.display = "none";
	else
		obj.style.display = "block";
}
function toggleSlide(objname)
{
    var sdiv = document.getElementById(objname);

      if(sdiv.style.display == "none")
        $("#"+objname).show("clip", { direction: "right" }, 1000);

      else
        $("#"+objname).hide("clip", { direction: "left" }, 1000);
        
    try {
            gradientshadow.position();
             
        } catch(err) { }
}
function toggleVisible(objname)
{
    var sdiv = document.getElementById(objname);

      if(sdiv.style.display == "none")
        sdiv.style.display = "block";

      else
        sdiv.style.display = "none";

    try {
            gradientshadow.position();
        } catch(err) { }

}

minus = new Image();
minus.src = '/images/icons/plus.gif';

function toggleImage(number)
{
	if (document.getElementById(number).src.match('/images/icons/plus.gif')) {
	document.getElementById(number).setAttribute('src', '/images/icons/minus.gif');
	}
	else {
	document.getElementById(number).setAttribute('src', '/images/icons/plus.gif');
	}
}
function confirmDeletePhotos()
{
    var response = confirm("Really Delete photos?");

    return response;
}
function confirmDelete(message)
{
	confirm = prompt("Type delete to permanently remove this "+message+":");
	
	if(confirm == "delete")
		return true;
		
	return false;
	
	//return(confirm("Permenantly delete this "+ message + "? This cannot be undone."));
}
function startUploadify(typeID,eID) {
	$("#uploadify").uploadify({
                            'uploader'       : '/lib/uploadify/example/scripts/uploadify.swf',
                            'script'         : '/lib/uploadify/scripts/singleAvatarUpload.php?typeID='+typeID+'%26objID='+eID,
                            'cancelImg'      : '/lib/uploadify/example/cancel.png',
                            'folder'         : 'uploads',
                            'auto'           : true,
                            'multi'          : false,
                            'buttonText'     : 'Change Image',
                            'scriptData'     : { PHPSESSID: '93e9c1f7617dfd01938e084500eed206'},
                            'onComplete'	 : function(a, b, c, d, e) { location.reload(true); } });
}
function startAjaxUpload(typeID,eID)
{
	var button = $('#uploader'), interval;
		
	new AjaxUpload(button, {
		action: '/lib/uploadify/scripts/singleAvatarUpload.php?typeID='+typeID+'%26objID='+eID, 
		name: 'profilePicture',
		onSubmit : function(file, ext){
						
			button.text('Uploading'); // change button text, when user selects file
								
			// If you want to allow uploading only 1 file at time,
			// you can disable upload button
			this.disable();
				
			// Uploding -> Uploading. -> Uploading...
			interval = window.setInterval(function(){
				var text = button.text();
				if (text.length < 13){
					button.text(text + '.');					
				} else {
					button.text('Uploading');				
				}
			}, 200);
		},
		onComplete: function(file, response){
		
			alert('REDIRECTING!');
			
			location.reload(true);
			button.text('Upload');
							
			window.clearInterval(interval);
							
			// enable upload button
			this.enable();
			
			// add file to the list
			$('<li></li>').appendTo('#example1 .files').text(file);						
		}
	});
}
function toggleStates()
{
    var states = document.getElementById('stateField');

    if(document.getElementById('countryField').value != 'US')
        states.disabled = true;

    else
        states.disabled = false;
}
function startGrowl(growlHeader,growlMsg,pos)
{
	growlHeader = growlHeader;
	growlMsg = growlMsg;
	try
	{
 		if(growlMsg != "" )
    		$.jGrowl(growlMsg, {
        		position: pos,
        		header: growlHeader,
        		life: 4500,
        		theme:  'manilla'
        	});
     }
     catch(err) {
     
		// Growl hasn't been declared yet... 
		//location.reload(true); 
	}
}
function hideAttributes()
{
    $(".attributeSlider").hide();
}

//
// User Tools Menu
//
		jQuery(function( $ ){
			var menuRoot = $( "#menu-root" );
			var menu = $( "#menu" );
            
            var menuRoot2 = $( "#menu-root2" );
			var menu2 = $( "#menu2" );

            var menuRoot3 = $( "#menu-root3" );
			var menu3 = $( "#menu3" );
			
			var menuRoot4 = $( "#menu-root4" );
			var menu4 = $( "#menu4" );
            
			// Hook up menu root click event.
			menuRoot
				.attr( "href", "javascript:void( 0 )" )
				.click(
					function()
                    {
						menu.toggle();
						menuRoot.blur();
 
						return( false );
					});
            
            menuRoot2
				.attr( "href", "javascript:void( 0 )" )
				.click(
					function(){
                  
						menu2.toggle();
						menuRoot2.blur();
 
						return( false );
					});
            menuRoot3
				.attr( "href", "javascript:void( 0 )" )
				.click(
					function(){
                  
						menu3.toggle();
						menuRoot3.blur();
 
						return( false );
					});
            menuRoot4
				.attr( "href", "javascript:void( 0 )" )
				.click(
					function(){
                  
						menu4.toggle();
						menuRoot4.blur();
 
						return( false );
					});

			$( document ).click
            (
				function( event )
                {
					if (menu.is( ":visible" ) && !$( event.target ).closest( "#menu" ).size())
                    {
							menu.hide();
					}
                    if (menu2.is( ":visible" ) && !$( event.target ).closest( "#menu2" ).size())
                    {
						menu2.hide();
					}
                    if (menu3.is( ":visible" ) && !$( event.target ).closest( "#menu3" ).size())
                    {
						menu3.hide();
					}
					if (menu4.is( ":visible" ) && !$( event.target ).closest( "#menu4" ).size())
                    {
						menu4.hide();
					}


				}
			);
 
		});
// Check all feature
checked=false;
function checkedAll (images) {
	var aa= document.getElementById('images');
	 if (checked == false)
          {
           checked = true
          }
        else
          {
          checked = false
          }
	for (var i =0; i < aa.elements.length; i++) 
	{
	 	aa.elements[i].checked = checked;
	}
      }
function stateChange(defaultState)
{
	var i=0;
	
	while ((document.settingsForm.stateField.options[i].value != defaultState) && (i < document.settingsForm.stateField.length))
		i++;
        
	if (i < document.settingsForm.stateField.options.length)
	{
		document.settingsForm.stateField.selectedIndex = i;
	}
}
function replaceFCK(editorName,toolSet, height)
{
	var oFCKeditor = new FCKeditor( editorName ) ;
	oFCKeditor.Height = height;
	oFCKeditor.BasePath = "/lib/fckeditor/" ;
	oFCKeditor.ToolbarSet	= toolSet ;
	oFCKeditor.replaceClass = 'ckeditor';
	
	oFCKeditor.ReplaceTextarea() ;
}
function replaceCKEditor(editorName, height)
{
	var editors = document.getElementsByName(editorName);
	
	for(var i in editors)
	{	
		try {
		
			CKEDITOR.replace( editors[i].id,
			{
				height: height + 'px',
				toolbar :
				[
					[ 'Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-'],
					[ 'UIColor' ,'Smiley','Image']
				]
			});
		}
		catch(err) { }
	}
}
function validateRequired(field,alerttxt)
{
with (field)
  {
  if (value==null||value=="")
    {
    alert(alerttxt);return false;
    }
  else
    {
    return true;
    }
  }
}
/*
function validateForm(thisform)
{
with (thisform)
  {
	  if (validateRequired(firstnameField,"First Name must be filled out!")==false)
	  	{nameField.focus();return false;} 
		
	  if (validateRequired(lastnameField,"Last Name must be filled out!")==false)
	  	{nameField.focus();return false;}  
		
	  if (validateRequired(userRegisterField,"Username must be filled out!")==false)
  		{userRegisterField.focus();return false;}
	  
	  if (validateRequired(emailField,"Email must be filled out!")==false)
	  	{emailField.focus();return false;}
		
	  if (validateEmail(emailField,"Not a valid email address!")==false)
                {emailField.focus();return false;}
	  
	  if (validateRequired(pass1Field,"Password must be filled out!")==false)
  		{pass1Field.focus();return false;}
		
	  if (validateRequired(pass2Field,"The Password Retype Field must be filled out!")==false)
  		{pass2Field.focus();return false;}
        
	  if (validateRequired(termsBox,"You Must Agree to our terms of service")==false)
  		{termsBox.focus();return false;}
  }
}*/

// jQuery tooltip bar
function tooltip()
{
    //Select all anchor tag with rel set to tooltip
    $('a[rel=tooltip]').mouseover(function(e) {
        
        //Grab the title attribute's value and assign it to a variable
        var tip = $(this).attr('title');	
        
        //Remove the title attribute's to avoid the native tooltip from the browser
        $(this).attr('title','');
        
        //Append the tooltip template and its value
        $(this).append('<div class="tooltip"><div class="tipBody">' + tip + '</div></div>');	
                
        //Show the tooltip with faceIn effect
        $('.tooltip').fadeIn('500');
        $('.tooltip').fadeTo('10',0.9);
        
    }).mousemove(function(e) {
    
        //Keep changing the X and Y axis for the tooltip, thus, the tooltip move along with the mouse
        //$('.tooltip').css('top', e.pageY + 10 );
        //$('.tooltip').css('left', e.pageX + 20 );
        
    }).mouseout(function() {
    
        //Put back the title attribute's value
        $(this).attr('title',$('.tipBody').html());
    
        //Remove the appended tooltip template
        $(this).children('div.tooltip').remove();
        
    });
}

function addFriend(friendID,handler)
{	
	if(friendID == 0 || friendID == "")
		return false;
		
	var params = "friendID="+friendID;
	var grwlMsg = "You are now friends";
	
	$.ajax({
       type: "POST",
       url: "/ajax/addFriend.php",
       data: params,
       success: function(msg){
         
         if(handler != "")
         	grwlMsg += " with "+handler;
         	
         startGrowl(grwlMsg);
       }
    });
    
    return false; // Done to avoid submission
}

function clearNotifications()
{
	$.ajax({type:"POST",url:"/ajax/resetNotifications.php"});
}
function handlerExists(handler)
{
	alert("CALLED WITH " +handler);
	if(handler == '')
		return false;
		
	var params = "handler="+handler;
	
	$.ajax({
       type: "POST",
       url: "/ajax/handlerExists.php",
       data: params,
       success: function(msg){
       
         alert("Response: "+msg);

       }
    });
}
function hideAndSlide(divID) // unfinished
{
	var div = '#'.divID;
	
	$(div).hide();
	
	$(div).slideDown('slow');	
}
function sendClubInvitation(clubID,toID,handler)
{
	var params = "clubID="+clubID+"&userID="+toID;
	
	$('#invite_link_'+toID).removeAttr('onclick');
	 $('#invite_status_'+toID).html('<img src="/images/icons/ajax-loader-small.gif" alt="Sending Invitation" />');
	
	$.ajax({
       type: "POST",
       url: "/ajax/sendClubInvitation.php",
       data: params,
       success: function(msg){
         
        
        $('#invite_status_'+toID).html("Invite Sent");
        
         if(handler != "")
         	grwlMsg = handler+" Invited!"
         	
         setSuccess(grwlMsg);
       },
       error: function(msg) { setError("Error: "+msg); }
    });
    
    return false;
}

//
// BEGIN RATING //
// 
/*
Author: Addam M. Driver
Date: 10/31/2006
*/

var sMax;	// Isthe maximum number of stars
var holder; // Is the holding pattern for clicked state
var preSet; // Is the PreSet value onces a selection has been made
var rated;

function submitRating(val)
{
    if(val > 0 && val < 6)
    {
            location.href = location.href + '&rate=' + val;
    }
}
// Rollover for image Stars //
function onRating(num){
    sMax = 0;	// Isthe maximum number of stars
    for(n=0; n<num.parentNode.childNodes.length; n++){
            if(num.parentNode.childNodes[n].nodeName == "A"){
                    sMax++;
            }
    }

    if(!rated){
            s = num.id.replace("_", ''); // Get the selected star
            a = 0;
            for(i=1; i<=sMax; i++){
                    if(i<=s){
                            document.getElementById("_"+i).className = "on";
                            document.getElementById("rateStatus").innerHTML = num.title;
                            holder = a+1;
                            a++;
                    }else{
                            document.getElementById("_"+i).className = "";
                    }
            }
    }
}

// For when you roll out of the the whole thing //
function offRating(me){
	if(!rated){
		if(!preSet){	
			for(i=1; i<=sMax; i++){		
				document.getElementById("_"+i).className = "";
				document.getElementById("rateStatus").innerHTML = me.parentNode.title;
			}
		}else{
			rating(preSet);
			document.getElementById("rateStatus").innerHTML = document.getElementById("ratingSaved").innerHTML;
		}
	}
}

// When you actually rate something //
function rateIt(me){
	if(!rated){
		document.getElementById("rateStatus").innerHTML = document.getElementById("ratingSaved").innerHTML + " :: "+me.title;
		preSet = me;
		rated=1;
		sendRate(me);
		rating(me);
	}
}
// Used on News Feed to switch between news feed
function toggleFriends(){
	$('.Similar').hide();
	$('.Friends').show("Fast");
	
	$('.SimilarIMG').hide();
	$('.FriendsIMG').show();

	$('.FriendsMenu').css("color","black");
	$('.SimilarMenu').css("color","#41A0E8");
}
function toggleSimilar(){
	$('.Friends').hide();
	$('.Similar').show("Fast");
	
	$('.FriendsIMG').hide();
	$('.SimilarIMG').show();
	
	$('.SimilarMenu').css("color","black");
	$('.FriendsMenu').css("color","#41A0E8");
}
	$("#search-box").autocomplete("ajax/searchSuggest2.php", {
		width: 320,
		max: 4,
		highlight: false,
		scroll: true,
		scrollHeight: 300,
		formatItem: function(data, i, n, value) {
			return "<img src='images/" + value + "'/> " + value.split(".")[0];
		},
		formatResult: function(data, value) {
			return value.split(".")[0];
		}
	});
// Send the rating information somewhere using Ajax or something like that.
function sendRate(sel){
	alert("Your rating was: "+sel.title);
}
//
// END RATING SYSTEM //
//

// Edit Forum Post Script //

